Important Java IQ(Inverview Questions) with answers_Part 6

Q. How can I swap two variables without using a third variable?
A. Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:


int a=5,b=10;a=a+b; b=a-b; a=a-b;


An other approach to the same question


You use an XOR swap.


for example:


int a = 5; int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;


Q. What is data encapsulation?
A. Encapsulation may be used by creating ‘get’ and ‘set’ methods in a class (JAVABEAN) which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is nothing but wrapping up the data and associated methods into a single unit in such a way that data can be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data hiding.


Q. What is reflection API? How are they implemented?

A. Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.


Q. Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why
A. Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.


Q. What is phantom memory?
A. Phantom memory is false memory. Memory that does not exist in reality.


Q. Can a method be static and synchronized?
A. A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:


synchronized(XYZ.class) {


}


Q. What is difference between String and StringTokenizer?
A. A StringTokenizer is utility class used to break up string.


Example:


StringTokenizer st = new StringTokenizer(“Hello World”);


while (st.hasMoreTokens()) {


System.out.println(st.nextToken());


}


Output:


Hello


World

Comments

Popular Posts