Java Interview Questions and Answers

0
2134

Java interview questions

What are Native methods in Java?

Java applications can call code written in C, C++, or assembler. This is sometimes done for performance and sometimes to access the underlying host operating system or GUI API using the JNI.

The steps for doing that are:

  • First write the Java code and compile it
  • Then create a C header file
  • Create C stubs file
  • Write the C code
  • Create shared code library (or DLL)
  • Run application

What are class loaders?

The class loader describes the behavior of converting a named class into the bits responsible for implementing that class.

Class loaders eradicate the JREs need to know anything about files and file systems when running Java programs.

A class loader creates a flat name space of class bodies that are referenced by a string name and are written as:

Class r = loadClass(String className, boolean resolveIt);

What is Reflection API in Java?

The Reflection API allows Java code to examine classes and objects at run time. The new reflection classes allow you to call another class’s methods dynamically at run time. With the reflection classes, you can also examine an instance’s fields and change the fields’ contents.

The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method, Constructor, Array, and Modifier.

Explain the difference between static and dynamic class loading.

The static class loading is done through the new operator.

Dynamic class loading is achieved through Run time type identification. Also called as reflection

This is done with the help of the following methods:

getClass(); getName(); getDeclaredFields();

Instance can also be created using forName() method. It loads the class into the current class memory.

Explain Shallow and deep cloning.

Cloning of objects can be very useful if you use the prototype pattern or if you want to store an internal copy of an object inside an aggregation class for example.

Deep cloning – You clone the object and their constituent parts.

It should be used when it is inappropriate to separate the parts; the object is formed of, from it.

Shallow cloning – You clone only the object, not their parts. You add references to their parts.

It should be used when it is adequate to have the references added to the cloned object

What is the purpose of Comparator Interface?

Comparators can be used to control the order of certain data structures and collection of objects too.

The interface can be found in java.util.Comparator

A Comparator must define a compare function which takes two Objects and returns a -1, 0, or 1

Sorting can be done implicitly by using data structures of by implementing sort methods explicitly.

Explain the impact of private constructor.

Private Constructors can’t be access from any derived classes neither from another class.

So you have to provide a public function that calls the private constructor if the object has not been initialized, or you have to return an instance to the object, if it was initialized.

This can be useful for objects that can’t be instantiated.

What are static Initializers?

A static initializer block resembles a method with no name, no arguments, and no return type. There is no need to refer to it from outside the class definition.

Syntax:

[code]static

{

//CODE

}[/code]

The code in a static initializer block is executed by the virtual machine when the class is loaded.

Because it is executed automatically when the class is loaded, parameters don’t make any sense, so a static initializer block doesn’t have an argument list.

Define the purpose of Externalizable Interface.

The Externizable interface extends the serializable interface.

When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process.

When you use Externalizable interface, you have a complete control over your class’s serialization process. The two methods to be implemented are :

void readExternal(ObjectInput)

The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.

void writeExternal(ObjectOutput)

The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.

What are transient and volatile modifiers?

When serializable interface is declared, the compiler knows that the object has to be handled so as so be able to serialize it. However, if you declare a variable in an object as transient, then it doesn’t get serialized.

Volatile

Specifying a variable as volatile tells the JVM that any threads using that variable are not allowed to cache that value at all.

Volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

What are daemon threads?

Threads that work in the background to support the runtime environment are called daemon threads.

Eg garbage collector threads.

When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.

You cannot create a daemon method but you can use

public final void setDaemon(boolean isDaemon) method to turn it into one.

What is JAVAdoc utility?

Javadoc utility enables you to keep the code and the documentation in sync easily.

The javadoc utility lets you put your comments right next to your code, inside your “.java” source files.

All you need to do after completing your code is to run the Javadoc utility to create your HTML documentation automatically.

Explain the difference between StringBuilder and StringBuffer class.

StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder.

StringBuilder is more efficient than StringBuffer.

Explain semaphore and monitors in java threading.

A semaphore is a flag variable used to check whether a resource is currently being used by another thread or process.

The drawback of semaphores is that there is no control or guarantee of proper usage.

A Monitor defines a lock and condition variables for managing concurrent access to shared data. The monitor uses the lock to ensure that only a single thread is active in the monitor code at any time.

A semaphore is a generalization of a monitor. A monitor allows only one thread to lock an object at once.

Describe synchronization in respect to multithreading.

