0

The below code in Java throws Null pointer exception.

public class New{
  int i;

  New(int i)
  {
    this.i = i;
  }

  public void func(New temp)
  {
     temp.i = 10;
     temp = new New(20);
  } 

  public static void main(String[] args)
  {
     New n = null;
     n.func(n);
     System.out.println("value "+ n.i);
  }
}

The reason being, java passes objects references by value. If I wanted to return one object, then I can return it from the function.

But, If I have multiple objects, the only way I could return the object references is, by keeping them into another object, like having some container which has references to all the objects.

Is there a better way to do it?

In C++, I normally just pass the address of pointer to handle this scenario. If I wanted to just return two objects of a single type, creating a container and passing it is a over kill.

What is the problem with returning multiple objects from a function? Why cannot the semantics of the function in all these languages be changed?

3
  • 1
    Shouldnt it be New n=new New(); instead of New n=null;?? Commented Mar 7, 2010 at 5:38
  • Obviously its not a homework question. Commented Mar 7, 2010 at 5:40
  • Hey Zaki, I could actually return the object from the function, but I am worried about the case, where I have to return multiple objects. Commented Mar 7, 2010 at 5:40

3 Answers 3

2

Most often you create an object to hold the combination of objects you want to return.

For a more general-purpose solution, you can either return a collection, and array or some sort of tuple, such as Pair, Triple, etc (the latter you will need to create).

Note, you don't generally pass a mutable object as a parameter, but return an immutable one:

public Pair<Integer,Integer> getLowHighTemp() {
    int                        low,hgh;

    // do stuff... 
    return new Pair(low,hgh);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

This is more of 2 questions than one.

Firstly the problem with your code is that you are not declaring n before you use it. That is throwing the exception.

Secondly if you would like to return 2 objects, you need to have a container object that will hold 2 objects.

Comments

0

You can return some kind of Collection. Returning a Map or List is pretty common.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.