Friday, March 28, 2008

Java Interview Questions - 2

Q1. How could Java classes direct program messages to the system console, but error messages, say to a file?

A. The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

* Q2. What's the difference between an interface and an abstract class?

A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

* Q3. Why would you use a synchronized block vs. synchronized method?

A. Synchronized blocks place locks for shorter periods than synchronized methods.

* Q4. Explain the usage of the keyword transient?

A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

* Q5. How can you force garbage collection?

A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

* Q6. How do you know if an explicit object casting is needed?

A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;

When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

* Q7. What's the difference between the methods sleep() and wait()

A. The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

* Q8. Can you write a Java class that could be used both as an applet as well as an application?

A. Yes. Add a main() method to the applet.

* Q9. What's the difference between constructors and other methods?

A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

* Q10. Can you call one constructor from another if a class has multiple constructors

A. Yes. Use this() syntax.

* Q11. Explain the usage of Java packages.

A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

* Q12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?

A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee

* Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0?

A.There's no difference, Sun Microsystems just re-branded this version.

* Q14. What would you use to compare two String variables - the operator == or the method equals()?

A. I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

* Q15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

* Q16. Can an inner class declared inside of a method access local variables of this method?

A. It's possible if these variables are final.

* Q17. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A. A single ampersand here would lead to a NullPointerException.

* Q18. What's the main difference between a Vector and an ArrayList

A. Java Vector class is internally synchronized and ArrayList is not.

* Q19. When should the method invokeLater()be used?

A. This method is used to ensure that Swing components are updated through the event-dispatching thread.
* Q20. How can a subclass call a method or a constructor defined in a superclass?

A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.
** Q21. What's the difference between a queue and a stack?

A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

** Q22. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

** Q23. What comes to mind when you hear about a young generation in Java?

A. Garbage collection.

** Q24. What comes to mind when someone mentions a shallow copy in Java?

A. Object cloning.

** Q25. If you're overriding the method equals() of an object, which other method you might also consider?

A. hashCode()

** Q26. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?

A. ArrayList

** Q27. How would you make a copy of an entire Java object with its state?

A. Have this class implement Cloneable interface and call its method clone().

** Q28. How can you minimize the need of garbage collection and make the memory use more effective?

A. Use object pooling and weak object references.

** Q29. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?

A. If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.

** Q30. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?

A. You do not need to specify any access level, and Java will use a default package access level.

Wednesday, March 26, 2008

Java Object Initialization

Suppose class A extends one class B and implements an interface C as follows:

public class A extends B implements C
{


}

In this case, if we call new A(), how object initialization will happen? Remember class A and B, and interface C are not empty


Whenever we instantiate A with a call new A(),

The JVM will allocate enough space in the heap to hold all the instance variables defined in class A, and its super class –B and the fields defined in interface C.
The JVM will initialize instance variables. First class B’s fields will be initialized. Then interface C’s declared fields will be initialized and in the end, Class A’s instance variables will be initialized.
The JVM will call method of class A. Whenever we compile a class, the java compiler creates an instance initialization method for each constructor declared in the source code of the class. It has a name, return type void and a set of parameters that matches the constructor parameters. So in our case class A will have an method and class B will have an method (assuming that there is only one constructor for each class). This method will be created for the constructor having call to super() (implicitly or explicitly) and will be call only once for new class creation and also we can be sure that the init method will be executed before the constructor code for that class is executed.


Case 1: there are only default constructors in class A and Class B



The method of class A will invoke the method of class B which in turn will call method of Object class (which is super class of all java objects). The method of Object class will do nothing and return back to class B’s method. Then the class B constructor will be executed and then returned back to class A method where class A constructor will be completely executed.


Case 2 : class B has multiple constructors defined.

For example

public class B
{
private int count;

public B()
{
this.B(100);

}

public B(int i)
{
count = i;
}
}

public Class A extends B
{



}

Here the method of class A will result in call to super() which is constructor B() which in turn calls this.B(). There will be only one method for class B that is for constructor B(int i).This method will call Object classes method. The method of Object class will do nothing and return back to class B’s method. Then the class B constructor B(int i) will be executed completing B() then returned back to class A method where class A constructor will be completely executed.

Java Object Serialization

Serialization is a process of reading or writing an object. It is a process of saving an object’s state to a sequence of
bytes, as well as a process of rebuilding those bytes back into a live object at some future time. An object is
marked serializable by implementing the java.io.Serializable interface, which is only a marker interface -- it simply
allows the serialization mechanism to verify that the class can be persisted, typically to a file.