Multithreading occurs asynchronously, meaning one thread executes independently of the other threads. In this way, threads don’t depend on each other’s execution. In contrast, processes that run synchronously depend on each other. That is, one process waits until the other process terminates before it can execute

What are Checked and UnChecked Exception?

The java.lang.Throwable class has two subclasses Error and Exception. There are two types of exceptions non runtime exceptions and runtime exceptions. Non runtime exceptions are called checked exceptions and the unchecked exceptions are runtime exceptions.

Runtime Exceptions occur when the code is not robust and non runtime exceptions occur due to the problems is environment, settings, etc.

What are different types of inner classes?

Local classes – Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration

Member classes – Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables.

Anonymous classes – Anonymous classes have no name, you cannot even provide a constructor.

What is serializable Interface?

If we want to transfer data over a network then it needs to be serialized. Objects cannot be transferred as they are. Hence, we need to declare that a class implements serializable so that a compiler knows that the data needs to be serialized.

How does thread synchronization occurs inside a monitor?

A Monitor defines a lock and condition variables for managing concurrent access to shared data. The monitor uses the lock to ensure that only a single thread is active in the monitor code at any time. A monitor allows only one thread to lock an object at once.

What is the difference between AWT and Swing?

Classes in swing are not OS dependent. They don’t create peer components, so they are light weight unlike AWT.

They don’t take the look and feel of the target platform so they have a consistent appearance

What is meant by Stream Tokenizer?

The StreamTokenizer class takes an input stream and parses it into “tokens”, allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.

What is resource bundle?

The place where an application stores its locale-specific data (isolated from source code).

When your program needs a locale-specific resource your program can load it from the resource bundle that is appropriate for the current user’s locale.

What is a thread? What are the advantages we derived by programming with thread?

Threads allow programs to execute simultaneously. A thread is an independent path of execution in a program. These threads can be executed synchronously or asynchronously. All threads have a priority attached. Thread with a higher priority is executed first.

Advantages:

•        Allows multiple programs to be executed concurrently

•        Cost of thread is low compared to processes in terms of space and communication.

•        Threads are lightweight.

Explain how to create a thread and start it running.

Creating a thread:

Declare a class as a sub class of Thread

[code]</pre>
Class SampleThread extends Thread
<pre>{

Long minSample; {

SampleThread( Long minSample);

}

Public void run()

{

//Program goes here

}

}[/code]

Run the thread: An instance is created to start the thread.

[code]SampleThread s = new SampleThread(100);

s.start();[/code]

What is multithreaded program? What is the importance of thread synchronization?

A multithreaded program involves multiple threads of control in a single program. Each thread has its own stack. Other resources of the process are shared by all threads and while trying to access them it should be synchronized.

Importance of thread synchronization:

Avoids issues like deadlocks and starvation

Can be used for de bugging multi threaded programs

What is the difference between yielding and sleeping?

Sleep holds the threads execution for the specified time. On the other hand, yield will cause the thread to rejoin the queue. When a task is invoked in yielding, it returns to the ready state. While when a task is invoked in sleeping, it returns to the waiting state.

What is the difference between C++ & Java?

•        Java does not support Enums, Structures or Unions but supports classes.

•        Java does not support multiple inheritance or operator overloading

•        Java allows functions to be overloaded

•        In java, memory leaks are prevented by automatic garbage collection

•        C++ allows direct calls to be made to the native system libraries. On the other hand java calls these libraries trough java native interface.

•        In c++ parameters are passed by either value or pointers. In java, due to the absence of pointers, parameters are passed by value.

What is JAR file?

JAR is a Java Archived file which allows many files to be stored. All applets and classes can be stored in a JAR file thereby reducing the size. JAR files can be created using the JAR command that comes with JDK. This JAR file can also be digitally signed. In this case, the JAR file itself is not signed. But, all the files inside it are signed.

What is JNI?

Java Native Interface is a framework that allows the Java code running in the Java Virtual Machine to interact and communicate with other applications and libraries written in some other languages. JNI is typically used when an application cannot be entirely written in Java. JNI can be invoked only by signed applets and applications.

What is serialization?

Serialization is an operation in which an object’s internal state is converted into a stream of bytes. This stream is then written to the disk. This stream can also be sent over a socket. Serialization is a very compact and accurate method. For any object to be serialized .it must be an instance of a class that implements either the Serializable or Externalizable interface.

Uses of serialization:

Helps to persist data for future use

To exchange data between servlets and applets

To store users session

How are Observer and Observable used?

The observer pattern in java is known for its use in design. Whenever an observable object changes its state, its corresponding observer classes are notified. Observable is implemented as a class which includes methods for managing Observer lists and notifying Observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state.  For example, third-party software cannot be made Observable without changing an existing class hierarchy.

What is synchronization and why is it important?

Java supports multiple threads to be executed. This may cause two or more threads to access the same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to be in synch. Synchronization avoids memory consistence errors caused due to inconsistent view of shared memory. When a method is declared as synchronized; the thread holds the monitor for that method’s object. If another thread is executing the synchronized method, your thread is blocked until that thread releases the monitor.

Does garbage collection guarantee that a program will not run out of memory?

Garbage collection does not guarantee that a program will not run out of memory. The garbage collection is dependant on the JVM. Hence it is possible for the resources to be used faster than they are garbage collected. Garbage collection cannot be predicted if it will happen or not.

What is the difference between a break statement and a continue statement?

A break statement when applied to a loop ends the statement. A continue statement ends the iteration of the current loop and returns the control to the loop statement. If the break keyword is followed by an identifier that is the label of a random enclosing statement, execution transfers out of that enclosing statement. If the continue keyword is followed by an identifier that is the label of an enclosing loop, execution skips to the end of that loop instead.

What are synchronized methods and synchronized statements?

Synchronized methods

When a method in Java needs to be synchronized, the keyword synchronized should be added.

Example:

[code]Public synchronized void increment()

{

X++;

}[/code]

Synchronization does not allow invocation of this Synchronized method for the same object until the first thread is done with the object. Synchronization allows having control over the data in the class.

Synchronized Statement:

A synchronized Statement can only be executed once the thread has obtained a lock for the object or the class that has been referred to in the statement. Synchronized statement contains a synchronized block, within which is placed objects and methods that are to be synchronized.

Example:

[code]public void run()
{

synchronized(p1)
     {
            //synchronize statement. P1 here is an object of some class P

p1.display(s1);

}

}[/code]

Features of Java 

Simple

  • Java omits rarely used, poorly understood features those are available in C++.
  • These features include operator overloading, multiple inheritance, destructors, allocation and freeing of memory.
  • Inheritance is simplified by supporting only inheritance, as there is ambiguity in multiple and hybrid inheritance.
  • Garbage collection is the feature which reclaims the memory space by removing orphan objects automatically.
  • Java is much easier to write bug free code. Java language is easy to read and write. Java provides bug free code to allocate and deallocate memory automatically.

Object-Oriented

  • Object oriented programming is promoted as a productive and more natural way for viewing solutions to problems.
  • The classes that are created in one project can be reusable on another project.
  • Object oriented programming is a natural implementation of software development.
  • As most of the problems are stated as objects, the way of implementing OOP is simple.

Robust

  • More emphasis on early checking of the possible problems, later dynamic checking are put by Java.
  • This eliminates the error prone solutions.
  • The biggest difference between Java and C++ is that Java has a built in pointer model which eliminates the overwriting memory and data corruption.
  • Java has true arrays which allow the checking of subscript. Java applications can not gain unauthorized access to memory.
  • Java supports exception handling. Certain abnormal situations can be resolved by using this feature.
  • Flexibility is gained by separating the regular program logic from exception program logic.

Distributed

  • Java has extensive library routines to deal with protocols like TCP/IP,HTTP, FTP
  • Creation of network connections is much easier than C or C++.
  • The objects can be accessed across the internet via URLs with ease

Portable

  • Java compiles source code to bytecode.
  • The intension of bytecode is to execute by Virtual Machine which need to be in native machine code.
  • For each processor type and operating system, JVM need to be compiled for that specific type of machine.
  • Any java bytecode can execute on other machines with JVM.

Interpreted:

  • Bytecode s translated to native machine instructions – interpreted- on the fly and are not stored anywhere.
  • As linking is lightweight and more incremental process, the process of development could be exploratory.
  • Compile time information is carried over and available at runtime which is the base for the linker’s type checks

Multithreaded:

  • Multithreading is one of the multitasking paradigms. Two parts of the same application can be run concurrently.
  • For example, in a word processing application, writing the document and checking the spellings can be done at a time. This is known as thread based multi tasking.
  • The central idea of multithreading is to minimize the CPU idle time. For example, a car engine keeps running regardless of whether car is moving. The objective is to keep the car moving as much as possible, so as to gain maximum mileage.
  • One benefit of multithreading is better interactive responsiveness and real time behavior.

