System.out.println(Byte.parseByte("123456789"));
Ans: There is a number format Exception and also the value is out of range.
What does the following code print? Explain it!
int x = 5;
for(int i = 0; i < 10; i++) {
switch(i%3) {
case 0:
x += 2;
default:
x += 1;
}
}
System.out.println(x);
Ans: The output of above code is given below:
What does the following code print? Explain it!
int i = 0;
int j = 20;
try {
j = i/2;
i = (j+1)/j+1;
} catch(ArithmeticException e) {
i = 30;
j = 50;
} catch(Exception e) {
i = 8;
j = 9;
}
finally {
i -= 10;
j += 10;
}
System.out.println(i + j);
Ans: The output of the above program is given below:
Given the definitions of class A, class B, and interface C as follows. Will everything be compiled successfully? Choose your answer.
a. C c = new C(); // yes /no [Ans: yes]
b. C c = new A(); // yes /no [ Ans: yes]
c. C c = new B(); // yes /no [Ans: no]
interface C { }
class A implements C { }
class B { }
Given this code, what will be return value of h (41)? Explain it.
public static int h(int i) {
return i<=1?1:i-h(i/2);
}
Ans:
The return value of h (41) is: 27.
What is information hiding in Java? Give an example!
Ans:
In programming, the process of hiding details of an object or function. Information hiding is a powerful programming technique because it reduces complexity. One of the chief mechanisms for hiding information is encapsulation -- combining elements to create a larger entity. The programmer can then focus on the new object without worrying about the hidden details. In a sense, the entire hierarchy of programming languages, from machine languages to high-level languages, can be seen as a form of information hiding.
Information hiding is also used to prevent programmers from intentionally or unintentionally changing parts of a program.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java :
-Declare the variables of a class as private.
-Provide public setter and getter methods to modify and view the variables values.
What does the following code print? Assume the “File.txt” is not available. Explain it.
try {
try (BufferedReader br = new BufferedReader(new FileReader("File.txt"))) {