Java - Frequently Asked Interview Questions and Answers

Q1.  Explain multithreading in Java ?

Ans. 

1. Multithreading provides better interaction with the user by distribution of task

2. Threads in Java appear to run concurrently, so it provides simulation for simultaneous activities.
The processor runs each thread for a short time and switches among the threads to simulate sim-ultaneous execution (context-switching) and it make appears that each thread has its own processor.By using this feature, users can make it appear as if multiple tasks are occurring simultaneously when, in fact, each is 
running for only a brief time before the context is switched to the next thread.

3. We can do other things while waiting for slow I/O operations.
In the java.iopackage, the class InputStreamhas a method, read(), that blocks until a byte is read from the stream or until an IOExceptionis thrown. The thread that executes this method cannot do anything elsewhile awaiting the arrival of another byte on the stream.

Q2.  Why java doesn't support multiple Inheritence ?

Ans. class A {
      void test() {
          System.out.println("test() method");
      }
}

class B {
         void test() {
            System.out.println("test() method");
         }
}

Suppose if Java allows multiple inheritance like this,

class C extends A, B {
}

A and B test() methods are inheriting to C class.

So which test() method C class will take? As A & B class test() methods are different , So here we would Facing Ambiguity.

Q3.  Why is String immutable in Java ?

Ans. 

1. String Pool

When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

2. To Cache its Hashcode

If string is not immutable, One can change its hashcode and hence not fit to be cached.

3. Security

String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.


Q4.  Which are the different segments of memory JVM uses ?

Ans. 

1. Stack Segment - contains local variables and Reference variables(variables that hold the address of an object in the heap)
2. Heap Segment - contains all created objects in runtime, objects only plus their object attributes (instance variables)
3. Code Segment -  The segment where the actual compiled Java bytecodes resides when loaded

Q5.  Describe what happens when an object is created in Java ?

Ans. 1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

Q6.  What is the difference between StringBuffer and String class ?

Ans. A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The String class represents character strings. All string literals in Java programs, such as "abc" are constant and implemented as instances of this class; their values cannot be changed after they are created.

Q7.  Describe, in general, how java's garbage collector works ?

Ans. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically frees the memory used by
objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java's dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected.

Q8.  What are the methods of Object Class ?

Ans. clone() - Creates and returns a copy of this object.
equals() - Indicates whether some other object is "equal to" this one.
finalize()  - Called by the garbage collector on an object when garbage collection determines that there are no more references to the object
getClass() - Returns the runtime class of an object.
hashCode() - Returns a hash code value for the object.
toString() - Returns a string representation of the object.
notify(), notifyAll(), and wait() - Play a part in synchronizing the activities of independently running threads in a program.

Q9.  What is difference between Encapsulation And Abstraction?

Ans. 

1.Abstraction solves the problem at design level while encapsulation solves the problem at implementation level

2.Abstraction is used for hiding the unwanted data and giving relevant data. while Encapsulation means hiding the code and data into a single unit to protect the data from outside world.

3. Abstraction lets you focus on what the object does instead of how it does it while Encapsulation means hiding the internal details or mechanics of how an object does something.

4.For example: Outer Look of a Television, like it has a display screen and channel buttons to change channel it explains Abstraction but Inner Implementation detail of a Television how CRT and Display Screen are connect with each other using different circuits , it explains Encapsulation.


Q10.  Explain the scenerios to choose between String , StringBuilder and StringBuffer ?

Ans. If the Object value will not change in a scenario use String Class because a String object is immutable.

If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).

If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).

Q11.  Difference between C++ and Java ?

Ans. Java does not support pointers.

Java does not support multiple inheritances.

Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method. 

Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework.

C++ compiles to machine language , when Java compiles to byte code .

In C++ the programmer needs to worry about freeing the allocated memory , where in Java the Garbage Collector takes care of the the unneeded / unused variables.

Java is platform independent language but c++ is depends upon operating system.

Java uses compiler and interpreter both and in c++ their is only compiler.

C++ supports operator overloading whereas Java doesn't.

Internet support is built-in Java but not in C++. However c++ has support for socket programming which can be used.

Java does not support header file, include library files just like C++ .Java use import to include different Classes and methods.

There is no goto statement in Java.

There is no scope resolution operator :: in Java. It has . using which we can qualify classes with the namespace they came from.

Java is pass by value whereas C++ is both pass by value and pass by reference.

Java Enums are objects instead of int values in C++

C++ programs runs as native executable machine code for the target and hence more near to hardware whereas Java program runs in a virtual machine.

C++ was designed mainly for systems programming, extending the C programming language whereas Java was created initially to support network computing.

C++ allows low-level addressing of data. You can manipulate machine addresses to look at anything you want. Java access is controlled.

C++ has several addressing operators . * & -> where Java has only one: the .

We can create our own package in Java(set of classes) but not in c and c++.


Q12.  What is the difference between final, finally and finalize() ?

Ans. final - constant variable, restricting method overloading, restricting class subclassing.

finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block. Use the finally block to close files or to release
other system resources like database connections, statements etc.

finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. 

Q13.  Explain Thread States ?

Ans. 

Runnable - waiting for its turn to be picked for execution by the thread schedular based on thread priorities.

Running - The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn. 

Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.

Sleeping - Java threads are forcibly put to sleep (suspended) with Thread.sleep. they can resume using Thread.resume method.

Blocked on I/O - Will move to runnable after I/O condition like reading bytes of data etc changes.

Blocked on synchronization - Will move to Runnable when a lock is acquired.

Dead - The thread is finished working.