Author Topic:   Concatenation
Suresh Ray
greenhorn
posted March 07, 2000 05:14 PM         
Hi,
One of Mock exam questions:

Which of the following are valid statements?

1) System.out.println(1+1); // ans
2) int i= 2+'2'; // ans - how? an implicit conversion to int?
3) String s= "on"+'one';// why not?
4) byte b=255;

For (3), IMO, + would convert 'one' to String representation and concatenate with "on" right? Correct me if I am wrong.
The answer here says, Option 3 is not valid because single quotes are used to indicate a character constant and not a string. If this is true, why character constants cannot be concatenated with Strings, like other data types, for example int ?

Would anyone please clarify this please?

Thanks..

Jim Yingst
sheriff
posted March 07, 2000 05:49 PM             
A single character constant could indeed be represented that way, and concatenated onto a string by the + operator. But "one" consists of three characters, and so it must be a string, and needs double quotes. Well, I suppose there's one other way to do it:

String s = "on" + 'o' + 'n' + 'e';

The point is, only one char at a time is allowed inside single quotes.

Java2learner
greenhorn
posted March 07, 2000 06:04 PM         
About the option (2), int i= 2+'2'; Is this an implicit conversion from char to int ? What method is used here for conversion?

[This message has been edited by Java2learner (edited March 07, 2000).]

maha anna
bartender
posted March 07, 2000 07:14 PM             
int i = 2+'2';
This is the case of binary numeric promotion The rules are

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

Here the last rule applies. Since 2 is an int literal, the other operand char '2' is promoted to int and addition takes place. The result is of type int which is assiginable to LHS var i.
regds
maha anna

[This message has been edited by maha anna (edited March 07, 2000).]

monty
greenhorn
posted March 08, 2000 10:29 AM             
1) System.out.println(1+1);
answer: 1+1 become an int of 2 which is then converted into a string

2) int i= 2+'2';
answer: '2' is 1st converted into an int then 2 is added to it before being assigned to i

3) String s= "on"+'one';
answer: will not compile! a char is only 16 bits long. just large enough to hold a single char, NOT three char.

4) byte b=255;
answer: will not compile, a byte is only 8 bits long including the sign. now what is the largest signed number you can fit?


[This message has been edited by monty (edited March 08, 2000).]

Java2learner
greenhorn
posted March 08, 2000 02:50 PM         
Thanks for your replies..

Jane Rozen
ranch hand
posted March 10, 2000 05:24 PM             

Just make sure you understand that '2' is not converted to int 2, but to 50 !!

|