This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

confused

 
sonali rao
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
got some doubts. Please help me out .
1.What is the result that will be printed out here ?
int i = - 128;
System.out.println((byte)i << 1);
answers 1: -256
2: 256 .
Correct answer is -256. but i thought it would be 256.
2.Will this test evaluate to true?
Object a = "hello";
String b = "hello";
if(a == b)
System.out.println("equal");
else
System.out.println("not equal");

Answer given is "Yes". but when i compile i get the following 2 errors.
error: incompatible types
found: java.lang.String
required: Object
Object a="hello";
error: incomparable types: Object and java.lang.String
if(a==b)
Thanks in advance.
 
Brahim Bakayoko
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. the sign is preserved given the shift (<<
2. the answer should be "not equal"
This would be true:
String s = "hello";
if(s == "hello")... only because of compiler optimization...
This would be false:
String s = "hello";
if(s == new String("hello"))...
This would be true also:
String s = "hello";
String s2 = "hello";
if(s == s2)... only because of compiler optimization...
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"System.out.println((byte)i << 1);"
The cast operator has a bigger precedence than <<. Thus "i" is interpreted as a byte for the next operation, however "<<" converts "i" to int, thus the cast to byte has no effect.
"System.out.println( (byte)(i << 1) );" prints 0 because the 8 least significant bits of -256 are 0.
[ November 04, 2003: Message edited by: Jose Botella ]
 
S. Sumukh
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Sonali,
Plz visit
JLS String Literals
It shud answer ur 1st question.
and I was able to compile the code

and o/p as expected is equl as 'a' and 'b' will refer
to same "hello".
Which java version u r using ?? I used 1.4.1..
hth
sumukh
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic