what exactly charAt() is returning in the following case?
String s1="abcd"; int i=s1.charAt(2); System.out.println(i);//will give 99 and if i give ...
Integer i=s1.charAt(2)
System.out.println(i);// gives error
Why the Autoboxing is not happening here?
Shiva Prasad P.K.
wise owen
Ranch Hand
Joined: Feb 02, 2006
Posts: 2023
posted
0
If i is a value of type char, then boxing conversion converts i into a reference r of class and type Character, such that r.value() == i.
[ October 26, 2006: Message edited by: wise owen ]
Burkhard Hassel
Ranch Hand
Joined: Aug 25, 2006
Posts: 1274
posted
0
Hi Shivaprasad,
charAt(int pos) always returns a char primitive.
The second line int i = s1.charAt(2);
works, because char -> int is a widening primitive conversion. ints are "wider" than char, they can be negative for example.These widening primitive conversions work with or without an explicit cast.
If you change the line to Integer i=s1.charAt(2);
The compiler tries to convert the char primitive to a Character wrapper object, that's ok. But then it is not possible to convert a Character to an Integer.
You cannot first box and then widen!
But the other way round, it works: Integer i=(int) s.charAt(2);
here, the char is first widened to an int primi. This int primi then can be boxed to an Integer.
Yours, Bu.
all events occur in real time
Deepthi Kanakam Rajan
Greenhorn
Joined: May 15, 2006
Posts: 13
posted
0
Originally posted by Burkhard Hassel: You cannot first box and then widen!
But the other way round, it works:Integer i=(int) s.charAt(2);
here, the char is first widened to an int primi. This int primi then can be boxed to an Integer.
Yours, Bu.[/QB]
Deepthi Kanakam Rajan
Greenhorn
Joined: May 15, 2006
Posts: 13
posted
0
Originally posted by Deepthi Kanakam Rajan: [QB][/QB]
sorry forgot to add my query to that which is according to K&B book its mentioned that:
One can box and then widen and not the other way while your statement contradicts it.
Can you please clarify this as I am confused now
Thanks
Shivaprasad P Kanaganahallimath
Ranch Hand
Joined: Sep 25, 2006
Posts: 48
posted
0
thank you all I got it!!
Burkhard Hassel
Ranch Hand
Joined: Aug 25, 2006
Posts: 1274
posted
0
Hi Deepthi,
One can box and then widen
this is wrong.
you cannot first box and then widen:
or: int i = 54321; Long lo = i; // no compile
or verbose: int i = 5; Integer inti = i; // ok so far but Long lo = inti; // no way!
But you can first widen and then box.
or:
Here no two-liner is possible.
K&B book says somewhere "an int can never become a Long", or something like that. But this is not correct in general. It's only correct, if you try it in the short cut coding style like in my example with the 54321.
Yours, Bu.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.