Using Operators and Decision Constructs Flashcards

1
Q

The following code snippet will not compile:

int i = 10; System.out.println( i<20 ? out1() : out2() );

Assume that out1 and out2 methods have the following signatures:

public void out1();
public void out2();

True or false?

A

Note that it is not permitted for the second and the third operand of the ?: operator to be an invocation of a void method.

The type of the expression built using ?: is determined by the types of the second and the third operands.

If one of the operands is of type byte and the other is of type short, then the type of the conditional expression is short.
If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type T, then the type of the conditional expression is T.

Otherwise, binary numeric promotion (5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type.
If the second and third operands are of different reference types, then it must be possible to convert one of the types to the other type (call this latter type T) by assignment conversion (5.2); the type of the conditional expression is T. It is a compile-time error if neither type is assignment compatible with the other type.

Note that binary numeric promotion performs unboxing conversion (5.1.8) and value set conversion (5.1.13).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What will the following code print when run without any arguments …

public class TestClass {

public static int m1(int i){
    return ++i;
}

public static void main(String[] args) {

    int k = m1(args.length);
    k += 3 + ++k;
    System.out.println(k);
}

}

A

When the program is run without any arguments, args gets assigned a string array of size 0.
NullPointerException or ArrayIndexOutOfBoundsException are out of question.
Thus, the first call becomes :
int k = m1(0);

Follow through the code like this:

  1. Method m1() uses pre-increment operation. Therefore, the first i is incremented and then the new value of i is returned.
  2. Thus, k gets the value of 1.
  3. Expand the += operator as:
    k = k + 3 + ++k;
This becomes (remember that k = 1 at this point): 
k = 1 + 3 + (++k) i.e. 
k = 1 + 3 + 2; 
(at this point value of k is 2 because of ++k). 
But the value of Right Hand Side has not yet been assigned to k. IMPORTANT
k = 6;  -  6 is assigned to k thereby overwriting the value of 2. 

Therefore, the final value of k is 6

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
//Given: 
public class LoopTest {
    int k = 5;
    public boolean checkIt(int k) {
        return k-- > 0 ? true : false;
    }
    public void printThem() {
        while (checkIt(k)) {
            System.out.print(k);
        }
    }
    public static void main(String[] args) {
        new LoopTest().printThem();
    }
}
// What changes should be made so that the program will print 54321 ?
A

Currently this goes on an infinite loop:

Replace System.out.print(k); with System.out.print(k–); to print 54321

Observe that the method parameter k in checkIt() shadows the instance variable k.
Therefore, any changes made to k in checkIt() will not affect the instance variable k. IMPORTANT
For checkIt() method to access the instance variable k, you need to do this.k. k–>0 means, first compare the value of k with 0, and then reduce it by 1.
(As opposed to –k>0, which means, first reduce the value of k by 1 and then compare with 0).
In the printThem() method, k refers to the instance variable.
You need to reduce it by 1 after each iteration.
Therefore, System.out.print(k–); will do.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
//What letters will be printed by this program?
 public class ForSwitch {
     public static void main(String args[]) {
         char i;
         LOOP: for (i = 0; i < 5; i++) {
             switch (i++) {
                 case '0': System.out.println("A");
                 case 1: System.out.println("B"); break LOOP;
                 case 2: System.out.println("C");break;
                 case 3: System.out.println("D");break;
                 case 4:System.out.println("E");
                 case 'E':System.out.println("F");
             }
         }
     }
 }
A

char i;
LOOP: for (i = 0; i < 5; i++) {
switch (i++) {
case ‘0’: System.out.println(“A”);
case 1: System.out.println(“B”); break LOOP;
case 2: System.out.println(“C”);break;
case 3: System.out.println(“D”);break;
case 4:System.out.println(“E”);
case ‘E’:System.out.println(“F”);

– C and F –

  1. Defining i as char doesn’t mean that it can only hold characters (a, b, c etc). It is an integral data type which can take any +ive integer value from 0 to 2^16 -1.
  2. Integer 0 or 1, 2 etc. is not same as char ‘0’, ‘1’ or ‘2’ etc.

So when i is equal to 0, nothing gets printed and i is incremented to 1 (due to i++ in the switch).

i is then incremented again by the for loop for next iteration. so i becomes 2.

when i = 2, “C” is printed and i is incremented to 3 (due to i++ in the switch) and then i is incremented to 4 by the for loop so i becomes 4.

when i = 4, “E” is printed and since there is no break, it falls through to case ‘E’ and “F” is printed.

i is incremented to 5 (due to i++ in the switch) and then it is again incremented to 6 by the for loop.
Since i < 5 is now false, the for loop ends.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which of the lines will cause a compile time error in the following program?

public class MyClass{
   public static void main(String args[]){
      char c;
      int i;
      c = 'a';//1
      i = c;  //2
      i++;    //3
      c = i;  //4
      c++;    //5
   }
}
A
  1. A char value can ALWAYS be assigned to an int variable, since the int type is wider than the char type. So line 2 is valid.
  2. Line 4 will not compile because it is trying to assign an int to a char. Although the value of i can be held by the char but since ‘i’ is not a constant but a variable, implicit narrowing will not occur.

Here is the rule given in JLS regarding assigment of constant values to primitive variables without explicit cast:

A narrowing primitive conversion may be used if all of the following conditions are satisfied:

  1. The expression is a compile time constant expression of type byte, char, short, or int.
  2. The type of the variable is byte, short, or char.
  3. The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.

Note that implict narrowing conversion (i.e. conversion without an explicit cast) does not apply to float, long, or double.

For example, char ch = 30L; will fail to compile although 30 is small enough to fit into a char.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

The following code snippet will print true.
String str1 = “one”;
String str2 = “two”;
System.out.println( str1.equals(str1=str2) );

A

First the value of ‘str1’ is evaluated (i.e. one).

Now, before the method is called, the operands are evaluated, so str1 becomes “two”. so “one”.equals(“two”) is false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
What is the result of executing the following fragment of code:  
boolean b1 = false; 
boolean b2 = false;
if (b2 != b1 = !b2){    
System.out.println("true"); } 
else{    
System.out.println("false"); 
}
A

Note that boolean operators have more precedence than =.
(In fact, = has least precedence of all operators.)
so, in (b2 != b1 = !b2) first b2 != b1 is evaluated which returns a value ‘false’. So the expression becomes false = !b2. And this is illegal because false is a value and not a variable!

Had it been something like (b2 = b1 != b2) then it is valid because it will boil down to : b2 = false.
Because all an if() needs is a boolean, now b1 != b2 returns false which is a boolean and as b2 = false is an expression and every expression has a return value (which is actually the Left Hand Side of the expression). Here, it returns false, which is again a boolean.

Note that return value of expression : i = 10 , where i is an int, is 10 (an int).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
What will the following code snippet print?      
Object t = new Integer(107);     
int k = (Integer) t.intValue()/9;     
System.out.println(k);
A

Compiler will complain that the method intValue() is not available in Object.
This is because the . operator has more precedence than the cast operator.
So you have to write it like this:
int k = ((Integer) t).intValue()/9;
Now, since both the operands of / are ints, it is an integer division.
This means the resulting value is truncated (and not rounded). Therefore, the above statement will print 11 and not 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly