Search Logic Blocks

Saturday, January 11, 2020

Java: Let's Practice Operators

Example: What should be the output for the following code?

Class Test (Test.java)
public class Test {
    public static void main(String args[]) {
        int i = 20;
        int j = 35;

        System.out.println("1. " + (i << 2));

        System.out.println("2. " + (j % i));

        System.out.println("3. " + i++);

        i *= 5;
        j /= 5;
        System.out.println("4. " + (i++ + j));

        System.out.println("5. " + (j > i));

        System.out.println("6. " + i);

        System.out.println("7. " + j);
    }
}
Solution : What should be the output for the following code?

1. 80      // i << 2 => 20 << 2 => 20 *2 * 2 = 80
2. 15      // j % i => 35 % 20 => 15
3. 20      // i++ => use i then increment => 20 then i = 21
4. 112    // i *= 5 => i = 21 * 5 = 105, j /= 5 => j = 35 / 5 = 7, i++ + j => use i = 105 => 105 + 7 = 112, and then increment = > i = 106
5. false  // j > i => 7 > 106 => false
6. 106   // i = 106
7. 7       // j = 7

No comments: