64

Consider a Java String Field named x. What will be the initial value of x when an object is created for the class x;

I know that for int variables, the default value is assigned as 0, as the instances are being created. But what becomes of String?

ROMANIA_engineer
  • 51,252
  • 26
  • 196
  • 186
Selvin
  • 12,013
  • 16
  • 58
  • 79
  • 1
    Have a look at the doc http://download.oracle.com/javase/tutorial/java/data/strings.html – UpCat Mar 22 '11 at 09:42

5 Answers5

120

It's initialized to null if you do nothing, as are all reference types.

duffymo
  • 299,921
  • 44
  • 364
  • 552
  • 3
    why it is not assigning as Empty String ""? Does Integer also become null? – Selvin Mar 22 '11 at 09:40
  • 36
    @selvin: yes, `Integer` will be `null` as well. As the answer says: **all** reference types will be `null`. `int` however, which is a primitive type and thus not a reference type, will be `0`. – Joachim Sauer Mar 22 '11 at 09:42
26

That depends. Is it just a variable (in a method)? Or a class-member?

If it's just a variable you'll get an error that no value has been set when trying to read from it without first assinging it a value.

If it's a class-member it will be initialized to null by the VM.

Dexter
  • 2,982
  • 5
  • 29
  • 32
15

There are three types of variables:

  • Instance variables: are always initialized
  • Static variables: are always initialized
  • Local variables: must be initialized before use

The default values for instance and static variables are the same and depends on the type:

  • Object type (String, Integer, Boolean and others): initialized with null
  • Primitive types:
    • byte, short, int, long: 0
    • float, double: 0.0
    • boolean: false
    • char: '\u0000'

An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.

Once the array is created all of its elements are assiged with the default type value. For example:

private boolean[] list; // default value is null

private Boolean[] list; // default value is null

once is initialized:

private boolean[] list = new boolean[10]; // all ten elements are assigned to false

private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)
Milo P
  • 1,285
  • 2
  • 33
  • 37
Carlos Caldas
  • 756
  • 10
  • 11
10

The answer is - it depends.

Is the variable an instance variable / class variable ? See this for more details.

The list of default values can be found here.

nikhil500
  • 3,406
  • 18
  • 22
5

Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.

developer
  • 9,309
  • 29
  • 85
  • 144