Vikjan
Vikjan

Reputation: 43

How to return 2 Strings in one method: String example(String firstName, String secondName)

Public class Example1
{

    String fullname(String firstName, String secondName)
    {
        return firstName,secondName;
        //return fullname(firstName,secondName); doesn't work either :(
    }

    public static void main(String[] args) 
    {
        Example1 myname=new Example();
        System.out.println(myname.fullname("John", "Wick");
    }
}

I got an error though, when I run my program. Can you help me out please guys? thanks a lot

Upvotes: 1

Views: 32307

Answers (4)

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

You cannot return 2 strings at a time. You can use String array though like this:

 public String[] fullname(String firstName, String secondName){

      String[] names = new String[2];
      names[0] = firstName;
      names[1] = secondName;
      return names;
 }

Another logical way to solve this issue is to concatenate both of them and split them.

You can use also use list

 List<String> nameList =  new ArrayList<String>();
 nameList.add(firstName);

and get the elements like nameList.get(0) and so on

You can use

 Map<String,String> nameMap = new HashMap<String,String>();
 nameMap.put("firstName",firstName);
 nameMap.put("secondName",secondName);

There are a number of ways to use data structures to solve this issue.

Upvotes: 5

Raj
Raj

Reputation: 1965

Well you have three options

  1. concatenate the strings and return as a single string. Split the string at the receiving end.

  2. Return String array

  3. Return an object . ie set the two srings to two member variables and return the object.

Upvotes: 2

HJK
HJK

Reputation: 1382

A method could return only one value at a time. Either concatenate the both the strings and return or you could use a class. set the details and return the instance of that class

Approach 1:

 return firstname+"|"+secondname;

If you want those separate in calling method just use return_value.split("|"). Now you get a array of strings with 2 elements, firstname and secondname

Approach 2:

Create a class like

 public class Person{
   private String firstName;
   private String secondName;
   public Person(String fname, String sname){
      firstname = fname; 
      secondname = sname;
    }
   // getter setters
 }

in the method do

 Person p = new Person(firstname, secondname);
 return p;

Upvotes: 5

Eran
Eran

Reputation: 393946

A method has a single return type, so unless you package the two Strings in some class and return that class (or put the two Strings in a String array or some other container of Strings), you can only return one String.

If your only requirement is to display the full name as a single String, you can simply concatenate the two Strings :

String fullname (String firstName, String secondName) 
{
    return firstName + " " + secondName;
}

Upvotes: 2

Related Questions