Kachi03
Kachi03

Reputation: 1

Adding string literals to initialized variables

I feel silly that I can't find the answer to this question, but I'm working on an assignment for class and I'm asked to describe the output of the following sample code:

int i = 1;
for (i = 0; i <= 6; i++){
    System.out.print( 'i' + i);
}

which outputs:

105106107108109110111

((I understand that initializing i to 1 is not necessary before the loop condition)) I don't understand why the above print statement outputs this pattern of numbers (1 05 1 06 1 07 1 08 1 09 1 10 1 11). Simply leaving it as

System.out.print( 'i');

prints "i" 5 times as expected. So why does adding the value of i change the output of 'i'?

edit: fixed variable name

Upvotes: 0

Views: 68

Answers (3)

knittl
knittl

Reputation: 265154

Because 'i' is a character literal of type char. Adding a char value and an int value automatically promotes it to an int. The ASCII value of the lower case i is 105 (0x69 in hex).

So what you have is System.out.print(105+i) etc.

If you want to concatenate strings, you have to use strings: System.out.print("i" + i) or System.out.printf("i%d", i). If your char were dynamic and stored in variable with name c, you might want to use String.valueOf(c) + i or printf/String.format again.

Upvotes: 3

mahdi lotfi
mahdi lotfi

Reputation: 116

in java you can add char with int and the character implicitly will convert to corresponding ASCII code.

in your print statement you are using single quotes, so it will be infer as character.

also notice the ASCII code for alphabet i is equal to 105.

Upvotes: 0

Soren Saville Scott
Soren Saville Scott

Reputation: 36

j appears to be uninitialised in this snippet, and so it shouldn't even compile. If you have a j variable somewhere else in the scope your for loop will be using that.

Also note that 'j' + j is trying to add a (presumably) integer to a char, which will promote it to an int, and so you are printing the integer code point of 'j' plus whatever variable j is.

Upvotes: 0

Related Questions