A K
A K

Reputation: 737

In java, why uninitialized char is OK but not String

In the following code, I get a compilation error if I leave the String name uninitialized, but the char initial has no problem being left uninitialized. Why is this difference in behaviour?

class Demo {
    public static void main(String[] args) {
        char initial;
        String name;
        for (String input: args) {
            name += input;
            initial = input.charAt(0);
            System.out.print(initial + " ");
        }
    }

Upvotes: 2

Views: 527

Answers (4)

Jeroen Vuurens
Jeroen Vuurens

Reputation: 1251

char is a primitive, these are initialized automatically (in case of char to \u0000). Now that you did not initialize name, name+= input makes no sense. You probably meant to start name with a value of "".

Upvotes: 0

xagyg
xagyg

Reputation: 9711

The first time initial is used it is set to a value:

initial = input.charAt(0);

The first time name is used it is using a null value in the calculation:

name += input; // is equivalent to
name = null + input;

Since name has not been initialized (see meaning of +=).

Upvotes: 2

Azodious
Azodious

Reputation: 13872

name += input;

is equivalent to

name = name + input;

You are using name (a local variable) without initializing it. and this is cause of error. specifically, you are trying to concat un-initialized name with input.

initial = input.charAt(0); 

Here, you are initializing it before using it in print statement. hence no error.

Upvotes: 3

user207421
user207421

Reputation: 310866

You're assigning the char before you read it (in the System.out.println() line), but you're not assigning the String before you read it, which happens in the name += input line.

Upvotes: 10

Related Questions