Transient variables cannot be serialized. The fields marked transient in a serializable object will not be
transmitted in the byte stream. An example would be a file handle or a database connection. Such objects are only
meaningful locally. So they should be marked as transient in a serializable class.
Serialization can adversely affect performance since it:
􀂃 Depends on reflection.
􀂃 Has an incredibly verbose data format.
􀂃 Is very easy to send surplus data.
When to use serialization? Do not use serialization if you do not have to. A common use of serialization is to use
it to send an object over the network or if the state of an object needs to be persisted to a flat file or a database.
Deep cloning or copy can be achieved through serialization. This may be fast
to code but will have performance implications .
The objects stored in an HTTP session should be serializable to support in-memory replication of sessions to
achieve scalability . Objects are passed in RMI (Remote Method Invocation)
across network using serialization.

The Java Virtual Machine

Each time a Java Application is executed then an instance of JVM ,responsible for its running,is created.A JVM instance is described in terms of subsystems, memory areas, data types, and instructions.The block diagram given below,depicts a view of Internal Architecture of JVM :



Each JVM has a class loader subsystem which loads classes and interfaces with fully qualified names.Each JVM has an execution engine too , which executes all instructions contained by methods of a loaded class.While executing a Java program,a JVM requires memory for storing bytecodes,objects ,local variables,method arguments,return values,intermediate computational results and JVM does that memory management on several runtime data areas.The specification of runtime data areas is quite abstract.This abstract nature of JVM specification helps different designers to provide implementation on wide variety of OS and as per choice of the designers.Some implementations may have a lot of memory in which to work, others may have very little. Some implementations may be able to take advantage of virtual memory, others may not.

Each instance of the Java virtual machine has one method area and one heap. These areas are shared by all threads running inside the virtual machine. When the virtual machine loads a class file, it parses information about a type from the binary data contained in the class file. It places this type information into the method area. As the program runs, the virtual machine places all objects the program instantiates onto the heap.

When a new thread is created, it gets its own pc register (program counter) and Java stack. If the thread is executing a Java method (not a native method), the value of the pc register indicates the next instruction to execute. A thread's Java stack stores the state of Java (not native) method which includes its local variables, the parameters with which it was invoked, its return value (if any), and intermediate calculations. The state of native method invocations is stored in an implementation-dependent way in native method stacks, in registers or other implementation-dependent memory areas.

The Java stack is composed of stack frames (or frames). A stack frame contains the state of one Java method invocation. When a thread invokes a method, the Java virtual machine pushes a new frame onto that thread's Java stack. When the method completes, the virtual machine pops and discards the frame for that method.

In JVM ,the instruction set uses the Java stack for storage of intermediate data values.The stack-based architecture of the JVM's instruction set optimizes code done by just-in-time and dynamic compilers.

Some more java interview questions

Is Vector is threadsafe ?

Ans : Yes, Vectors are threadsafe. Vectors are synchronized.


Why String objects are called immutable objects ?

String objects are called immutable because once you assign a value to a string object, you can never changes the value. String objects are immutable . String references are not.

If you redirect a String reference to a new String, the old String can be lost.

Can we override String methods ?

No...The String class is final—its methods can’t be overridden.

What is the difference between comparing two String objects and two StringBuffer objects using equals methods ?

String class overrides equal method of Object class but StringBuffer equals() is not overridden; it doesn’t compare values.

How many number of non-public class definition can a source file have
Unlimited
Can abstract class be instantiated

No.. abstract class cannot be be instantiated


What is a Java Virtual Machine (JVM)?


A Java Virtual Machine is a runtime environment required for execution of a Java application.Every Java application runs inside a runtime instance of some concrete implementation of abstract specifications of JVM.It is JVM which is crux of 'platform independent' nature of the language.

What is the difference between interpreted code and compiled code?


An interpreter produces a result from a program, while a compiler produces a program written in assembly language and in case of Java from bytecodes.The scripting languages like JavaScript,Python etc. require Interpreter to execute them.So a program written in scripting language will directly be executed with interpreter installed on that computer,if it is absent then this program will not execute.While in case of compiled code,an assembler or a virtual machine in case of Java is required to convert assembly level code or bytecodes into machine level instructions/commands.Generally, interpreted programs are slower than compiled programs, but are easier to debug and revise.