RonB7
RonB7

Reputation: 297

JAVA System.out.println equation

Can someone explain to me why the following code prints the char 'u' ?

 int p = 9;
 int q = 5;
 int r = p - q;
 double x = p;
 double y = q;
 String s = "Question";

 System.out.println ((char)(s.charAt(r) + 1));

Upvotes: 2

Views: 2555

Answers (5)

user5794376
user5794376

Reputation:

The value of r is 4. Therefore,

s.charAt(r); = s.charAt(4); = ELEMENT AT 4th INDEX OF "Question" = 't'

When an integer is added to a char (eg. 'A'+1) or the post increment operator is used with a char (eg. char_variable++), the ASCII value of the char is incremented.
So,

s.charAt(r)+1 = (char)((ASCII value of 't')+1) = (char)(116+1) = 'u'

Since 117 is the ASCII value of 'u', the program displays 'u'.

Upvotes: 0

Adnan Isajbegovic
Adnan Isajbegovic

Reputation: 2307

You take char at position 4 (since r is p - q, which is 4) in string s, and its t. In s.charAt('t') you take its char value (ASCII code), which is 116, and you add 1 to it, so you will 117, which is ASCII code of u and you turn it in char, so it will print u.

For example, if you do this:

String s = "Question";
System.out.println((int)s.charAt(r));

It will print 116. If you do this:

 String s = "Question";
 System.out.println((char) 177);

It prints u.

If you're wondering why is t at position 4, and not s, thats because charAt works from 0, not from 1.

Upvotes: 1

1) p-q = 4

2) character at index 4 is t (s.chartAt(4) gives character at index 4 in string s).

3) you have added 1 to it so 1 was added to its ASCII value making the ASCII value equal to ASCII value of u.

4) then the integer was cast to char which will be 'u', which was printed.

Upvotes: 3

René Link
René Link

Reputation: 51403

Because s.charAt(r) = 't' and 't' as int is 116. 116 + 1 is 117 and 117 as char is u;

If you split up the oneliner it might be more clear:

char charAtR = s.charAt(r);
int plusOne = charAtR + 1; // char will be converted to int
char toPrint = (char) plusOne;

System.out.println (toPrint);

Upvotes: 2

Oleg Baranenko
Oleg Baranenko

Reputation: 398

In System.out.println() you receive character 't' from string "Question" and output next codePoint that is 'u'.

Upvotes: 1

Related Questions