(a)
Q: Given int n, i=10, j=20, x=3, y= 100, what is the value of n and y at the end of the following expression?
n = (i > j) && (x < ++y)
A: n==0 and y==100, y will not be incremented since i is less than j, so the first expression is False, and the logical "and" in C doesn't evaluate the second expression under that circumstance.
(b)
Q: Given the following code fragment in Java:
String bob = new String( "Bob" );
String bob2 = new String( "Bob" );
boolean bobIsBob = ( bob == bob2 );
What is the value of bobIsBob?
A: False. The Java comparison operator compares the strings' references to see if they reference the same object. Two different string objects that happen to contain the same string value are still different to the comparison operator. Bob is not Bob -- he only looks like Bob. To get the behavior you would expect, use the following expression:
bobIsBob = bob.equals(bob2);
Example 2: Language feature questions.
Back to Article