Java Coding Interview Questions – Part 1
Java Coding Interview Questions – Part 2
Java Coding Interview Questions – Part 3
1. What will be the output of following Java program ?
package quiz; public class StringCompare { public static void main(String[] args) { String s1 = new String ("Hello"); String s2 = "Hello"; System.out.println(s1 == s2); } }
Output
false
Note :
== compares the reference and should not be used for String comparison. Rather use methods equals() or equalsIgnoreCase() for string comparison.
2. Predict the output of following Java program.
package quiz; public class StaticQuiz { static int a = 5; static{ a = a + 5; } static void square(int num){ System.out.println("Square of " + num + " = " + num*num); } public static void main(String[] args) { int a = 5; square(a); } }
Output
Square of 5 = 25
Explanation
The instance variable value will be used.
3. What will be the output of following program ?
public class Varargsquiz { public static void main(String[] args) { method(); } public static void method(int... v) { System.out.println("int"); for (int n : v) System.out.println(n); } public static void method(boolean... v) { System.out.println("bool"); for (boolean b : v) System.out.println(b); } }
Output
Compilation error due to ambiguous method
Explanation
This will result in a compilation problem because the call method() is ambiguous.. compiler won’t be able to resolve which of the overloaded methods to invoke.
4. What happens when you compile and run the following program ?
public class VarargsExample { public static void main(String[] args) { vaTest(10, 20); } static void vaTest(int... v) { for (int n : v) System.out.println(n); } static void vaTest(int a, int b) { System.out.println(a + b); } }
Output
30
Explanation
The varargs method and the normal method are overloaded. But the method will exact match will be preferred in this case.
5. What will be the output of running Class2.java ?
package quiz; public class Class1 { public static void main(String[] args) { for (String s : args) System.out.print(s); System.out.println(4); } }
package quiz; public class Class2 { public static void main(String[] args) { String[] numbers = { "1", "2", "3" }; Class1.main(numbers); } }
Output
1234
Explanation
We can call main() of a class from another class using Classname.main(). Hence, both the print statements will be executed.
You may also like :
Java Coding Interview Questions – Collections
Java Coding Interview Questions – Collections (Part 2)
© 2016 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post