Platform Independent:

  • Java byte code is generated after compiling Java code.
  • Byte code is independent of the computer systems.
  • The byte code is submitted to the JVM of the system, in which it need to be executed. Every system has its own JVM.
  • The byte code is interpreted by JVM. JVM invokes Just In-Time compiler to convert native byte code into the byte code of the running system. Hence, Java is platform independent.

Secure:

  • Java enables tamper-free, virus-free systems.
  • The public-key encryption techniques are authenticated in network and distributed environments
  • Using ‘private’ access specifier, data / operations on data can not be shared by another class, except the class in which they were declared.

Java program executio

What is JVM? Explain its roles and functions.

  • Java Virtual Machine executes the byte code of another platform with simple platform specific instructions
  • JVM implements non-Java programming languages like Ada.

Roles and functions of JVM:

  • JVM loads class files
  • Class files are verified to determine whether the .class file contain valid byte code
  • Interpretation of byte code and running the application
  • Garbage Collection – the process of reclaiming memory space by removing orphan objects.

Explain why Java is called as Platform independent language. Explain how Java executable executes on any platform where JVM is available. 

  • Java byte code can run on any OS with java installed.
  • JVM takes care of executing of native byte code.
  • Java executable executes the byte code after converting the native byte code into system specific byte code.

Java architecture

Explain Java architecture, i.e. typical Java environment.

Java programming language :

  • The complete Java developing kit. In other words, it is the complete java software to write and run applications.

Java class file format 

  • A class file has a stream of 8 bit bytes.
  • The 16-bit, 32-bit and 64-bit quantities are read in two, four and eight consecutive 8-bit bytes respectively

Java Application Programming Interface:

  • Java API is a group of classes and interfaces that are included as a part of Java Development Environment.
  • These classes are developed by using Java language.
  • These classes are executed on the JVM.

Java virtual machine:

  • JVM is a group of data structures and programs that uses virtual model for the execution of byte code.
  • JVM accepts byte code, which is in intermediate form and conceptually represents the instructions set of a stack oriented architecture.
  • JVM runtime environment executes the .class files or .jar files by interpreting them or by using Just In-Time compiler.
  • JVM maintains the garbage collection

Features of Java class

Explain the features of Java class. Explain Fields, Methods, and Access Levels.

A Java class has attributes, static blocks, non-static blocks, constructors, methods and inner classes.

Fields: Fields are referred to data members whom are to be accessed by the methods, constructors of the same class and methods of other classes.

  • A class can have only copy of fields
  • An object can share group of fields, each per object.

Methods: Methods are executable blocks which has certain process instructions Methods can be static – one copy per class, and can be non-static – one copy per object

Access Levels: Java has the following access levels:

  • private: The private members can be accessed only by the class
  • public: The public members can be accessed by any other classes, across packages
  • protected: The protected members can be accessed by the class, all of sub classes of the current package.

no scope definition: The members with no scope definition can be accessed only by the package in which the class was defined.

Write a sample Java class with explanation.

The following is a code for displaying Hello! World!

[code]public class HelloWorld
{
          public void showHelloWorld()
          {
                     System.out.println(“Hello! World!!”);
          }
}[/code]

The code must be written in any text editor and the file name should be HelloWorld.java

The code starts with class definition

The method showHelloWorld() has statement to display Hello! World!!

The statement System.out.println(“Hello! World!!”); is to display Hello!World!! on the screen.

The closing braces are to close method block and class definition respectively.

Create the class HelloWorld object in public static void main(String args[]) of another class and invoke the method showHelloWorld().

The following code is the definition of initial class – which has public static void main(String args[])

[code]public class MainHelloWorld
{
        public static void main(String args[])
        {
                  HelloWorld helloWrld = new HelloWorld();
                  helloWrld.showhelloWorld();
         }
}[/code]

The code starts with class definition – public class MainHelloWorld

The method ‘ public static void main(String args[]) ‘ creates object of HelloWorld class and invokes the method showHelloWorld()

After compiling both the classes, JVM should be invoked by identified by the initial class name

  • C:……..> java MainHelloWorld from command prompt of Windows / DOS
  • $> java MainHelloWorld from terminal of Linux / Unix

