Home > Software engineering >  Adding string literals to initialized variables
Adding string literals to initialized variables

Time:09-29

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

CodePudding user response:

Because 'i' is 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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related