Monday, March 5, 2018

Java Questions : What will print type questions?

Question 1:
public class StringDoubleEquals {
    private static String global = "Hell"+"o";

    /**
     * @param args
     */
    public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = new String("Hello");
        String s3 = "Hel";
        String s4 = "lo";
        String s5 = s3+s4;
        String s6 = "Hel"+"lo";
        System.out.println(s1 == s2);//false
        System.out.println(s1 == s5);//false
        System.out.println(s1 == s6);//true
        System.out.println(s1 == global);//true
    }

}

Question 2:
public class ZeroDivide {

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
        System.out.println(2/0);
        }catch (NumberFormatException e) {
            System.out.println("Numberformat");
        }catch (IllegalArgumentException e) {
            System.out.println("IllegalArgumentException");
        }
    }

}
ANS: System will throw following exception
Exception in thread "main" java.lang.ArithmeticException: / by zero

Question 3:
public class SumArray {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int sum = 0;
        int[][] arry= {{1,2,3},{4,5,6},{7,8,9}};
        for(int i =0; i<3 ;i++)
            for(int j=0; j<3; j++)
                sum = sum+arry[i][j];
   
        System.out.println(sum/5);
    }
}
ANS : 9

Question 4:
public class StringArg {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("Hello " + args[0]);
    }

}

ANS : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

Question 5:
public class StringConcat {

    /**
     * @param args
     */
    public static void main(String[] args) {
    int i = 10;
    int j = 20;
    System.out.println(i+j+"\n");
    }
}

ANS : 30

Question 6:
public class OperatorIncDec {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int i = 10;
        i = (i++)+(++i) - (--i)+(i--);
        System.out.println(i);
    }
}

ANS : 22

 NOTE : Explanation will coming soon.