JVM can identify only ‘public static void main(String args[]) ‘ in the initial class MainHelloWorld

What are accessors and mutator methods in a Java class? Explain with example for each.

Accessors and mutators are used to enforce data encapsulation

Accessor Methods:

Accessor methods are used to return values of private fields
The naming convention of accessor method is to prefix the word “get” to the method name.

Ex:

[code]public String getLastName()
{
                return firstName;
}[/code]

Accessor methods always returns same data types for private fields
The following code snippet shows how accessor methods are used.

[code]public class Person
{
            //Private fields
            private String firstName;
            private String middleNames;
            private String lastName;
            private String address;
            private String username;

//Constructor method
       public Person(String firstName, String middleNames, String lastName, String address)
       {
           this.firstName = firstName;
           this.middleNames = middleNames;
           this.lastName = lastName;
           this.address = address;
           this.username = "";
       }

//Accessor for firstName

public String getFirstName()
       {
           return firstName;
       }

//Accessor for middleNames
       public String getMiddlesNames()
       {
              return middleNames;
       }

//Accessor for lastName
       public String getLastName()
       {
            return lastName;
       }
}[/code]

The initial class for the above code is

[code]public class PersonExample
{
      public static void main(String[] args)
      {
               Person harry = new Person("Harry", "Mathew Shannon", "Davidson", "12 Pall all");
               System.out.println(harry.getFirstName() + " " + harry.getMiddlesNames() + " " +  harry.getLastName());
      }
}[/code]

Mutator Methods:

  • A mutator method is to set a value to a private field
  • The naming convention of mutator method is to prefix the word “set” to the method name.
    Ex:
    [code]public String setFirstName(String firstName)
    {
          this.firstName=return firstName;
    }[/code]
  •  Mutator methods always sets same data types for private fields
  • The following code snippet shows how mutator methods are used.
    public class Person {
    private firstName, middleName, lastName;
    //Mutator for firstName
    [code]public void setFirstName(String firstName){
    this.firstName = firstName;
    }[/code]

    //Mutator for middleName

    [code]public void setMiddleName(String middleName){
    this.middleName = middleName;
    } [/code]

    //Mutator for lastName

    [code]public void setLastName(String lastName){
    this.lastName = lastName;
    }[/code]

  • Mutator methods accept a parameter which the same data type of their corresponding private field
  • The parameter is used to set the private field’s value. It is now possible to modify the values for the address and username inside the Person object:
  • Now the values of the private fields can be modified
    The following initial class illustrates the use of mutator methods:
    [code]public class PersonExample
    {
            public static void main(String[] args)
            {
                    Person fedrick = new Person("Fedrick", "Paul", "John");
                    fedrick.setMiddleName("Kennedy");
            }
    }[/code]

Explain the importance of ‘this’ reference. Write a code to depicts the use of ‘this’ reference

The ‘this’ reference is used to refer to the current object, i.e., the object whose methods are invoked

‘this’ is used within an instance method or constructor

Any instance variable within an instance method by using the key word ‘this’

When a field is shadowed by a method or a constructor parameter, the use of ‘this’ is quite common

The following code depicts the use of ‘this’:

[code]public class Employee
{
        int empId;
        float salary;
        public void setValues ( int empId, float salary)
        {
               this.empId = empid;// empId – parameter,this.empId – instance variable
               this.salary = salary;// salary – parameter, this.salary – instance variable
        }
}[/code]

Explain static variables and static methods in Java. Provide an example to explain them.

  • The static variables and methods are belongs to the class but not to the object
  • Each class will have one copy of static variables and methods
  • Static members are not part of the objects of the class that instantiates

The following example depicts the use of static members

[code]public class MyUtilitiy{
public static double mean(int[] readings)
{
        int sum = 0; // sum of all the elements
        for (int index=0; index<readings.length; index++)
        {
                sum += readings[index];
        }
             return ((double)sum) / readings.length;
 }//endmethod mean[/code]

  • Mean is a static method and can be invoked as ‘MyUtility.mean(readings); ‘
  • The objects of MyUtility class will not have a copy of mean() method
  • All the methods in java.lang.Math class are static methods. Ex: Math.sqr()
  • Like static methods, static variables are also belongs to the class.
  • Very common use of static variables is to define constants with keyword ‘final’ Ex: Math.PI, Color.RED

LEAVE A REPLY

Please enter your comment!
Please enter your name here