Java Questions 2

11. Will it compile? If yes, what is the output of below snippet?

Options:

a. No. Size of the array must be defined.

b. No. Compilation error.

c. Yes. 4

d. Yes. 5

Ans: d

12. Find the output of below code.

Options:

a. Compilation error

b. Run time error

c. The final local variable num cannot be assigned.

d. 45

Ans: d

13. Find the output of below code.

Options:

a. Compilation error

b. Exception catched 99

c. Exception catched error

d. Run-time error

Ans: a

Reason: No exception of type int can be thrown; an exception type must be a subclass of Throwable.

14. Find the output for below code snippet.

Options:

a. 300, 300.9

b. Compilation error

c. 100200, 100.5200.4

d. 300, 300

Ans: a

15. Write a code to find the first repeated char in a String.

Sol:

Output:

Length is: 10
First repeated char found. It is e

16. Write a code to find if string is having all unique characters or not. Print true or false.

public void uniqueCharsInString() {
boolean flag = false;
String str = “selenium99“;
System.out.println(str);
HashSet<Character> uniqueSet = new HashSet<Character>();
for (int i = 0; i < str.length(); i++) {
flag = uniqueSet.add(str.charAt(i));
if (flag == false)
break;
}
System.out.println(flag);
}

Output:

selenium99
false

*If the input is “WebDriv”, then output is true.

17. Can we use method overloading for a static method.

Ans: Yes. But a static method can not be overridden.

18. What is the use of final keyword in Java.

Ans: Final keyword is used in java in 3 contexts.

final variable –> Is used to create constant variables. Once it is declared final, it’s value can not be changed later.

final method –> Used to prevent method overriding

final class      –> Used to prevent inheritance. A final class can not extended.

Java inheritance:

19. Predict the output of the below java program?

a. child

b. parent

c. child parent

d. parent child

 

Ans: a

Explanation: p is a reference of Parent class and is referring to the object of child class. In this scenario, run time polymorphism occurrs and Child class method ‘print‘ will be called.

20. Predict the output of the below java program?

a. child

b. parent

c. compile time exception

d. run time error

 

Ans: d

Error: Exception in thread “main” java.lang.ClassCastException: inheritance.Parent cannot be cast to inheritance.Child
at inheritance.Inheritance.main(Inheritance.java:16)

 

Leave a Reply

Your email address will not be published. Required fields are marked *