Question

What is the value of a primitive type prior to an assignment?

What I'd like to do is have a variable that, if set, returns whatever its set to and if not returns null. I recognise that the below is a stupid way of doing it, and I've already solved the problem. However, in thinking about it I realised that I didn't know how primitive types acted prior to assignment and a quick Google didn't show anything. So this is more about answering that question than about finding a better way of solving the problem.

for example:

public class Something{
  int value;
  public Something(){
    //irrelevant stuff
  }

  public int getValue(){
    return value;
  }
}

public class SomeOtherClass{
  public SomeOtherClass(){
    Something s = new Something();
    System.out.println(s.getValue);
  }
}

What would be shown?

Was it helpful?

Solution

An integer class member is initialized by default to 0, if you don't explicitly initialize it yourself.

See http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5 from the language specification.

OTHER TIPS

and in code it is s.getValue() its a method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top