Top Java and JEE Interview Questions and Answers

Last updated on Feb 18 2022
Shankar Shankar Trivedi

What is JAVA?

Java is a high-level programming language and is platform-independent.

Java is a collection of objects. It was developed by Sun Microsystems. There are a lot of applications, websites, and games that are developed using Java.

What are the features of JAVA?

Features of Java are as follows:

  • OOP concepts
    • Object-oriented
    • Inheritance
    • Encapsulation
    • Polymorphism
    • Abstraction
  • Platform independent: A single program works on different platforms without any modification.
  • High Performance: JIT (Just In Time compiler) enables high performance in Java. JIT converts the bytecode into machine language and then JVM starts the execution.
  • Multi-threaded: A flow of execution is known as a Thread. JVM creates a thread which is called the main thread. The user can create multiple threads by extending the thread class or by implementing the Runnable interface.

What do you understand by Aggregation in context of Java?

Aggregation is a form of association in which each object is assigned its own lifecycle. But, there is ownership in this, and the child object cannot belong to any other parent object in any manner.

Name the superclass in Java.

Java.lang. All different non-primitive are inherited directly or indirectly from this class.

Explain the difference between ‘finally’ and ‘finalize’ in Java?

Used with the try-catch block, the ‘finally’ block is used to ensure that a particular piece of code is always executed, even if the execution is thrown by the try-catch block.

In contrast, finalize() is a special method in the object class. It is generally overridden to release system resources when garbage value is collected from the object.

What is an anonymous inner class? How is it different from an inner class?

Any local inner class which has no name is known as an anonymous inner class. Since it doesn’t have any name, it is impossible to create its constructor. It always either extends a class or implements an interface, and is defined and instantiated in a single statement.

A non-static nested class is called an inner class. Inner classes are associated with the objects of the class and they can access all methods and variables of the outer class.

What is a system class?

It is a core class in Java. Since the class is final, we cannot override its behavior through inheritance. Neither can we instantiate this class since it doesn’t provide any public constructors. Hence, all of its methods are static.

 

How to create daemon thread in Java?

We use the class setDaemon(true) to create this thread. We call this method before the start() method, else we get IllegalThreadStateException.

Does Java support global variables? Why/Why not?


No, Java doesn’t support global variables. This is primarily because of two reasons:
● They create collisions in the namespace.
● They break the referential transparency.

 

How is an RMI object developed?


The following steps can be taken to develop an RMI object:
● Define the interface
● Implement the interface
● Compile the interface and their implementations with the java compiler
● Compile server implementation with RMI compiler
● Run RMI registry
● Run application

Explain the differences between time slicing and preemptive scheduling?

In case of time slicing, a task executes for a specified time frame – also known as a slice. After that, it enters the ready queue — a pool of ‘ready’ tasks. The scheduler then picks the next task to be executed based on the priority and other factors.

Whereas under preemptive scheduling, the task with the highest priority is executed either until it enters dead or warning states or if another higher priority task comes along.

Garbage collector thread is what kind of a thread?

It is a daemon thread.

What all does JVM comprise of?

JVM, short for Java Virtual Machine is required by any system to run Java programs. Its architecture essentially comprises of:
● Classloader: It is a subsystem of JVM and its main function is to load class files whenever a Java program is run.
● Heap: it is the runtime data that is used for allocating objects.
● Class area: it holds the class level of each class file such as static variables, metadata, and constant run pool.
● Stack: used for storing temporary variables.
● Register: the register contains the address of the JVM instruction currently being executed
● Execution engine: the EE consists of a virtual processor, an interpreter that executes instructions after reading the bytecode, and a JIT compiler which improves performance when the rate of execution is slow.
● Java Native Interface: it acts as the communication medium for interacting with another application developed in C, C++, etc.

What is object-oriented programming? Is Java an object-oriented language?

Essentially, object-oriented programming is a programming paradigm that works on the concept of objects. Simply put, objects are containers – they contain data in the form of fields and code in the form of procedures. Following that logic, an object-oriented language is a language that works on objects and procedure.

Since Java utilizes 8 primitive datatypes — boolean, byte, char, int, float, long, short, double — which are not objects, Java cannot be considered a 100% object-oriented language.

What is the lifecycle of a thread in Java?

Any thread in Java goes through the following stages in its lifecycle:
● New
● Runnable
● Running
● Non-runnable (blocked)
● Terminated

State the methods used during deserialization and serialization process.

ObjectInputStream.readObject
Reads the file and deserializes the object.

ObjectOuputStream.writeObject
Serialize the object and write the serialized object to a file.

What are volatile variables and what is their purpose?

Volatile variables are variables that always read from the main memory, and not from thread’s cache memory. These are generally used during synchronization.

What are wrapper classes in Java?

All primitive data types in Java have a class associated with them – known as wrapper classes. They’re known as wrapper classes because they ‘wrap’ the primitive data type into an object for the class. In short, they convert Java primitives into objects.

How can we make a singleton class?

By making its constructor private.

What are the important methods of Exception Class in Java?

  • string getMessage()
    ● string toString()
    ● void printStackTrace()
    ● synchronized Throwable getCause()
    ● public StackTraceElement[] getStackTrace()

How can we make a thread in Java?

We can follow either of the two ways to make a thread in Java:
● By extending Thread Class

The disadvantage of this method is that we cannot extend any other classes since the thread class has already been extended.
● By implementing Runnable interface

Explain the differences between get() and load() methods.


The get() and load() methods have the following differences:
● get() returns null if the object is not found, whereas load() throws the ObjectNotFound exception.
● get() always returns a real object, whereas load() returns a proxy object.
● get() method always hits the database whereas load() doesn’t.
● get() should be used if you aren’t sure about the existence of an instance, whereas load() should be used if you are sure that the instance exists.

What is the default value of the local variables?

They aren’t initialized to any default value. Neither are primitives or object references.

What is Singleton in Java?

It is a class with one instance in the whole Java application. For an example java.lang.Runtime is a Singleton class. The prime objective of Singleton is to control the object creation by keeping the private constructor.

What is a servlet?

Servlets are Java software components that add more capabilities to a Java server via technology, API, interface, class, or any web deployment. Servlets run specifically on Java-powered web application servers and are capable of handling complex requests from the web server. Servlets add the benefit of higher performance, robustness, scalability, portability, and ensure safety for the Java applications.

Servlet Process or Execution:

  • This starts when a user sends a request from a web browser.
  • The web server receives and then passes this request to the specific servlet.
  • The Servlet then processes this request to get a specific response with output.
  • The Servlet then sends this response back to the web server.
  • Then the web server gets the information that the browser displays on the screen.

Java Servlets come with multiple classes and interfaces like GenericServlet, ServletRequest, Servlet API, HttpServlet, ServeResponse, etc.

What is Request Dispatcher?

In Servlet, RequestDispatcher acts as an interface for defining an object to receive requests from clients at one side and then dispatching it to particular resources on the other side (that may be a servlet, HTML, JSP). This RequestDispatcher has two methods in general:

void forward(ServletRequest request, ServletResponse response) That allows and forwards the requests from any servlet to server resources in the form of a Servlet, HTML file, or a JSP file.
void include(ServletRequest request, ServletResponse response) That has content for a particular resource in the form of a response such as HTML file, JSP page, or a servlet.

What is the life-cycle of a servlet?

Servlet is a Java software component that has the main function to first take the request, then process the request, and give a response to the user in an HTML page. Here Servlet Container manages the life-cycle of a servlet. Here are the main stages:

  • Loading Servlet.
  • Then initialising the Servlet.
  • Handling the Request (invoking service method).
  • Then destroying the Servlet.

Here is a quick diagram showing the life cycle of a Java Servlet:

 

  • Loading Servlet

The life cycle for Servlet begins with the loading stage in the Servlet container. Servlet loads in either of the two ways with:

    • Setting the servlet as a positive or zero integral value.
    • Secondly, this process may get delays, as the container selects the right servlet to handle the request.

Now the containers first load the Servlet class and then build an instance via the no-argument constructor.

  • Initialising Servlet

Next step is to use the Servlet.init(ServletConfig) method to initialise the Servlet for instance JDBC data source.

  • Handling the Request (Invoking Service Method)

Here the Servlet takes the client requests and performs the required operation using the service() method.

  • Destroying the Servlet

Now the Servlet container destroys the servlet by performing and completing specific tasks and calling the destroy() method in the instance.

What are the different methods of session management in servlets?

Sessions track the user’s activity after they login to the site. Session management provides the mechanism to procure information for every independent user. Here are the four different methods for session management in the servlets:

  • HttpSession
  • Cookies
  • URL Rewriting
  • HTML Hidden field

What is a JDBC Driver?

Java Database Connectivity (JDBC) here acts as a software component that allows Java applications to communicate with a database.

JDBC drivers have the following four types in the environment:

  • JDBC-ODBC bridge driver
  • Network Protocol driver (Middleware driver)
  • Database Protocol driver (fully Java driver)
  • Native-API driver

What is the JDBC Connection interface?

Connections define the sessions between the database and Java applications. JDBC Connection interface is part of the java.sql package only and provides session information for a particular database. These represent multiple SQL statements for executing and results in the context of a single connection interface. Here are the main methods for Connections interface:

  • createStatement(): To create a specific statement object for adding SQL statements to the particular database.
  • setAutoCommit(boolean status): To define the connection of a commit mode to a false or true directive.
  • commit(): That makes all the modifications from the last commit and further releases any database presently held by the specific Connection object.
  • rollback(): That undoes or rollbacks all the changes done in the past or current transaction and also releases the presently held database in the connection object.
  • close(): That terminates or closes the current connection and also releases or clears the JDBC resources instantly.

Name the different modules of the Spring framework?

There are multiple modules in the Spring framework:

  • Web module
  • Struts module
  • Servlet module
  • Core Container module
  • Aspect-Oriented Programming (AOP)
  • Application Context module
  • MVC framework module
  • JDBC abstraction and DAO module
  • OXM module
  • Expression Language module
  • Transaction module
  • Java Messaging Service (JMS) module
  • ORM integration module

These modules are present in groups:

Explain Bean in Spring and list the different scopes of Spring bean.

Beans are one of the fundamental concepts of the Spring framework in managing structures efficiently. In a simple definition, Spring Bean represents the IoC containers that manage the object forming the backbone of applications.

Scopes of Spring Bean:

Scopes play a crucial role in the effective use of Spring beans in the application. Scope helps us to understand the lifecycle of the Spring Bean, and they have the following types.

S. No. Scope and Description
1. Singleton – By default, Spring bean scope has a singleton scope that represents only one instance for Spring IOC container. This same object gets shared for each request.
2. Prototype – In this, a new instance will be called and created for every single bean definition, every time a request is made for a specific bean.
3. Request – In this scope, a single bean will be called and created for every HTTP request for that specific bean.
4. Session – This scope defines the single bean use for a life cycle in a particular global HTTP session.
5. Global-session – This scope allows a single bean for the particular life cycle for implementing in the global HTTP session.

Note: Last three scopes are applicable in the web-aware Spring ApplicationContext only.

Must Read: Why Java is so popular with Developers

Explain the role of DispatcherServlet and ContextLoaderListener.

While configuring XML based Spring MVC configuration in web.xml file, two declarations of DispatcherServlet and ContextLoaderListener play an essential role in complementing the purpose of the framework.

  • DispatcherServlet – 

DispatcherServlet has the primary purpose for managing incoming web requests for specific matching configured URI patterns. DispatcherServlet acts as the front controller for the core of the Spring MVC application and specifically loads the configuration file and then initialises the right beans present in that file. And when annotations are enabled, then it can also check and scan the configurations and packages for all annotated with @Repository, @Component, @Service, or @Controller.

  • ContextLoaderListener – 

ContextLoaderListener here acts as the request listener for starting and shutting down root WebApplicationContext. So, it creates and shares the root application context with child contexts by the DispatcherServlet contexts. Applications can only use one entry for the ContextLoaderListener in the web.xml.

Explain Hibernate architecture.

Hibernate defines a layered architecture that empowers users to operate and perform without knowing the underlying APIs, i.e., Hibernate acts as a framework to build and develop persistence logic independent from the Database software.

Hibernate architecture has the main four layers with:

  • Java application layer
  • Database layer
  • Backend API layer
  • Hibernate framework layer

Elements of the Hibernate Architecture

There are several aspects and scope for Hibernate architecture. To learn more about them, you must know about the elements of Hibernate architecture.

  • SessionFactory: Sessionfactory provides the method to create session objects that are present in the org.hiberate package only. It is thread-safe in nature, immutable, and holds and preserves the second-level cache of the data.
  • Session: Session objects provide the interface for Connection and Database software via the hibernate framework.
  • Transaction: Interface that aids transaction management and allows a change in the database.
  • ConnectiveProvider: A part of the JDBC connections, it separates the main application from the DataSource or DriverManager.
  • TransactionFactory: Represents the factory of the transaction.

What is an exception hierarchy in Java?

The exception defines the unwanted events that present themselves during the run or execution of the program. Exception disrupts the regular flow of the program.
Exception Hierarchy is part of the java.lang.Exception class and comes under the primary Throwable class only. Another subclass ‘Error’ also represents the Throwable class in Java. Though Errors are unusual conditions in case of a failure, still they are not handled or cleared with the Java programs.
There are two primary subclasses for exceptional hierarchy in Java with RuntimeException class and IOCException Class.

What is synchronisation?

Synchronisation in Java defines the capability to manage and control the access of multiple threads to a particular resource. So that, one thread can access a specific resource at the present time. Here, Java allows the development of threads and then synchronising tasks via the synchronising blocks.

These Synchronised blocks allow only one thread execution for a particular time and block the other threads until the current thread exits in the block. Here monitors concept is crucial in implementing the synchronisation in Java. Once the thread goes in a lock phase, it is termed to enter the monitor. Thus, locking all the other threads unless the first thread has exited the monitor.

What are the features that make Java one of the best programming languages?

Here are the top features that make Java for starting your learning curve in the programming world:

  • Simplicity: Java is quite simple to learn and write. Java syntax is in C++ that allows the developers to write programs seamlessly.
  • OOPS: Java is based on the object-oriented programming system (OOPS), thus, empowering to build code in multiple types of objects with different data and behaviour.
  • Dynamic: Java is a complete dynamic language that supports the loading of dynamic classes whenever and wherever required. And it also has comprehensive support for native code language such as C, C++, etc.
  • Platform Independent: Java also supports exclusive and platform-independent programming language, thus, allowing developers to run their program on their platform only.
  • Portability: Java has a reach once write anywhere approach that allows the code to run on any platform.
  • Security: Following the concept of ByteCode, exception handling, and no use of any explicit pointers makes Java a highly secured environment.

Java is also architect neutral with no dependency on any architecture. Strong memory management and automated garbage collection add more robustness to its environment.

What makes Java enable high performance?

Use of Just in Time (JIT) compiler in its architecture makes Java one of the high performing programming languages, as it transforms instructions into bytecodes.

Name most popular Java IDE’s.

There are many IDE’s available in the industry for Java. Here are the top five Java IDEs that you can use to start learning this programming language today:

  • Eclipse
  • Netbeans
  • IntelliJ
  • JDeveloper
  • MyEclipse

Define the main differences between Java and other platforms?

Two main differences that make Java stand out from other platforms are:

  • Java is primarily a software-based platform, while others can be either software or hardware-based platforms.
  • Java runs or executes on any hardware platform, whereas others require specific hardware requirements.

What makes Java have its ‘write once and run anywhere’ (WORA) nature?

Well, the one-word answer is Bytecode. Java compiler converts all the Java programs into a specific Byte Code acting as a mediator language between the machine code and source code. ByteCode can run on any computer and has no platform dependency.

Explain the different types of access specifiers used in Java.

In the Java programming language, access specifiers represent the exact scope for class, variable, or a method. There are four main access specifiers:

  • Public defined variables, methods, or classes are accessible across any method or class.
  • Protected access specifier defines the scope of a class, method, and variable to the same package, within the same class, or to that particular subclass of class.
  • The Default scope is there for all the present classes, variables, and methods with access to the package only.
  • The Private scope keeps access of class, variables, and methods to a particular class only.

Explain the meaning of packages in Java along with their advantages.

Packages are a grouping mechanism for similar types (interface, classes, annotations, and enumerations) ensuring the protection of the assets and comprehensive name management.

Here are the advantages of packages in Java:

  • Packages help us prevent naming conflicts when classes of the same name exist in two different packages.
  • Packages aid in making access control systematically.
  • Build hidden classes to be used by the packages.
  • Helps in locating related classes for the package.

How would you define Constructor in Java?

Constructors are a special block of codes that initialises an object in the time of creation. Though it has a resemblance to instance method, still Constructors are not the method, as they don’t have any explicit return type. So every time an object is being created in the system, there is one constructor called for that to execute. If there is no constructor defined, then the compiler uses a default constructor.

Here is a simple presentation of Constructor in Java:

1

2

3

4

5

6

public class MyClass{

//This is the constructor

MyClass(){

}

..

}

 

What are the different types of constructors used in Java?

There are three types of constructors used in Java:

  • Default Constructor: When a developer doesn’t use a constructor, Java compiler adds a more specific default constructor existing in the .class file.
  • No-argument Constructor: In this case, there are no arguments in the constructor and the compiler doesn’t accept any parameter, as instance variable method gets initialised with specific fixed values.
  • Parameterized Constructor: In this case, one or more parameters are present in the constructor written inside the parentheses of the main element only.

What are the differences between constructors and methods?

The main difference in the constructors and methods are:

  • Purpose: Constructors aim is to initialise the object of a class whereas method performs specific tasks on code execution.
  • The method has return types while constructors do not.
  • In Methods, there are abstract, static, final, and synchronisation while in constructors, you can’t make specific procedures.

Explain the meaning of Local variable and Instance variable?

  • Local variables are present in the method, and the scope exists within the method only.
  • Instance variables are present and defined in the class only with their scope across the class.

Explain the meaning of Class in Java?

In Java, all the codes, variables, and methods are defined in the class.

  • Variables represent attributes that define the state of a particular class.
  • Methods represent where business logic takes its effect. Methods include a set of statements and instructions to match the requirements.

Here is a simple example for a class in Java:

1

2

3

4

5

6

7

public class Addition{ //Class name declaration

int x = 10; //Variable declaration

int y= 10;

public void add(){ //Method declaration

int z = a+b;

}

}

 

Explain the meaning of Object in Java?

Objects are defined as an instance of a class only with specific state and behaviour. For example, a dog with a specific state of name, breed, and colour while behaviour includes barking, wagging the tail, etc. So anytime JVM reads any new() keyword then a corresponding instance will be created. An object needs to be first declared, then instantiated and finally initialised for performing further.

Define the default value for byte datatype in Java language.

For the Byte data type, the default value is 0.

Why is byte data type more beneficial in Java?

As byte data type is almost four times smaller than an integer, so it can store more space for large arrays.

Explain the OOPs concepts in Java.

Ops, are the fundamental concepts of the Java programming language. These include abstraction, polymorphism, inheritance, and encapsulation. Java OOPs concepts empower developers to create variables, methods, and components that further allow them to reuse them in a customised way while maintaining security.

Explain the meaning of Inheritance.

In Java, Inheritance is a specific mechanism that allows one class to acquire the properties (with fields and methods) of another class. Inheritance is one of the basic concepts of Java OOPs.

Inheritance makes it possible to build new classes, add more fields and methods on the existing classes for reusing them in any way.

  • A subclass is the one that inherits the properties of the other class.
  • Superclass is the one whose properties are inherited.

Explain the concepts of Encapsulation in Java?

As one of the primary concepts of Java OOPs, Encapsulation empowers the wrapping of data and code within a single unit only. Encapsulation is also known as Data hiding, with variables of a specific class hidden from all other classes and accessible with the methods from the existing class only.

The two essential things for achieving encapsulation in Java are:

  • Declaring the variables of a specific class as a private.
  • Leveraging public setter and getter methods for making changes and viewing the variable values.

Explain the concepts of Polymorphism.

Polymorphism in Java allows developers to perform a single task in multiple ways. There are two types of Polymorphism in Java with Runtime and Compile time. You can use overriding and overloading methods to operate Polymorphism in Java.

Explain the meaning of interface.

In Java, we cannot achieve multiple inheritances. Here, interface plays a crucial role in overcoming this problem to achieve abstraction, aid multiple inheritances, and also supports loose coupling. Now we have a default, static, and private method in interface with the latest Java updates.

What is meant by Abstract class?

Abstract classes are built with a specific abstract keyword in Java. They represent both abstract and non-abstract methods.

Explain the Abstraction Class in Java?

Abstraction is one of the essential properties for hiding the implementation information from the user and then representing the user functions only. For instance, when you send an SMS from one person to another person. The user gets to know only the message and number while the backend process remains hidden.

You can achieve abstraction in Java using the following two ways:

  • Abstract Class (0 to 100%)
  • Interface (100%)

Explain the difference between Abstraction and Encapsulation in Java.

Here are the main differences:

Abstraction Encapsulation
Abstraction aims to gain information. Encapsulation’s main aim is to contain or procure information.
In the abstraction process, issues or problems are handled at the interface/ design level. In Encapsulation, problems are handled at a specific implementation level.
Abstraction aids in hiding unwanted information. Encapsulation method applies hiding data within a single unit.
Implemented with interfaces and abstract classes. Implemented with a particular access modifier (public, private, and protected).
Use abstract classes and interfaces to hide complexities. Use getters and setters to hide data.
Objects that extend to abstraction must be encapsulated. An object for encapsulation must not be abstracted.

Explain the differences between Abstract class and interface.

Abstract Class Interface
Abstract Class comes with a default constructor. The interface doesn’t have a constructor. So, no further process.
Uses both Abstract and Non-Abstract methods. Only use Abstract methods.
Classes that must extend for Abstract class need only abstract methods throughout their sub-class. Classes that extend to interface must provide implementation across all the methods.
These include instance variables. The interface presents constants only.

Explain the main differences between Array and Array List.

Array Array List
The size needs to be defined for the declaring array.

String[] name = new String[5]

No size requirements; and modifies dynamically.

ArrayList name = new ArrayList

You must specify an index for putting an object inside the array.

name[1] = “dog”

There are no index requirements.

 

name.add(“dog”)

Arrays are not parameterised. From Java 5.0 onwards, ArrayLists have a specific parameterised type.

Explain the difference between static method and instance method.

Static or Class Method Instance Method
You must declare a method static for a static method. All methods with declaration as static come under Instance method only.
No requirements for creating objects in the Static method. The object is a must for calling the instance method.
You cannot access Instance or Non-static methods in the static context. You can access both static and non-static in the instance method.

How to make Constructors static?

Constructors invoked with the object, and static context is part of the class, not the object. Hence, constructors cannot be static and show compiler error if run or executed.

Explain the use of ‘this’ keyword in Java?

In Java, ‘this’ keyword represents a specific reference on the current object. There are multiple uses for this keyword for referring to the current class properties from a variable, constructors, methods, and more. You can also pass this as an argument within constructors or methods. You can also fetch this as a return value from the current class instance. You can also refer to this as a static context.

What is a classloader in Java? What are the different types of ClassLoaders in Java?

Java Classloader’s main function is to dynamically load all classes into the Java Virtual Machine (JVM). ClassLoaders are part of the JRE only. So every time we run a Java program, classloader loads the classes to execute this program. A single ClassLoader loads only a specific class on requirements and uses getClassLoader() method to specify the class. These classes are loaded by calling their names, and in case these are not found then it retrieves or throws a ClassNotFoundException or NoClassDefFoundError.

Java ClassLoader uses three principles in performing tasks with delegation, uniqueness, and visibility.
There are three different types of Java ClassLoader:

  • BootStrap ClassLoader: 

BootStrap ClassLoader represents the parent or superclass for extension classloader and all other classloaders. It has machine code that loads the pure first Java ClassLoader and takes classes from the rt.jar and also known as Primordial ClassLoader.

  • Extension ClassLoader: 

Extension ClassLoader represents the child classloader for the superclass or BootStrap ClassLoader. It loads core java classes from jre/lib/ext, i.e., JDK extension library.

  • System ClassLoader: 

Application or System ClassLoader are further child classes of Extension ClassLoader. It takes and loads a file from the current directory for the program that you can customise with the ‘classpath’ switch.

Explain the meaning of Java Applet.

Java Applet is a program that executes or runs in the web browser only. Applets are specifically designed to function and embed with HTML web pages. Applets have the capability to function full Java applications with the entire use of Java API. JVM is a must requirement to view an applet on the browser. Applet extends with the use of java.applet.Applet class.

What are the types of Applets?

Based on location, there are two types of Java applets as Local Applets that are stored on the same computer or system. The Remote Applets that have files on remote systems.

What are immutable objects in Java?

In Java, immutable objects are the ones whose state does not change after it has been created. Immutable objects are ideal for multi-threaded applications that allow sharing the threads while avoiding synchronisation. Immutable objects are preferred for building simple, sound and reliable code to match with an effective strategy.

What do you mean by JRE (Java Runtime Environment)?

Java Runtime Environment is the software layer that provides support for minimum requirements to run Java programs on a machine. Along with JDK and JRE, these three constitute the fundamental for running and developing Java programs on a specific machine.

What is a JDK part of?

Java Development Kit (JDK) is one of the primary technology packages essential for running Java programs. It can be the implementation from any one of the Java platforms, Standard Edition, Micro or Enterprise edition developed by Oracle for building applications on Windows, Linux, or macOS.

What is a Java Virtual Machine (JVM)?

Java Virtual Machine (JVM) is one of the three fundamental requirements for running and executing Java programs along with JDK and JRE. JVM has two primary functions; first, to empower Java programs to seamlessly run on any machine or system and second to optimise memory to deliver performance.

What are the differences between JDK, JRE, and JVM?

JVM JRE JDK
Java Virtual Machine Java Runtime Environment Java Development Kit
Platform dependent with several software and hardware options available. Software layer that provides support for minimum requirements to run Java programs on a machine. Standard Edition

Enterprise Edition

Micro Edition

 

Three notions as:

  • Specification
  • Implementation
  • Instance
Set of libraries + files that empower JVM on runtime. JRE + development tools
Provides runtime environment for execution. JRE represents the implementation of JVM. Software development environment.

How many types of memory areas are there in JVM?

There are several types of memory areas in JVM:

  • Class Area: This memory stores pre-class structures with the field, pool, method data, and code.
  • Heap stands for runtime memory specifically allocated to the objects.
  • Stack represents the frame’s memory with a local variable, partial results, thread, and a frame for each method.
  • Program Counter Register stores the information for current instruction with the Java Virtual machine execution.
  • Native method Stack stores all the present native methods being used in the current applications.

What is Data Binding in Java?

Data binding represents the connections between class and method, field, variable, constructors, or a method body. Java can handle data binding both statically and dynamically.

What are the different types of data binding in Java?

There are two crucial types of data binding in Java.

  • Static Binding happens at compile time using static, final, and private methods; also known as early binding.
  • Dynamic Binding presents at runtime with no exact information known about the right method during the compile time.

What is a Java Socket?

Sockets help in building communication mechanisms from the two computers via TCP. Sockets are ideally more sufficient and flexible for communications.

Explain the difference between Path and Classpath.

Both path and Classpath represent local environment variables. The path provides the software to locate the executable files while ClassPath specifies the location for .class files in the system.

Is there an abstract method without the use of abstract class?

No, for an abstract method to exist in a class, it must be an abstract class.

What is the process of making a read-only class in Java?

In Java, you can make a read-only class by keeping all the fields private. This specific read-only class will have only getter methods that return private property. It does not allow to modify or change this property as no setter method is available.

1

2

3

4

5

6

7

8

9

//A Read-only class in Java

public class Student{

//private data member

private String institute =”MKG”;

//getter method for institute

public String getInstitute (){

return institute;

}

}

 

What is the process for making a write-only class in Java?

In Java, you can also make a write-only class by keeping all the fields private with the implementation of setter methods only.

1

2

3

4

5

6

7

8

9

// A write-only class in Java

public class Student{

//private data member

private String institute;

//setter method for institute

public void setInstitute (String institute){

this.institute=institute;

}

}

 

Explain the way to access a class in another class in Java?

In Java, there are two ways to access a class in another class as:

  • Using the specific name: We can access a particular class from a different package by using the qualified name or import that package that contains a specific class.
  • Using the relative path: Similarly, we can also use the relative path for that package with a specific class.

What is Exception Handling?

Exception handling represents the mechanism to handle the exception or abnormal conditions during the runtime errors to keep the normal flow of the application. There are three different types of Java Exceptions with Checked Exception, Unchecked Exception, and Error.

Explain the difference between Checked Exception and Unchecked Exception.

  • Checked Exceptions are classes that further extend throwable classes except for RuntimeException such as SQLException, IOException, etc. Checked Exceptions are handled during the compile-time only.
  • Unchecked Exceptions are classes that extend RuntimeException such as NullPointerException, ArithmeticException, etc. and are not handled during the compile time.

Which is the base class for Exception and Error?

Here, the Throwable class represents the base class for Exception and Error.

Mention the Exception handling keyword in Java.

There are five keywords for handling exceptions in Java are:

Keyword Description
try This try block defines the block for placing the execution code. This try block is generally followed by the use of either catch or finally. So, they can’t be used alone.
catch Catch block’s main aim is to handle the exception. You must use this in combination with try block and then finally in the later stage.
finally Finally, block checks the important code of the program that checks whether execution is done or not.
throw The main aim of the throw keyword is to throw an exception from the program.
throws The throws keyword is mainly used for declaring exceptions and not for throwing an exception. It provides information about occurrence for exception and is applied with a method signature.

Explain the importance of the finally block.

Here, the finally block has crucial importance in the smooth running of the program. It is always executed whether the exception is handled or not. Finally, the block comes after the try or catch block. In the JVM, the system will always run the finally block before terminating or closing a file. For each try block present, there can be zero or multiple catch blocks, still there can only one finally block.

Is running a finally block possible without a catch block?

Yes, a finally block can run followed by either a try or catch block, respectively.

Are there any cases for not existing finally block?

Finally block does not run or execute in case the program already exists or brings fatal error for aborting the process.

Explain the main differences between throw and throws.

throw keyword throws keyword
It throws an exception. It declares an exception.
Checked exceptions can’t propagate with throw only. Checked exceptions can propagate with throws.
It is followed by an instance. It is followed by a class.
It is used in the method only. It is used with a specific method signature.
There are no possibilities for multiple exceptions. Whereas in this procedure, multiple exceptions can be declared.

Is there a possibility for an exception to be rethrown?

Yes, if an exception exists, then it can be rethrown.

Explain about Exception Propagation.

The process of exception within the handling procedure is known as exception propagation. For instance, an exception is first handled at the top of the stack and then if it is not caught then the exception drops to the previous method and if not, then it goes down further till either the exception gets caught, or it reaches the bottom of the stack. Checked exceptions by default have no propagation.

Explain the meaning of thread in Java.

In Java, the way or flow of the execution is known as the thread. So, every program contains one thread termed as the main thread created by the JVM. Developers have the power to define their custom threads by adding and extending the Thread class using the interface.

Explain the meaning of the thread pool.

Java thread pool is a group of multiple threads that are continuously waiting for allocated tasks. Here Thread pools work under the service provider that pulls a thread from this pool and then assign them the task for a specific job. The Thread pool adds more performance and stability to the system.

Explain the difference between String and StringBuffer.

String StringBuffer
String class is immutable in nature. StringBuffer class, on the other hand, is mutable.
Strings are slow. StringBuffer otherwise is quite fast.
These consume more memory for creating a new instance. These consume less memory with concat strings.
Strings allow the comparison of its content, as it overrides the equals() method from the Object class. Whereas the StringBuffer class cannot override the equals() method from the Object class.

Explain the difference between StringBuffer and StringBuilder.

StringBuffer StringBuilder
It is synchronised with safety to threads. It is non-synchronised with no safety to threads.
In this, two threads have no call method. In this, two threads can have call methods seamlessly.
Lower or less efficient than StringBuilder. More efficient than StringBuffer.

What is the way to create an immutable class in Java?

In Java, you can create an immutable class by declaring a final class with all its members as final. Let’s take an example to understand this:

1

2

3

4

5

6

7

8

9

10

11

12

public final class Employee{

final String securityNumber;

public Employee(String securityNumber){

this.securityNumber=securityNumber;

}

public String getSecurityNumber(){

return securityNumber;

}

}

 

What are inner classes?

Java Inner classes are defined and declared within an interface or class. Inner classes allow the system to group classes and interfaces logically making them more readable as well as easy to maintain them. Moreover, these classes can access all members of the outer class with methods as well as private data members.

What are the main advantages and disadvantages of using Java Inner classes?

Main advantages for Java inner classes include:

  • Accessibility to all members from the outer classes.
  • Less code to write.
  • More maintenance and readable code.

The main disadvantages for Java inner classes include:

  • Less support from the IDE.
  • A high number of total classes.

Define the types of inner classes in the Java programming language?

Inner classes have three main types:

  • Member Inner class that specifies a class within the class using the outside method.
  • Anonymous Inner Class for extending the class or specifying the implementation of an interface.
  • Local Inner Class to create a class within the method.

Define a nested class.

Nested classes are defined or declared within a class or interface only. A nested class can specifically access all the members of the outer class with methods and private data members too. Here is a simple syntax of a nested class:

1

2

3

4

5

6

class Java_Outer_class{

//code

class Java_Nested_class{

//code

}

}

 

Can you explain the difference between inner classes and nested classes?

All inner classes are defined as non-static nested classes. So, inner classes are part of the nested classes only.

How would you define the meaning of Collections in Java?

Collections in Java are a group of multiple objects that present as one unit; primarily known as a Collections of the objects. They are also called a Collection Framework or architecture that provides storing space for objects and further manipulates design for changes.

Here are the main functions performed by the Java Collections:

  • Sorting
  • Searching
  • Insertion
  • Manipulation
  • Deletion

There are many interfaces and classes that are part of the collections.

Which interfaces and classes are available in the collections?

Here is the list of the interfaces and classes that are available with the collections in Java.

  • Interfaces: Collection, Queue, Sorted Set, Sorted Map, List, Set, Map
  • Classes: Lists, Vector, Array List, Linked List
  • Sets: Hash set, Tree set, Linked Hash Set
  • Maps: Hash map, Hash Table, TreeMap, Linked Hashed Map
  • Queue: Priority Queue

Explain sorted and ordered in relation to collections in Java?

  • Sorted: Sorting allows the group of objects to apply internally or externally to sort them in a particular collection, based on their different properties.
  • Ordered: Defines the values that are sorted on the basis of the values added in the collection and iterate them in a particular order.

Which are the different lists available in the collection?

Lists store values based on their index position with the duplication allowed. Here are the main types of lists:
Array Lists: Uses the Random Access Interface, provides order collection by the index, not sorted, and offers quick iteration. Here is an example to understand this:

1

2

3

4

5

6

7

8

9

10

11

12

13

public class Fruits{

public static void main (String [ ] args){

ArrayList <String>names=new ArrayList <String>();

names.add (“apple”);

names.add (“avocado”);

names.add (“cherry”);

names.add (“kiwi”);

names.add (“oranges”);

names.add (“banana”);

names.add (“kiwi”);

System.out.println (names);

}

}

 

Output is as follows:

[Apple, avocado, cherry, kiwi, oranges, banana, kiwi]

With the output, you can check that Array List keeps the original insertion order and also allows duplicates. Though not sorted.

Vector: also uses the Random-access method, are synchronised, and offers support for thread safety.

Let us understand this with an example:

1

2

3

4

5

6

7

8

9

10

11

12

13

public class Fruits{

public static void main (String [ ] args){

ArrayList <String>names=new vector <String>();

names.add (“kiwi”);

names.add (“oranges”);

names.add (“banana”);

names.add (“apple”);

names.add (“avocado”);

names.add (“cherry”);

names.add (“kiwi”);

System.out.println (names);

}

}

 

Output is as follows:

[kiwi, oranges, banana, apple, avocado, cherry, kiwi]

Vector lists follow the original insertion order and also support the duplicates.

Linked List: It is also an ideal choice for deletion and insertion, elements are double-linked, but is slow in performance.

Example for Linked list:

1

2

3

4

5

6

7

8

9

10

11

12

13

public class Fruits{

public static void main (String [ ] args){

ArrayList <String>names=new vector <String>();

names.add (“kiwi”);

names.add (“oranges”);

names.add (“banana”);

names.add (“apple”);

names.add (“avocado”);

names.add (“cherry”);

names.add (“kiwi”);

System.out.println (names);

}

}

 

Output is as follows:

[Apple, avocado, cherry, kiwi, oranges, banana, kiwi]

It also follows the original insertion order and accepts duplicates.

What are the main differences between collection and collections in Java?

The main differences are as follows:

  • The collection represents an interface while Collections is particularly class only.
  • Collection interface provides multiple functionalities for structuring data as List, Set, and Queue. Whereas Collection class’s main aim is limited to sort and synchronise the elements of the collection.

Explain the Priority Queue.

Priority Queue defines the queue interface for handling linked lists with the purpose of a Priority-in and Priority-out. Queue generally follows a first in first out (FIFO) algorithm, still you can queue elements based on specific requirements, and then we can implement PriorityQueue for customisation. With Priority Queue, it depends on the priority heap either naturally or via the comparator on their relative priority.

When is it ideal to use and compare the Runnable interface in Java?

When we need to extend a class with some other classes and not the threads then runnable interfaces are an ideal choice.

What is the difference between start() and run() method of thread class?

The start() method adds and creates a new thread. And code in run() method gets executed in the new thread only. While run() method will execute code in the current thread only.

What is Multithreading?

In Java, we can execute multiple threads simultaneously, which is known as Multithreading. It helps the program to multitask while taking less memory and giving higher performance. In Multithreading, threads are lightweight, share the same space, and are quite affordable in every aspect.

Explain the difference between process and threads.

Here the main differences are:

  • A Java program in execution is termed as a process while a thread represents a subset of the process only.
  • Processes represent different spaces in the memory, while threads have the same address.
  • Processes are entirely independent, while threads are part of the process only.
  • Slow communication between inter-processes, while the inter-thread communication is swift.

Explain the meaning of inter-thread communication.

Inter-thread communication is defined as the process that allows communication between multiple synchronised threads. Its main aim is to avoid thread pooling in Java. Communication is achieved through the methods of wait(), notify(), and notifyAll().

Explain the wait() method.

With wait() method, you can allow the thread to be in the waiting stage while the other thread is locked on the object. Thus, the wait() method can add significant waiting duration for threads.

Here is a syntax to represent this:

1

2

3

4

5

6

public static void main (String[] args){

Thread t = new Thread ();

t.start ();

Synchronized (t) {

Wait();

}

 

What is the main difference between the notify() and notifyAll() method in Java?

notify() method sends a signal to wake up only a particular thread in the waiting pool whereas notifyAll() wakes up all the threads in the waiting stage of the pool.

Define the main differences between sleep() and wait().

Sleep() pauses or stops the current thread progress by suspending execution for a particular duration while not releasing the lock. While wait() causes a waiting duration for a thread after invoking a notify() method for waking later.

Explain the join() method in relation to the thread in Java. 

The join() method allows combining one thread with one of the continuous threads. Here is a syntax for join() method:

1

2

3

4

5

public static void main (String[] args){

Thread t = new Thread ();

t.start ();

t.join ();

}

 

Explain the Yield method of Thread.

Yield method is a static method and does not release any lock in the threads. Here, a Yield() method empowers the current thread to a more runnable thread while allowing the other threads for keeping the execution. Thus, equal thread priority threads can run regularly.

What is the Starvation stage?

Starvation is a phase when a thread fails to gain access to shared resources and is not able to make any progress.

What is Deadlock for a thread?

Deadlock defines a stage when two or multiple threads get blocked forever in wait for each other.

Define Serialisation and Deserialisation in Java?

Serialisation is the process for transforming the state of an object into a particular byte stream ideally suited for JPA, JMS, RMI, JPA, and Hibernate technologies. While the opposite process of changing a byte stream into an object is called deserialisation. Both processes are platform-independent, so they allow you to serialise in one platform and deserialise into an entirely different platform efficiently.

What is the importance of transient variables?

The importance of transient variables lies in the deserialisation that is set to the default variables and not used with the static variables.

What are volatile variables?

Volatile variables play a crucial role in the synchronisation and reading from the main memory while avoiding the thread cache memory.

What is SerialVersionUID?

In the Serialised process, an object is stamped with a specific version ID number for the respective object class. This number is termed as SerialVersionUID and plays a crucial role in verifying during the deserialisation process for checking the compatibility on sender and receiver, respectively.

What is the process for cloning an object in Java?

With Object cloning, you can create an exact copy of the original object. For cloning to be possible, a class must have the support for cloning with the java.lang.Cloneable interface and allow override clone() method from the original object class.

Here a simple syntax for the clone() method:

protected Object clone() throws CloneNotSupportedException

In case the clone does not implement it then it generally throws an exception with the ‘CloneNotSupportedException’.

Define the class that remains superclass for each class?

Object class.

Define whether a string class is mutable or immutable?

String class represents an immutable state. So once an object is created, this cannot change any further.

How do you differentiate between StringBuffer and StringBuilder class?

  • StringBuilder is quicker than the StringBuffer.
  • StringBuffer is synchronised while StringBuilder is not synchronised.
  • StringBuffer offers a thread-safe environment, while StringBuilder has no thread-safe capability.

What is the use of the toString() method in Java?

In Java, toString() retrieves or returns the string representation from any object.

What is a garbage collection in Java?

As objects get dynamically allocated via the operator, Java system also handles the deallocation of the memory used automatically in case there are no references for the object that remains for a significant duration. This process of keeping the system free of objects that don’t have use is known as Garbage Collection in Java. The main aim of the garbage collection is to make it more memory efficient management.

What is the number of times a garbage collector calls finalize() method for a specific object?

You can call the finalize() method in garbage collection only once.

Define the ways to call the garbage collection.

There are two ways to call the garbage collection:

  • System.gc()
  • Runtime.getRuntime().gc()

Can we force Garbage Collection?

No, this is an automatic process. You can call the garbage collection method but can’t force it. Still, it does not guarantee that it would be complete.

What are the different data types in Java? Explain.

Here is a shortlist to help you with data types:

  • byte – 8 bit
  • short – 16 bit
  • char – 16 bit Unicode
  • int – 32 bit (whole number)
  • float – 32 bit (real number)
  • long – 64 bit (Single precision)
  • double – 64 bit (double precision)

Define the Unicode.

Unicodes are a way to define international characters in human languages, and Java uses this Unicode structure to symbolise the characters.

Define literal.

A literal is a constant value assigned to a particular variable

  // Here 105 is a literal

int num = 105

Define the type of casting in Java?

In the case of assigning a value of one data type to another data type, these two may or may not be compatible and require conversion. Java will automatically convert in case of compatible data types. While if the data types are not compatible, then these must be cast for successful conversion. Casting has two basic types: Implicit and Explicit.

Explain the two different types of typecasting?

  • Implicit: Defines the storing of values from smaller data types into larger data types, performed by the compiler only.
  • Explicit: Defines the storing of values from larger data types into smaller data types that may result in information loss.

Explain JDK, JRE and JVM?

JDK vs JRE vs JVM
JDK JRE JVM
It stands for Java Development Kit. It stands for Java Runtime Environment. It stands for Java Virtual Machine.
It is the tool necessary to compile, document and package Java programs. JRE refers to a runtime environment in which Java bytecode can be executed. It is an abstract machine. It is a specification that provides a run-time environment in which Java bytecode can be executed.
It contains JRE + development tools. It’s an implementation of the JVM which physically exists. JVM follows three notations: Specification, Implementation, and Runtime Instance.

Explain public static void main(String args[]) in Java.

main() in Java is the entry point for any Java program. It is always written as public static void main(String[] args).

  • public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
  • static: It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the class.
  • void: It is the return type of the method. Void defines the method which will not return any value.
  • main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.
  • String args[]: It is the parameter passed to the main method.

Why Java is platform independent?

Java is called platform independent because of its byte codes which can run on any system irrespective of its underlying operating system.

Why Java is not 100% Object-oriented?

Java is not 100% Object-oriented because it makes use of eight primitive data types such as boolean, byte, char, int, float, double, long, short which are not objects.

What are wrapper classes in Java?

Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. Refer to the below image which displays different primitive type, wrapper class and constructor argument.

What are constructors in Java?

In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.

There are two types of constructors:

  1. Default Constructor: In Java, a default constructor is the one which does not take any inputs. In other words, default constructors are the no argument constructors which will be created by default in case you no other constructor is defined by the user. Its main purpose is to initialize the instance variables with the default values. Also, it is majorly used for object creation.
  2. Parameterized Constructor: The parameterized constructor in Java, is the constructor which is capable of initializing the instance variables with the provided values. In other words, the constructors which take the arguments are called parameterized constructors.

What is singleton class in Java and how can we make a class singleton?

Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.

What is the difference between Array list and vector in Java?

ArrayList Vector
Array List is not synchronized.  Vector is synchronized.
Array List is fast as it’s non-synchronized. Vector is slow as it is thread safe.
If an element is inserted into the Array List, it increases its Array size by 50%. Vector defaults to doubling size of its array.
Array List does not define the increment size. Vector defines the increment size.
Array List can only use Iterator for traversing an Array List. Vector can use both Enumeration and Iterator for traversing.

What is the difference between equals() and == in Java?

Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.

“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare the values of two objects.

What are the differences between Heap and Stack Memory in Java?

The major difference between Heap and Stack memory are:

Features Stack Heap
Memory Stack memory is used only by one thread of execution. Heap memory is used by all the parts of the application.
Access Stack memory can’t be accessed by other threads. Objects stored in the heap are globally accessible.
Memory Management Follows LIFO manner to free memory. Memory management is based on the generation associated with each object.
Lifetime Exists until the end of execution of the thread. Heap memory lives from the start till the end of application execution.
Usage Stack memory only contains local primitive and reference variables to objects in heap space. Whenever an object is created, it’s always stored in the Heap space.

What is a package in Java? List down various advantages of packages.

Packages in Java, are the collection of related classes and interfaces which are bundled together. By using packages, developers can easily modularize the code and optimize its reuse. Also, the code within the packages can be imported by other classes and reused. Below I have listed down a few of its advantages:

  • Packages help in avoiding name clashes
  • They provide easier access control on the code
  • Packages can also contain hidden classes which are not visible to the outer classes and only used within the package
  • Creates a proper hierarchical structure which makes it easier to locate the related classes

Why pointers are not used in Java?

Java doesn’t use pointers because they are unsafe and increases the complexity of the program. Since, Java is known for its simplicity of code, adding the concept of pointers will be contradicting. Moreover, since JVM is responsible for implicit memory allocation, thus in order to avoid direct access to memory by the user,  pointers are discouraged in Java.

What is JIT compiler in Java?

JIT stands for Just-In-Time compiler in Java. It is a program that helps in converting the Java bytecode into instructions that are sent directly to the processor. By default, the JIT compiler is enabled in Java and is activated whenever a Java method is invoked. The JIT compiler then compiles the bytecode of the invoked method into native machine code, compiling it “just in time” to execute. Once the method has been compiled, the JVM summons the compiled code of that method directly rather than interpreting it. This is why it is often responsible for the performance optimization of Java applications at the run time.

What are access modifiers in Java?

In Java, access modifiers are special keywords which are used to restrict the access of a class, constructor, data member and method in another class. Java supports four types of access modifiers:

  1. Default
  2. Private
  3. Protected
  4. Public
Modifier Default Private Protected Public
Same class YES YES YES YES
Same Package subclass YES NO YES YES
Same Package non-subclass YES NO YES YES
Different package subclass NO NO YES YES
Different package non-subclass NO NO NO YES

Define a Java Class.

A class in Java is a blueprint which includes all your data.  A class contains fields (variables) and methods to describe the behavior of an object. Let’s have a look at the syntax of a class.

1

2

3

class Abc {

member variables // class body

methods}

What is an object in Java and how is it created?

An object is a real-world entity that has a state and behavior. An object has three characteristics:

  1. State
  2. Behavior
  3. Identity

An object is created using the ‘new’ keyword. For example:

ClassName obj = new ClassName();

What is Object Oriented Programming?

Object-oriented programming or popularly known as OOPs is a programming model or approach where the programs are organized around objects rather than logic and functions. In other words, OOP mainly focuses on the objects that are required to be manipulated instead of logic. This approach is ideal for the programs large and complex codes and needs to be actively updated or maintained.

What are the main concepts of OOPs in Java?

Object-Oriented Programming or OOPs is a programming style that is associated with concepts like:

  1. Inheritance: Inheritance is a process where one class acquires the properties of another.
  2. Encapsulation: Encapsulation in Java is a mechanism of wrapping up the data and code together as a single unit.
  3. Abstraction: Abstraction is the methodology of hiding the implementation details from the user and only providing the functionality to the users.
  4. Polymorphism: Polymorphism is the ability of a variable, function or object to take multiple forms.

What is the difference between a local variable and an instance variable?

In Java, a local variable is typically used inside a method, constructor, or a block and has only local scope. Thus, this variable can be used only within the scope of a block. The best benefit of having a local variable is that other methods in the class won’t be even aware of that variable.

Example

1

2

3

4

if(x > 100)

{

String test = “Tecklearn”;

}

 

Whereas, an instance variable in Java, is a variable which is bounded to its object itself. These variables are declared within a class, but outside a method. Every object of that class will create it’s own copy of the variable while using it. Thus, any changes made to the variable won’t reflect in any other instances of that class and will be bound to that particular instance only.

1

2

3

4

class Test{

public String EmpName;

public int empAge;

}

Differentiate between the constructors and methods in Java?

Methods Constructors
1. Used to represent the behavior of an object 1. Used to initialize the state of an object
2. Must have a return type 2. Do not have any return type
3. Needs to be invoked explicitly 3. Is invoked implicitly
4. No default method is provided by the compiler 4. A default constructor is provided by the compiler if the class has none
5. Method name may or may not be same as class name 5. Constructor name must always be the same as the class name

In case you are facing any challenges with these Java interview questions, please comment on your problems in the section below.

What is final keyword in Java?

final is a special keyword in Java that is used as a non-access modifier. A final variable can be used in different contexts such as:

  • final variable

When the final keyword is used with a variable then its value can’t be changed once assigned. In case the no value has been assigned to the final variable then using only the class constructor a value can be assigned to it.

  • final method

When a method is declared final then it can’t be overridden by the inheriting class.

  • final class

When a class is declared as final in Java, it can’t be extended by any subclass class but it can extend other class.

 What is the difference between break and continue statements?

break continue
1. Can be used in switch and loop (for, while, do while) statements 1. Can be only used with loop statements
2. It causes the switch or loop statements to terminate the moment it is executed 2. It doesn’t terminate the loop but causes the loop to jump to the next iteration
3. It terminates the innermost enclosing loop or switch immediately 3. A continue within a loop nested with a switch will cause the next loop iteration to execute

Example break:

1

2

3

4

5

6

7

8

for (int i = 0; i < 5; i++)

{

if (i == 3)

{

break;

}

System.out.println(i);

}

Example continue:

1

2

3

4

5

6

7

8

for (int i = 0; i < 5; i++)

{

if(i == 2)

{

continue;

}

System.out.println(i);

}

What is an infinite loop in Java? Explain with an example.

An infinite loop is an instruction sequence in Java that loops endlessly when a functional exit isn’t met. This type of loop can be the result of a programming error or may also be a deliberate action based on the application behavior. An infinite loop will terminate automatically once the application exits.

For example:

1

2

3

4

5

6

7

8

public class InfiniteForLoopDemo

{

public static void main(String[] arg) {

for(;;)

System.out.println(“Welcome to Tecklearn!”);

// To terminate this program press ctrl + c in the console.

}

}

 

What is the difference between this() and super() in Java?

In Java, super() and this(), both are special keywords that are used to call the constructor.

this() super()
1. this() represents the current instance of a class 1. super() represents the current instance of a parent/base class
2. Used to call the default constructor of the same class 2. Used to call the default constructor of the parent/base class
3. Used to access methods of the current class 3. Used to access methods of the base class
4.  Used for pointing the current class instance 4. Used for pointing the superclass instance
5. Must be the first line of a block 5. Must be the first line of a block

What is Java String Pool?

Java String pool refers to a collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then the same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned.

Differentiate between static and non-static methods in Java.

Static Method Non-Static Method
1. The static keyword must be used before the method name 1. No need to use the static keyword before the method name
2. It is called using the class (className.methodName) 2. It is can be called like any general method
3. They can’t access any non-static instance variables or methods 3. It can access any static method and any static variable without creating an instance of the class

What is constructor chaining in Java?

In Java, constructor chaining is the process of calling one constructor from another with respect to the current object. Constructor chaining is possible only through legacy where a subclass constructor is responsible for invoking the superclass’ constructor first. There could be any number of classes in the constructor chain. Constructor chaining can be achieved in two ways:

  1. Within the same class using this()
  2. From base class using super()

Difference between String, StringBuilder, and StringBuffer.

Factor String StringBuilder StringBuffer
Storage Area Constant String Pool Heap Area Heap Area
Mutability Immutable Mutable Mutable
Thread Safety Yes No Yes
Performance Fast More efficient Less efficient

What is a classloader in Java?

The Java ClassLoader is a subset of JVM (Java Virtual Machine) that is responsible for loading the class files. Whenever a Java program is executed it is first loaded by the classloader. Java provides three built-in classloaders:

  1. Bootstrap ClassLoader
  2. Extension ClassLoader
  3. System/Application ClassLoader

Why Java Strings are immutable in nature?

In Java, string objects are immutable in nature which simply means once the String object is created its state cannot be modified. Whenever you try to update the value of that object instead of updating the values of that particular object, Java creates a new string object. Java String objects are immutable as String objects are generally cached in the String pool. Since String literals are usually shared between multiple clients, action from one client might affect the rest. It enhances security, caching, synchronization, and performance of the application.

What is the difference between an array and an array list?

Array ArrayList
Cannot contain values of different data types Can contain values of different data types.
Size must be defined at the time of declaration Size can be dynamically changed
Need to specify the index in order to add data No need to specify the index
Arrays are not type parameterized Arraylists are type
Arrays can contain primitive data types as well as objects Arraylists can contain only objects, no primitive data types are allowed

What is a Map in Java?

In Java, Map is an interface of Util package which maps unique keys to values. The Map interface is not a subset of the main Collection interface and thus it behaves little different from the other collection types. Below are a few of the characteristics of Map interface:

  1. Map doesn’t contain duplicate keys.
  2. Each key can map at max one value.

What is collection class in Java? List down its methods and interfaces.

In Java, the collection is a framework that acts as an architecture for storing and manipulating a group of objects. Using Collections, you can perform various tasks like searching, sorting, insertion, manipulation, deletion, etc. Java collection framework includes the following:

  • Interfaces
  • Classes
  • Methods

The below image shows the complete hierarchy of the Java Collection.

 

 

What is Polymorphism?

Polymorphism is briefly described as “one interface, many implementations”. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow an entity such as a variable, a function, or an object to have more than one form. There are two types of polymorphism:

  1. Compile time polymorphism
  2. Run time polymorphism

Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and interface.

What is runtime polymorphism or dynamic method dispatch?

In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. Let’s take a look at the example below to understand it better.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

class Car {

void run()

{

System.out.println(“car is running”);

}

}

class Audi extends Car {

void run()

{

System.out.prinltn(“Audi is running safely with 100km”);

}

public static void main(String args[])

{

Car b= new Audi();    //upcasting

b.run();

}

}

What is abstraction in Java?

Abstraction refers to the quality of dealing with ideas rather than events. It basically deals with hiding the details and showing the essential things to the user. Thus, you can say that abstraction in Java is the process of hiding the implementation details from the user and revealing only the functionality to them. Abstraction can be achieved in two ways:

  1. Abstract Classes (0-100% of abstraction can be achieved)
  2. Interfaces (100% of abstraction can be achieved)

What do you mean by an interface in Java?

An interface in Java is a blueprint of a class or you can say it is a collection of abstract methods and static constants. In an interface, each method is public and abstract but it does not contain any constructor. Thus, interface basically is a group of related methods with empty bodies. Example:

public interface Animal {

public void eat();

public void sleep();

public void run();

}

What is the difference between abstract classes and interfaces?

Abstract Class Interfaces
An abstract class can provide complete, default code and/or just the details that have to be overridden An interface cannot provide any code at all, just the signature
In the case of an abstract class, a class may extend only one abstract class A Class may implement several interfaces
An abstract class can have non-abstract methods All methods of an Interface are abstract
An abstract class can have instance variables An Interface cannot have instance variables
An abstract class can have any visibility: public, private, protected An Interface visibility must be public (or) none
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method
An abstract class can contain constructors An Interface cannot contain constructors
Abstract classes are fast Interfaces are slow as it requires extra indirection to find the corresponding method in the actual class

What is inheritance in Java?

Inheritance in Java is the concept where the properties of one class can be inherited by the other. It helps to reuse the code and establish a relationship between different classes. Inheritance is performed between two types of classes:

  1. Parent class (Super or Base class)
  2. Child class (Subclass or Derived class)

A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class.

What are the different types of inheritance in Java?

Java supports four types of inheritance which are:

  1. Single Inheritance: In single inheritance, one class inherits the properties of another i.e there will be only one parent as well as one child class.
  2. Multilevel Inheritance: When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent class but at different levels, such type of inheritance is called Multilevel Inheritance.
  3. Hierarchical Inheritance: When a class has more than one child classes (subclasses) or in other words, more than one child classes have the same parent class, then such kind of inheritance is known as hierarchical.
  4. Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance.

What is method overloading and method overriding?

Method Overloading:

  • In Method Overloading, Methods of the same class shares the same name but each method must have a different number of parameters or parameters having different types and order.
  • Method Overloading is to “add” or “extend” more to the method’s behavior.
  • It is a compile-time polymorphism.
  • The methods must have a different signature.
  • It may or may not need inheritance in Method Overloading.

Let’s take a look at the example below to understand it better.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

class Adder {

Static int add(int a, int b)

{

return a+b;

}

Static double add( double a, double b)

{

return a+b;

}

public static void main(String args[])

{

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(12.3,12.6));

}}

Method Overriding:  

  • In Method Overriding, the subclass has the same method with the same name and exactly the same number and type of parameters and same return type as a superclass.
  • Method Overriding is to “Change” existing behavior of the method.
  • It is a run time polymorphism.
  • The methods must have the same signature.
  • It always requires inheritance in Method Overriding.

Let’s take a look at the example below to understand it better.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

class Car {

void run(){

System.out.println(“car is running”);

}

Class Audi extends Car{

void run()

{

System.out.prinltn(“Audi is running safely with 100km”);

}

public static void main( String args[])

{

Car b=new Audi();

b.run();

}

}

Can you override a private or static method in Java?

You cannot override a private or static method in Java. If you create a similar method with the same return type and same method arguments in child class then it will hide the superclass method; this is known as method hiding. Similarly, you cannot override a private method in subclass because it’s not accessible there. What you can do is create another private method with the same name in the child class. Let’s take a look at the example below to understand it better.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

class Base {

private static void display() {

System.out.println(“Static or class method from Base”);

}

public void print() {

System.out.println(“Non-static or instance method from Base”);

}

class Derived extends Base {

private static void display() {

System.out.println(“Static or class method from Derived”);

}

public void print() {

System.out.println(“Non-static or instance method from Derived”);

}

public class test {

public static void main(String args[])

{

Base obj= new Derived();

obj1.display();

obj1.print();

}

}

What is multiple inheritance? Is it supported by Java?

If a child class inherits the property from multiple classes is known as multiple inheritance. Java does not allow to extend multiple classes.

The problem with multiple inheritance is that if multiple parent classes have the same method name, then at runtime it becomes difficult for the compiler to decide which method to execute from the child class.

Therefore, Java doesn’t support multiple inheritance. The problem is commonly referred to as Diamond Problem.

In case you are facing any challenges with these java interview questions, please comment on your problems in the section below.

What is encapsulation in Java?

Encapsulation is a mechanism where you bind your data(variables) and code(methods) together as a single unit. Here, the data is hidden from the outer world and can be accessed only via current class methods. This helps in protecting the data from any unnecessary modification. We can achieve encapsulation in Java by:

  • Declaring the variables of a class as private.
  • Providing public setter and getter methods to modify and view the values of the variables.

What is an association?

Association is a relationship where all object has their own lifecycle and there is no owner. Let’s take the example of Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. These relationships can be one to one, one to many, many to one and many to many.

What do you mean by aggregation?

An aggregation is a specialized form of Association where all object has their own lifecycle but there is ownership and child object cannot belong to another parent object. Let’s take an example of Department and teacher. A single teacher cannot belong to multiple departments, but if we delete the department teacher object will not destroy.

What is composition in Java?

Composition is again a specialized form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of a relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room cannot belong to two different houses if we delete the house room will automatically delete.

What is a marker interface?

A Marker interface can be defined as the interface having no data member and member functions. In simpler terms, an empty interface is called the Marker interface. The most common examples of Marker interface in Java are Serializable, Cloneable etc. The marker interface can be declared as follows.

1

2

public interface Serializable{

}

What is object cloning in Java?

Object cloning in Java is the process of creating an exact copy of an object. It basically means the ability to create an object with a similar state as the original object. To achieve this, Java provides a method clone() to make use of this functionality. This method creates a new instance of the class of the current object and then initializes all its fields with the exact same contents of corresponding fields. To object clone(), the marker interface java.lang.Cloneable must be implemented to avoid any runtime exceptions. One thing you must note is Object clone() is a protected method, thus you need to override it.

What is a copy constructor in Java?

Copy constructor is a member function that is used to initialize an object using another object of the same class. Though there is no need for copy constructor in Java since all objects are passed by reference. Moreover, Java does not even support automatic pass-by-value.

What is a constructor overloading in Java?

In Java, constructor overloading is a technique of adding any number of constructors to a class each having a different parameter list. The compiler uses the number of parameters and their types in the list to differentiate the overloaded constructors.

1

2

3

4

5

6

7

8

9

10

11

12

class Demo

{

int i;

public Demo(int a)

{

i=k;

}

public Demo(int a, int b)

{

//body

}

}

What is a servlet?

  • Java Servlet is server-side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
  • The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.
  • All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.
  • Most of the times, web applications are accessed using HTTP protocol and thats why we mostly extend HttpServlet class. Servlet API hierarchy is shown in below image.

What are the differences between Get and Post methods?

Get Post
Limited amount of data can be sent because data is sent in header. Large amount of data can be sent because data is sent in body.
 Not Secured because data is exposed in URL bar.  Secured because data is not exposed in URL bar.
 Can be bookmarked  Cannot be bookmarked
 Idempotent  Non-Idempotent
 It is more efficient and used than Post  It is less efficient and used

What is Request Dispatcher?

RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response.

There are two methods defined in this interface:

1.void forward()

2.void include()

What are the differences between forward() method and sendRedirect() methods?

 

forward() method SendRedirect() method
forward() sends the same request to another resource. sendRedirect() method sends new request always because it uses the URL bar of the browser.
 forward() method works at server side.  sendRedirect() method works at client side.
 forward() method works within the server only. sendRedirect() method works within and outside the server.

What is the life-cycle of a servlet?

There are 5 stages in the lifecycle of a servlet:

  1. Servlet is loaded
  2. Servlet is instantiated
  3. Servlet is initialized
  4. Service the request
  5. Servlet is destroyed

How does cookies work in Servlets?

  • Cookies are text data sent by server to the client and it gets saved at the client local machine.
  • Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.
  • HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.
  • Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.

What are the differences between ServletContext vs ServletConfig?

The difference between ServletContext and ServletConfig in Servlets JSP is in below tabular format.

ServletConfig ServletContext
Servlet config object represent single servlet It represent whole web application running on particular JVM and common for all the servlet
Its like local parameter associated with particular servlet Its like global parameter associated with whole application
It’s a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope ServletContext has application wide scope so define outside of servlet tag in web.xml file.
getServletConfig() method is used to get the config object getServletContext() method is  used to get the context object.
for example shopping cart of a user is a specific to particular user so here we can use servlet config To get the MIME type of a file or application session related information is stored using servlet context object.

What are the different methods of session management in servlets?

Session is a conversational state between client and server and it can consist of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.

Some of the common ways of session management in servlets are:

  1. User Authentication
  2. HTML Hidden Field
  3. Cookies
  4. URL Rewriting
  5. Session Management API

What is JDBC Driver?

JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:

  1. JDBC-ODBC bridge driver
  2. Native-API driver (partially java driver)
  3. Network Protocol driver (fully java driver)
  4. Thin driver (fully java driver)

What are the steps to connect to a database in java?

  • Registering the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connection

What is the static method?

A static method can be invoked without the need for creating an instance of a class. A static method belongs to the class rather than an object of a class. A static method can access static data member and can change the value of it.

What’s the exception?

Exceptions Unusual conditions during the program. This may be due to an incorrect logic written by incorrect user input or programmer.

In simple terms, how would you define Java?

Java is a high-level, platform-independent, object-oriented portal, and offers support with high performance for building sophisticated programs, applications, and websites. Java is a general-purpose programming language that empowers developers to build rich functionality applications with their write once run anywhere (WORA) environment. James Arthur Gosling, a computer scientist from Canada, developed Java in 1991 and is popularly known as ‘Dr Java’. Today, Java has become an essential foundation for the modern IT industry.

What is Java String Pool?

A String Pool in Java is a distinct place that has a pool of strings stored via the Java Heap Memory. Here, String represents a special class in Java, and string objects can be created using either a new operator or using values in double-quotes.
The String is immutable in Java, thus, making feasibility of String pool and then the further implementation via String interning concepts.

What is a collection class in Java? List down its methods and interfaces?

Java Collection Classes are special classes, which are exclusively used with static methods that work specifically on return collections. Java Collection by default inherit a class and have two essential features as:

  •  They support and operate with polymorphic algorithms that return new collections for every specific collection.
  • Methods in Java Collection throw a NullPointerException in case the class objects or collections have Null value.

These are represented and declared as Java.util.Collectionclass.

There are more than 60 methods, modifiers, and types of Java Collection classes. Here is a list of the topmost important methods in Java Collection Class:

 

S. No. Modifier, Method, and Type Description
1. static <T> boolean addAll() This method allows the addition of specific elements to a particular collection.
2. static <T> Queue <T> asLifoQueue() This method allows the listing of the collection as Last-in-first-out (LIFO) in view.
3. static <T> int binarySearch() This method allows searching for a specific object and then returns them in a sorted list.
4. static <E> Collection<E> This method returns the dynamic view from any particular collection.
5. static <E> List <E> This method gives a return of a dynamic typesafe view from a particular list.

 

Here are some examples for Java Collection:
Java Collection min() Example:

1

2

3

4

5

6

7

8

9

10

11

12

import java.util.*;

public class CollectionsExample {

public static void main(String a[]){

List<Integer> list = new ArrayList<Integer>();

list.add(90);

list.add(80);

list.add(76);

list.add(58);

list.add(12);

System.out.println(“Minimum Value element in the collection: “+Collections.min(list));

}

}

 

The output will be:

Minimum Value element in the collection: 12

Java Collection max() Example:

1

2

3

4

5

6

7

8

9

10

11

12

import java.util.*;

public class CollectionsExample {

public static void main(String a[]){

List<Integer> list = new ArrayList<Integer>();

list.add(90);

list.add(80);

list.add(76);

list.add(58);

list.add(12);

System.out.println(“Maximum Value element in the collection: “+Collections.max(list));

}

}

 

The output will be:

Maximum Value element in the collection: 90

 

What are the JDBC API components?

The java.sql package contains interfaces and classes for JDBC API.

Interfaces:

  • Connection
  • Statement
  • PreparedStatement
  • ResultSet
  • ResultSetMetaData
  • DatabaseMetaData
  • CallableStatement etc.

Classes:

  • DriverManager
  • Blob
  • Clob
  • Types
  • SQLException etc.

What is the role of JDBC DriverManager class?

The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.

What is JDBC Connection interface?

The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.

In case you are facing any challenges with these java interview questions, please comment on your problems in the section below.

What is the purpose of JDBC ResultSet interface?

The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.

What is JDBC ResultSetMetaData interface?

The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc.

What is JDBC DatabaseMetaData interface?

The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc.

What do you mean by batch processing in JDBC?

Batch processing helps you to group related SQL statements into a batch and execute them instead of executing a single query. By using batch processing technique in JDBC, you can execute multiple queries which makes the performance faster.

What is the difference between execute, executeQuery, executeUpdate?

Statement execute(String query) is used to execute any SQL query and it returns TRUE if the result is an ResultSet such as running Select queries. The output is FALSE when there is no ResultSet object such as running Insert or Update queries. We can use getResultSet() to get the ResultSet and getUpdateCount() method to retrieve the update count.

Statement executeQuery(String query) is used to execute Select queries and returns the ResultSet. ResultSet returned is never null even if there are no records matching the query. When executing select queries we should use executeQuery method so that if someone tries to execute insert/update statement it will throw java.sql.SQLException with message “executeQuery method can not be used for update”.

Statement executeUpdate(String query) is used to execute Insert/Update/Delete (DML) statements or DDL statements that returns nothing. The output is int and equals to the row count for SQL Data Manipulation Language (DML) statements. For DDL statements, the output is 0.

You should use execute() method only when you are not sure about the type of statement else use executeQuery or executeUpdate method.

What do you understand by JDBC Statements?

JDBC statements are basically the statements which are used to send SQL commands to the database and retrieve data back from the database. Various methods like execute(), executeUpdate(), executeQuery, etc. are provided by JDBC to interact with the database.

JDBC supports 3 types of statements:

  1. Statement: Used for general purpose access to the database and executes a static SQL query at runtime.
  2. PreparedStatement: Used to provide input parameters to the query during execution.
  3. CallableStatement: Used to access the database stored procedures and helps in accepting runtime parameters.

What is Spring?

Wikipedia defines the Spring framework as “an application framework and inversion of control container for the Java platform. The framework’s core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform.” Spring is essentially a lightweight, integrated framework that can be used for developing enterprise applications in java.

Name the different modules of the Spring framework.

Some of the important Spring Framework modules are:

  • Spring Context – for dependency injection.
  • Spring AOP – for aspect oriented programming.
  • Spring DAO – for database operations using DAO pattern
  • Spring JDBC – for JDBC and DataSource support.
  • Spring ORM – for ORM tools support such as Hibernate
  • Spring Web Module – for creating web applications.
  • Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.

List some of the important annotations in annotation-based Spring configuration.

The important annotations are:

  • @Required
  • @Autowired
  • @Qualifier
  • @Resource
  • @PostConstruct
  • @PreDestroy

Explain Bean in Spring and List the different Scopes of Spring bean.

Beans are objects that form the backbone of a Spring application. They are managed by the Spring IoC container. In other words, a bean is an object that is instantiated, assembled, and managed by a Spring IoC container.

There are five Scopes defined in Spring beans.

  • Singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
  • Prototype: A new instance will be created every time the bean is requested.
  • Request: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
  • Session: A new bean will be created for each HTTP session by the container.
  • Global-session: This is used to create global session beans for Portlet applications.

In case you are facing any challenges with these java interview questions, please comment on your problems in the section below.

Explain the role of DispatcherServlet and ContextLoaderListener.

DispatcherServlet is basically the front controller in the Spring MVC application as it loads the spring bean configuration file and initializes all the beans that have been configured. If annotations are enabled, it also scans the packages to configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.

ContextLoaderListener, on the other hand, is the listener to start up and shut down the WebApplicationContext in Spring root. Some of its important functions includes tying up the lifecycle of Application Context to the lifecycle of the ServletContext and automating the creation of ApplicationContext.

What are the differences between constructor injection and setter injection?

No. Constructor Injection Setter Injection
 1)  No Partial Injection  Partial Injection
 2)  Doesn’t override the setter property  Overrides the constructor property if both are defined.
 3) Creates a new instance if any modification occurs Doesn’t create a new instance if you change the property value
 4)  Better for too many properties  Better for a few properties.

What is autowiring in Spring? What are the autowiring modes?

Autowiring enables the programmer to inject the bean automatically. We don’t need to write explicit injection logic. Let’s see the code to inject bean using dependency injection.

  1. <bean id=“emp” class=“com.tecklearn.Employee” autowire=“byName” />

The autowiring modes are given below:

No. Mode Description
 1)  no  this is the default mode, it means autowiring is not enabled.
 2)  byName  Injects the bean based on the property name. It uses setter method.
 3)  byType  Injects the bean based on the property type. It uses setter method.
 4)  constructor  It injects the bean using constructor

How to handle exceptions in Spring MVC Framework?

Spring MVC Framework provides the following ways to help us achieving robust exception handling.

Controller Based:

We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.

Global Exception Handler:

Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.

HandlerExceptionResolver implementation:

For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.

What are some of the important Spring annotations which you have used?

Some of the Spring annotations that I have used in my project are:

@Controller – for controller classes in Spring MVC project.

@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples

@ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.

@PathVariable – for mapping dynamic values from the URI to handler method arguments.

@Autowired – for autowiring dependencies in spring beans.

@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.

@Service – for service classes.

@Scope – for configuring the scope of the spring bean.

@Configuration, @ComponentScan and @Bean – for java based configurations.

AspectJ annotations for configuring aspects and advices , @Aspect, @Before, @After, @Around, @Pointcut, etc.

How to integrate Spring and Hibernate Frameworks?

We can use Spring ORM module to integrate Spring and Hibernate frameworks if you are using Hibernate 3+ where SessionFactory provides current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with dependency injection for the integration.

Also, Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for hibernate boiler-plate code for transaction management. 

Name the types of transaction management that Spring supports.

Two types of transaction management are supported by Spring. They are:

  1. Programmatic transaction management: In this, the transaction is managed with the help of programming. It provides you extreme flexibility, but it is very difficult to maintain.
  2. Declarative transaction management: In this, transaction management is separated from the business code. Only annotations or XML based configurations are used to manage the transactions.

What is Hibernate Framework?

Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is Java-based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa.

Hibernate provides a reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use the Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.

Similarly, hibernate configurations are flexible and can be done from XML configuration file as well as programmatically.

What are the important benefits of using Hibernate Framework?

Some of the important benefits of using hibernate framework are:

  1. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
  2. Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
  3. Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism, and association.
  4. Hibernate is an open-source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentation and help is easily available in forums.
  5. Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.
  6. Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
  7. Hibernate cache helps us in getting better performance.
  8. For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.

Overall hibernate is the best choice in current market for ORM tool, it contains all the features that you will ever need in an ORM tool.

Explain Hibernate architecture.

Hibernate has a layered architecture which helps the user to operate without having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application. It includes many objects such as persistent object, session factory, transaction factory, connection factory, session, transaction etc.

The Hibernate architecture is categorized in four layers.

  • Java application layer
  • Hibernate framework layer
  • Backhand API layer
  • Database layer

What are the differences between get and load methods?

The differences between get() and load() methods are given below.

No. get() load()
 1)  Returns null if object is not found. Throws ObjectNotFoundException if an object is not found.
 2)  get() method always hit the database.  load() method doesn’t hit the database.
 3)  It returns a real object, not a proxy.  It returns a proxy object.
 4) It should be used if you are not sure about the existence of instance. It should be used if you are sure that the instance exists.

What are the advantages of Hibernate over JDBC?

Some of the important advantages of Hibernate framework over JDBC are:

  1. Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks cleaner and readable.
  2. Hibernate supports inheritance, associations, and collections. These features are not present with JDBC API.
  3. Hibernate implicitly provides transaction management, in fact, most of the queries can’t be executed outside transaction. In JDBC API, we need to write code for transaction management using commit and rollback.
  4. JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throw JDBCException or HibernateException un-checked exception, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
  5. Hibernate Query Language (HQL) is more object-oriented and close to Java programming language. For JDBC, we need to write native SQL queries.
  6. Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
  7. Hibernate provides option through which we can create database tables too, for JDBC tables must exist in the database.
  8. Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource for the connection pool. This is a very important feature in enterprise application and completely missing in JDBC API.
  9. Hibernate supports JPA annotations, so the code is independent of the implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.

What are the life-cycle methods for a jsp?

Methods Description
 public void jspInit() It is invoked only once, same as init method of servlet.
public void _jspService(ServletRequest request,ServletResponse)throws ServletException,IOException It is invoked at each request, same as service() method of servlet.
 public void jspDestroy() It is invoked only once, same as destroy() method of servlet.

What are the JSP implicit objects?

JSP provides 9 implicit objects by default. They are as follows:

Object Type
1) out  JspWriter
2) request  HttpServletRequest
3) response  HttpServletResponse
4) config  ServletConfig
5) session  HttpSession
6) application  ServletContext
7) pageContext  PageContext
8) page  Object
9) exception  Throwable

What are the differences between include directive and include action?

include directive include action
The include directive includes the content at page translation time. The include action includes the content at request time.
The include directive includes the original content of the page so page size increases at runtime. The include action doesn’t include the original content rather invokes the include() method of Vendor provided class.
 It’s better for static pages.  It’s better for dynamic pages.

How to disable caching on back button of the browser?

<%
response.setHeader(“Cache-Control”,”no-store”);
response.setHeader(“Pragma”,”no-cache”);
response.setHeader (“Expires”, “0”);                    //prevents caching at the proxy server
%>

What are the different tags provided in JSTL?

There are 5 type of JSTL tags.

  1. core tags
  2. sql tags
  3. xml tags
  4. internationalization tags
  5. functions tags

How to disable session in JSP?

  1. <%@ page session=“false” %>

How to delete a Cookie in a JSP?

The following code explains how to delete a Cookie in a JSP :

1

2

3

4

5

6

7

8

9

10

11

Cookie mycook = new Cookie(“name1″,”value1”);

 

response.addCookie(mycook1);

 

Cookie killmycook = new Cookie(“mycook1″,”value1”);

 

killmycook . set MaxAge ( 0 );

 

killmycook . set Path (“/”);

 

killmycook . addCookie ( killmycook 1 );

Explain the jspDestroy() method.

jspDestry() method is invoked from javax.servlet.jsp.JspPage interface whenever a JSP page is about to be destroyed. Servlets destroy methods can be easily overridden to perform cleanup, like when closing a database connection.

How is JSP better than Servlet technology?

JSP is a technology on the server’s side to make content generation simple. They are document-centric, whereas servlets are programs. A Java server page can contain fragments of Java program, which execute and instantiate Java classes. However, they occur inside an HTML template file. It provides the framework for the development of a Web Application.

Why should we not configure JSP standard tags in web.xml?

We don’t need to configure JSP standard tags in web.xml because when container loads the web application and find TLD files, it automatically configures them to be used directly in the application JSP pages. We just need to include it in the JSP page using taglib directive.

How will you use JSP EL in order to get the HTTP method name?

Using pageContext JSP EL implicit object you can get the request object reference and make use of the dot operator to retrieve the HTTP method name in the JSP page. The JSP EL code for this purpose will look like ${pageContext.request.method}.

What is the difference between Error and Exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you cannot repair them at runtime. Though error can be caught in the catch block but the execution of application will come to a halt and is not recoverable.

While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving the user feedback for entering proper values etc.

How can you handle Java exceptions?

There are five keywords used to handle exceptions in Java:

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

What are the differences between Checked Exception and Unchecked Exception?

Checked Exception

  • The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions.
  • Checked exceptions are checked at compile-time.
  • Example: IOException, SQLException etc.

Unchecked Exception

  • The classes that extend RuntimeException are known as unchecked exceptions.
  • Unchecked exceptions are not checked at compile-time.
  • Example: ArithmeticException, NullPointerException etc.

What purpose do the keywords final, finally, and finalize fulfill? 

Final:

Final is used to apply restrictions on class, method, and variable. A final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed. Let’s take a look at the example below to understand it better.

1

2

3

4

5

6

class FinalVarExample {

public static void main( String args[])

{

final int a=10;   // Final variable

a=50;             //Error as value can’t be changed

}

Finally

Finally is used to place important code, it will be executed whether the exception is handled or not. Let’s take a look at the example below to understand it better.

1

2

3

4

5

6

7

8

9

10

11

12

class FinallyExample {

public static void main(String args[]){

try {

int x=100;

}

catch(Exception e) {

System.out.println(e);

}

finally {

System.out.println(“finally block is executing”);}

}}

}

Finalize

Finalize is used to perform clean up processing just before the object is garbage collected. Let’s take a look at the example below to understand it better.

1

2

3

4

5

6

7

8

9

10

11

12

13

class FinalizeExample {

public void finalize() {

System.out.println(“Finalize is called”);

}

public static void main(String args[])

{

FinalizeExample f1=new FinalizeExample();

FinalizeExample f2=new FinalizeExample();

f1= NULL;

f2=NULL;

System.gc();

}

}

What are the differences between throw and throws? 

throw keyword throws keyword
Throw is used to explicitly throw an exception. Throws is used to declare an exception.
Checked exceptions cannot be propagated with throw only. Checked exception can be propagated with throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exception You can declare multiple exception e.g. public void method()throws IOException,SQLException.

In case you are facing any challenges with these java interview questions, please comment on your problems in the section below.

What is exception hierarchy in java?

The hierarchy is as follows:

Throwable is a parent class of all Exception classes. There are two types of Exceptions: Checked exceptions and UncheckedExceptions or RunTimeExceptions. Both type of exceptions extends Exception class whereas errors are further classified into Virtual Machine error and Assertion error.

How to create a custom Exception?

To create you own exception extend the Exception class or any of its subclasses.

  • class New1Exception extends Exception { }               // this will create Checked Exception
  • class NewException extends IOException { }             // this will create Checked exception
  • class NewException extends NullPonterExcpetion { }  // this will create UnChecked exception

What are the important methods of Java Exception Class?

Exception and all of it’s subclasses doesn’t provide any specific methods and all of the methods are defined in the base class Throwable.

  1. String getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor.
  2. String getLocalizedMessage() – This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.
  3. Synchronized Throwable getCause() – This method returns the cause of the exception or null id the cause is unknown.
  4. String toString() – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.
  5. void printStackTrace() – This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as an argument to write the stack trace information to the file or stream.
  1. What are the differences between processes and threads?
Process Thread
Definition An executing instance of a program is called a process. A thread is a subset of the process.
Communication Processes must use inter-process communication to communicate with sibling processes. Threads can directly communicate with other threads of its process.
Control Processes can only exercise control over child processes. Threads can exercise considerable control over threads of the same process.
Changes Any change in the parent process does not affect child processes. Any change in the main thread may affect the behavior of the other threads of the process.
Memory Run in separate memory spaces. Run in shared memory spaces.
Controlled by Process is controlled by the operating system. Threads are controlled by programmer in a program.
Dependence Processes are independent. Threads are dependent.

What is a finally block? Is there a case when finally, will not execute?

Finally, block is a block which always executes a set of statements. It is always associated with a try block regardless of any exception that occurs or not.
Yes, finally will not be executed if the program exits either by calling System.exit() or by causing a fatal error that causes the process to abort.

What is synchronization?

Synchronization refers to multi-threading. A synchronized block of code can be executed by only one thread at a time. As Java supports execution of multiple threads, two or more threads may access the same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to be in sync. Synchronization avoids memory consistency 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 the thread is blocked until that thread releases the monitor.

 Can we write multiple catch blocks under single try block? 

Yes we can have multiple catch blocks under single try block but the approach should be from specific to general. Let’s understand this with a programmatic example.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

public class Example {

public static void main(String args[]) {

try {

int a[]= new int[10];

a[10]= 10/0;

}

catch(ArithmeticException e)

{

System.out.println(“Arithmetic exception in first catch block”);

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println(“Array index out of bounds in second catch block”);

}

catch(Exception e)

{

System.out.println(“Any exception in third catch block”);

}

}

What are the important methods of Java Exception Class?

Methods are defined in the base class Throwable. Some of the important methods of Java exception class are stated below.

  1. String getMessage() – This method returns the message String about the exception. The message can be provided through its constructor.
  2. public StackTraceElement[] getStackTrace() – This method returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack whereas the last element in the array represents the method at the bottom of the call stack.
  3. Synchronized Throwable getCause() – This method returns the cause of the exception or null id as represented by a Throwable object.
  4. String toString() – This method returns the information in String format. The returned String contains the name of Throwable class and localized message.
  5. void printStackTrace() – This method prints the stack trace information to the standard error stream.

What is OutOfMemoryError in Java?

OutOfMemoryError is the subclass of java.lang.Error which generally occurs when our JVM runs out of memory.

What is a Thread?

A thread is the smallest piece of programmed instructions which can be executed independently by a scheduler. In Java, all the programs will have at least one thread which is known as the main thread. This main thread is created by the JVM when the program starts its execution. The main thread is used to invoke the main() of the program.

What are the two ways to create a thread?

In Java, threads can be created in the following two ways:-

  • By implementing the Runnable interface.
  • By extending the Thread

What are the different types of garbage collectors in Java?

Garbage collection in Java a program which helps in implicit memory management. Since in Java, using the new keyword you can create objects dynamically, which once created will consume some memory. Once the job is done and there are no more references left to the object, Java using garbage collection destroys the object and relieves the memory occupied by it. Java provides four types of garbage collectors:

  • Serial Garbage Collector
  • Parallel Garbage Collector
  • CMS Garbage Collector
  • G1 Garbage Collector

What is the difference between an Inner Class and a Sub-Class?

Ans: An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.

A sub-class is a class which inherits from another class called super class. Sub-class can access all public and protected methods and fields of its super class.

What are the various access specifiers for Java classes?

Ans: In Java, access specifiers are the keywords used before a class name which defines the access scope. The types of access specifiers for classes are:

  1. Public : Class,Method,Field is accessible from anywhere.
  2. Protected:Method,Field can be accessed from the same class to which they belong or from the sub-classes,and from the class of same package,but not from outside.
  3. Default: Method,Field,class can be accessed only from the same package and not from outside of it’s native package.
  4. Private: Method,Field can be accessed from the same class to which they belong.

What’s the purpose of Static methods and static variables?

Ans: When there is a requirement to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keyword to make a method or variable shared for all objects.

What is data encapsulation and what’s its significance?

Ans: Encapsulation is a concept in Object Oriented Programming for combining properties and methods in a single unit.

Encapsulation helps programmers to follow a modular approach for software development as each object has its own set of methods and variables and serves its functions independent of other objects. Encapsulation also serves data hiding purpose.

What is a singleton class? Give a practical example of its usage.

A singleton class in java can have only one instance and hence all its methods and variables belong to just one instance. Singleton class concept is useful for the situations when there is a need to limit the number of objects for a class.

The best example of singleton usage scenario is when there is a limit of having only one connection to a database due to some driver limitations or because of any licensing issues.

What are Loops in Java? What are three types of loops?

Ans: Looping is used in programming to execute a statement or a block of statement repeatedly. There are three types of loops in Java:

1) For Loops

For loops are used in java to execute statements repeatedly for a given number of times. For loops are used when number of times to execute the statements is known to programmer.

2) While Loops

While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled. In while loops, condition is checked first before execution of statements.

3) Do While Loops

Do While Loop is same as While loop with only difference that condition is checked after execution of block of statements. Hence in case of do while loop, statements are executed at least once.

What is an infinite Loop? How infinite loop is declared?

Ans: An infinite loop runs without any condition and runs infinitely. An infinite loop can be broken by defining any breaking logic in the body of the statement blocks.

Infinite loop is declared as follows:

for (;;)

{

// Statements to execute

 

// Add any loop breaking logic

}

What is the difference between continue and break statement?

Ans: break and continue are two important keywords used in Loops. When a break keyword is used in a loop, loop is broken instantly while when continue keyword is used, current iteration is broken and loop continues with next iteration.

In below example, Loop is broken when counter reaches 4.

for (counter = 0; counter & lt; 10; counter++)

system.out.println(counter);

 

if (counter == 4) {

 

break;

}

 

}

In the below example when counter reaches 4, loop jumps to next iteration and any statements after the continue keyword are skipped for current iteration.

for (counter = 0; counter < 10; counter++)

system.out.println(counter);

 

if (counter == 4) {

 

continue;

}

system.out.println(“This will not get printed when counter is 4”);

}

What is the difference between double and float variables in Java?

Ans: In java, float takes 4 bytes in memory while Double takes 8 bytes in memory. Float is single precision floating point decimal number while Double is double precision decimal number.

What is Final Keyword in Java? Give an example.

Ans: In java, a constant is declared using the keyword Final. Value can be assigned only once and after assignment, value of a constant can’t be changed.

In below example, a constant with the name const_val is declared and assigned avalue:

Private Final int const_val=100

When a method is declared as final,it can NOT be overridden by the subclasses.This method are faster than any other method,because they are resolved at complied time.

When a class is declares as final,it cannot be subclassed. Example String,Integer and other wrapper classes.

What is ternary operator? Give an example.

Ans: Ternary operator , also called conditional operator is used to decide which value to assign to a variable based on a Boolean value evaluation. It’s denoted as ?

In the below example, if rank is 1, status is assigned a value of “Done” else “Pending”.

public class conditionTest {

public static void main(String args[]) {

String status;

int rank = 3;

status = (rank == 1) ? “Done” : “Pending”;

System.out.println(status);

}

}

How can you generate random numbers in Java?

Ans:

  • Using Math.random() you can generate random numbers in the range greater than or equal to 0.1 and less than 1.0
  • Using Random class in package java.util

What is default switch case? Give example.

Ans: In a switch statement, default case is executed when no other switch condition matches. Default case is an optional case .It can be declared only once all other switch cases have been coded.

In the below example, when score is not 1 or 2, default case is used.

public class switchExample {

int score = 4;

public static void main(String args[]) {

switch (score) {

case 1:

system.out.println(“Score is 1”);

break;

case 2:

system.out.println(“Score is 2”);

break;

default:

system.out.println(“Default Case”);

}

}

}

What’s the base class in Java from which all classes are derived?

Ans: java.lang.object

Can main() method in Java can return any data?

Ans: In java, main() method can’t return any data and hence, it’s always declared with a void return type.

What are Java Packages? What’s the significance of packages?

Ans: In Java, package is a collection of classes and interfaces which are bundled together as they are related to each other. Use of packages helps developers to modularize the code and group the code for proper re-use. Once code has been packaged in Packages, it can be imported in other classes and used.

Can we declare a class as Abstract without having any abstract method?

Ans: Yes we can create an abstract class by using abstract keyword before class name even if it doesn’t have any abstract method. However, if a class has even one abstract method, it must be declared as abstract otherwise it will give an error.

What’s the difference between an Abstract Class and Interface in Java?

Ans: The primary difference between an abstract class and interface is that an interface can only possess declaration of public static methods with no concrete implementation while an abstract class can have members with any access specifiers (public, private etc) with or without concrete implementation.

Another key difference in the use of abstract classes and interfaces is that a class which implements an interface must implement all the methods of the interface while a class which inherits from an abstract class doesn’t require implementation of all the methods of its super class.

A class can implement multiple interfaces but it can extend only one abstract class.

What are the performance implications of Interfaces over abstract classes?

Ans: Interfaces are slower in performance as compared to abstract classes as extra indirections are required for interfaces. Another key factor for developers to take into consideration is that any class can extend only one abstract class while a class can implement many interfaces.

Use of interfaces also puts an extra burden on the developers as any time an interface is implemented in a class; developer is forced to implement each and every method of interface.

Does Importing a package imports its sub-packages as well in Java?

Ans: In java, when a package is imported, its sub-packages aren’t imported and developer needs to import them separately if required.

For example, if a developer imports a package university.*, all classes in the package named university are loaded but no classes from the sub-package are loaded. To load the classes from its sub-package ( say department), developer has to import it explicitly as follows:

Import university.department.*

Can we declare the main method of our class as private?

Ans: In java, main method must be public static in order to run any application correctly. If main method is declared as private, developer won’t get any compilation error however, it will not get executed and will give a runtime error.

How can we pass argument to a function by reference instead of pass by value?

Ans: In java, we can pass argument to a function only by value and not by reference.

How an object is serialized in java?

Ans: In java, to convert an object into byte stream by serialization, an interface with the name Serializable is implemented by the class. All objects of a class implementing serializable interface get serialized and their state is saved in byte stream.

When we should use serialization?

Ans: Serialization is used when data needs to be transmitted over the network. Using serialization, object’s state is saved and converted into byte stream .The byte stream is transferred over the network and the object is re-created at destination.

Is it compulsory for a Try Block to be followed by a Catch Block in Java for Exception handling?

Ans: Try block needs to be followed by either Catch block or Finally block or both. Any exception thrown from try block needs to be either caught in the catch block or else any specific tasks to be performed before code abortion are put in the Finally block.

Is there any way to skip Finally block of exception even if some exception occurs in the exception block?

Ans: If an exception is raised in Try block, control passes to catch block if it exists otherwise to finally block. Finally block is always executed when an exception occurs and the only way to avoid execution of any statements in Finally block is by aborting the code forcibly by writing following line of code at the end of try block:

System.exit(0);

When the constructor of a class is invoked?

Ans: The constructor of a class is invoked every time an object is created with new keyword.

For example, in the following class two objects are created using new keyword and hence, constructor is invoked two times.

public class const_example {

 

const_example() {

 

system.out.println(“Inside constructor”);

}

public static void main(String args[]) {

 

const_example c1 = new const_example();

 

const_example c2 = new const_example();

}

}

Can a class have multiple constructors?

Ans: Yes, a class can have multiple constructors with different parameters. Which constructor gets used for object creation depends on the arguments passed while creating the objects.

Can we override static methods of a class?

Ans: We cannot override static methods. Static methods belong to a class and not to individual objects and are resolved at the time of compilation (not at runtime).Even if we try to override static method,we will not get an complitaion error,nor the impact of overriding when running the code.

In the below example, what will be the output?

public class superclass {

 

public void displayResult() {

 

system.out.println(“Printing from superclass”);

 

}

 

}

 

public class subclass extends superclass {

 

public void displayResult() {

 

system.out.println(“Displaying from subClass”);

 

super.displayResult();

 

}

 

public static void main(String args[]) {

 

subclass obj = new subclass();

 

obj.displayResult();

 

}

 

}

Ans: Output will be:

Displaying from subclass

Displaying from superclass

Is String a data type in java?

Ans: String is not a primitive data type in java. When a string is created in java, it’s actually an object of Java.Lang.String class that gets created. After creation of this string object, all built-in methods of String class can be used on the string object.

In the below example, how many String Objects are created?

String s1=”I am Java Expert”;

 

String s2=”I am C Expert”;

 

String s3=”I am Java Expert”;

Ans: In the above example, two objects of Java.Lang.String class are created. s1 and s3 are references to same object.

. Why Strings in Java are called as Immutable?

Ans: In java, string objects are called immutable as once value has been assigned to a string, it can’t be changed and if changed, a new object is created.

In below example, reference str refers to a string object having value “Value one”.

String str=”Value One”;

When a new value is assigned to it, a new String object gets created and the reference is moved to the new object.

str=”New Value”;

What’s the difference between an array and Vector?

Ans: An array groups data of same primitive type and is static in nature while vectors are dynamic in nature and can hold data of different data types.

What is multi-threading?

Ans: Multi threading is a programming concept to run multiple tasks in a concurrent manner within a single program. Threads share same process stack and running in parallel. It helps in performance improvement of any program.

Why Runnable Interface is used in Java?

Ans: Runnable interface is used in java for implementing multi threaded applications. Java.Lang.Runnable interface is implemented by a class to support multi threading.

What are the two ways of implementing multi-threading in Java?

Ans: Multi threaded applications can be developed in Java by using any of the following two methodologies:

  1. By using Java.Lang.Runnable Interface. Classes implement this interface to enable multi threading. There is a Run() method in this interface which is implemented.
  2. By writing a class that extend Java.Lang.Thread class.

When a lot of changes are required in data, which one should be a preference to be used? String or StringBuffer?

Ans: Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects unlike String which is immutable, it’s always a good choice to use StringBuffer when data is being changed too much. If we use String in such a case, for every data change a new String object will be created which will be an extra overhead.

What’s the purpose of using Break in each case of Switch Statement?

Ans: Break is used after each case (except the last one) in a switch so that code breaks after the valid case and doesn’t flow in the proceeding cases too.

If break isn’t used after each case, all cases after the valid case also get executed resulting in wrong results.

How garbage collection is done in Java?

Ans: In java, when an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. For automatic garbage collection java calls either System.gc() method or Runtime.gc() method.

How we can execute any code even before main method?

Ans: If we want to execute any statements before even creation of objects at load time of class, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before creation of objects in the main method.

Can a class be a super class and a sub-class at the same time? Give example.

Ans: If there is a hierarchy of inheritance used, a class can be a super class for another class and a sub-class for another one at the same time.

In the example below, continent class is sub-class of world class and it’s super class of country class.

public class world {

 

……….

 

}

public class continenet extends world {

 

…………

 

}

public class country extends continent {

 

………………….

 

}

How objects of a class are created if no constructor is defined in the class?

Ans: Even if no explicit constructor is defined in a java class, objects get created successfully as a default constructor is implicitly used for object creation. This constructor has no parameters.

In multi-threading how can we ensure that a resource isn’t used by multiple threads simultaneously?

Ans: In multi-threading, access to the resources which are shared among multiple threads can be controlled by using the concept of synchronization. Using synchronized keyword, we can ensure that only one thread can use shared resource at a time and others can get control of the resource only once it has become free from the other one using it.

Can we call the constructor of a class more than once for an object?

Ans: Constructor is called automatically when we create an object using new keyword. It’s called only once for an object at the time of object creation and hence, we can’t invoke the constructor again for an object after its creation.

There are two classes named classA and classB. Both classes are in the same package. Can a private member of classA can be accessed by an object of classB?

Ans: Private members of a class aren’t accessible outside the scope of that class and any other class even in the same package can’t access them.

Can we have two methods in a class with the same name?

Ans: We can define two methods in a class with the same name but with different number/type of parameters. Which method is to get invoked will depend upon the parameters passed.

For example in the class below we have two print methods with same name but different parameters. Depending upon the parameters, appropriate one will be called:

public class methodExample {

 

public void print() {

 

system.out.println(“Print method without parameters.”);

 

}

 

public void print(String name) {

 

system.out.println(“Print method with parameter”);

 

}

 

public static void main(String args[]) {

 

methodExample obj1 = new methodExample();

 

obj1.print();

 

obj1.print(“xx”);

 

}

 

}

How can we make copy of a java object?

Ans: We can use the concept of cloning to create copy of an object. Using clone, we create copies with the actual state of an object.

Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies.

What’s the benefit of using inheritance?

Ans: Key benefit of using inheritance is reusability of code as inheritance enables sub-classes to reuse the code of its super class. Polymorphism (Extensibility ) is another great benefit which allow new functionality to be introduced without effecting existing derived classes.

What’s the default access specifier for variables and methods of a class?

Ans: Default access specifier for variables and method is package protected i.e variables and class is available to any other class but in the same package,not outside the package.

Give an example of use of Pointers in Java class.

Ans: There are no pointers in Java. So we can’t use concept of pointers in Java.

How can we restrict inheritance for a class so that no class can be inherited from it?

Ans: If we want a class not to be extended further by any class, we can use the keyword Final with the class name.

In the following example, Stone class is Final and can’t be extend

public Final Class Stone {

// Class methods and Variables

}

. What’s the access scope of Protected Access specifier?

Ans: When a method or a variable is declared with Protected access specifier, it becomes accessible in the same class,any other class of the same package as well as a sub-class.

Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

What’s difference between Stack and Queue?

Ans: Stack and Queue both are used as placeholder for a collection of data. The primary difference between a stack and a queue is that stack is based on Last in First out (LIFO) principle while a queue is based on FIFO (First In First Out) principle.

In java, how we can disallow serialization of variables?

Ans: If we want certain variables of a class not to be serialized, we can use the keyword transient while declaring them. For example, the variable trans_var below is a transient variable and can’t be serialized:

public class transientExample {

private transient trans_var;

// rest of the code

}

How can we use primitive data types as objects?

Ans: Primitive data types like int can be handled as objects by the use of their respective wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can apply different methods to a wrapper class, just like any other object.

Which types of exceptions are caught at compile time?

Ans: Checked exceptions can be caught at the time of program compilation. Checked exceptions must be handled by using try catch block in the code in order to successfully compile the code.

Describe different states of a thread.

Ans: A thread in Java can be in either of the following states:

  • Ready: When a thread is created, it’s in Ready state.
  • Running: A thread currently being executed is in running state.
  • Waiting: A thread waiting for another thread to free certain resources is in waiting state.
  • Dead: A thread which has gone dead after execution is in dead state.

Can we use a default constructor of a class even if an explicit constructor is defined?

Ans: Java provides a default no argument constructor if no explicit constructor is defined in a Java class. But if an explicit constructor has been defined, default constructor can’t be invoked and developer can use only those constructors which are defined in the class.

Can we override a method by using same method name and arguments but different return types?

Ans: The basic condition of method overriding is that method name, arguments as well as return type must be exactly same as is that of the method being overridden. Hence using a different return type doesn’t override a method.

What will be the output of following piece of code?

public class operatorExample {

 

public static void main(String args[]) {

 

int x = 4;

 

system.out.println(x++);

}

}

Ans: In this case postfix ++ operator is used which first returns the value and then increments. Hence it’s output will be 4.

A person says that he compiled a java class successfully without even having a main method in it? Is it possible?

Ans: main method is an entry point of Java class and is required for execution of the program however; a class gets compiled successfully even if it doesn’t have a main method. It can’t be run though.

Can we call a non-static method from inside a static method?

Ans: Non-Static methods are owned by objects of a class and have object level scope and in order to call the non-Static methods from a static block (like from a static main method), an object of the class needs to be created first. Then using object reference, these methods can be invoked.

What are the two environment variables that must be set in order to run any Java programs?

Ans: Java programs can be executed in a machine only once following two environment variables have been properly set:

  1. PATH variable
  2. CLASSPATH variable

Can variables be used in Java without initialization?

Ans: In Java, if a variable is used in a code without prior initialization by a valid value, program doesn’t compile and gives an error as no default value is assigned to variables in Java.

Can a class in Java be inherited from more than one class?

Ans: In Java, a class can be derived from only one class and not from multiple classes. Multiple inheritances is not supported by Java.

Can a constructor have different name than a Class name in Java?

Ans: Constructor in Java must have same name as the class name and if the name is different, it doesn’t act as a constructor and compiler thinks of it as a normal method.

What will be the output of Round(3.7) and Ceil(3.7)?

Ans: Round(3.7) returns 4 and Ceil(3.7) returns 4.

Can we use goto in Java to go to a particular line?

Ans: In Java, there is not goto keyword and java doesn’t support this feature of going to a particular labeled line.

Can a dead thread be started again?

Ans: In java, a thread which is in dead state can’t be started again. There is no way to restart a dead thread.

Is the following class declaration correct?

Ans:

public abstract final class testClass {

// Class methods and variables

}

Ans: The above class declaration is incorrect as an abstract class can’t be declared as Final.

Is JDK required on each machine to run a Java program?

Ans: JDK is development Kit of Java and is required for development only and to run a Java program on a machine, JDK isn’t required. Only JRE is required.

What’s the difference between comparison done by equals method and == operator?

Ans: In Java, equals() method is used to compare the contents of two string objects and returns true if the two have same value while == operator compares the references of two string objects.

In the following example, equals() returns true as the two string objects have same values. However == operator returns false as both string objects are referencing to different objects:

public class equalsTest {

 

public static void main(String args[]) {

 

String str1 = new String(“Hello World”);

 

String str2 = new String(“Hello World”);

 

if (str1.equals(str2))

 

{ // this condition is true

 

System.out.println(“str1 and str2 are equal in terms of values”);

 

}

 

if (str1 == str2) {

 

//This condition is true

 

System.out.println(“Both strings are referencing same object”);

 

} else

 

{

 

// This condition is NOT true

 

System.out.println(“Both strings are referencing different objects”);

 

}

 

}

 

}

Is it possible to define a method in Java class but provide its implementation in the code of another language like C?

Ans: Yes, we can do this by use of native methods. In case of native method-based development, we define public static methods in our Java class without its implementation and then implementation is done in another language like C separately.

How are destructors defined in Java?

Ans: In Java, there are no destructors defined in the class as there is no need to do so. Java has its own garbage collection mechanism which does the job automatically by destroying the objects when no longer referenced.

Can a variable be local and static at the same time?

Ans: No a variable can’t be static as well as local at the same time. Defining a local variable as static gives compilation error.

Can we have static methods in an Interface?

Ans: Static methods can’t be overridden in any class while any methods in an interface are by default abstract and are supposed to be implemented in the classes being implementing the interface. So it makes no sense to have static methods in an interface in Java.

In a class implementing an interface, can we change the value of any variable defined in the interface?

Ans: No, we can’t change the value of any variable of an interface in the implementing class as all variables defined in the interface are by default public, static and Final and final variables are like constants which can’t be changed later.

Is it correct to say that due to garbage collection feature in Java, a java program never goes out of memory?

Ans: Even though automatic garbage collection is provided by Java, it doesn’t ensure that a Java program will not go out of memory as there is a possibility that creation of Java objects is being done at a faster pace compared to garbage collection resulting in filling of all the available memory resources.

So, garbage collection helps in reducing the chances of a program going out of memory but it doesn’t ensure that.

Can we have any other return type than void for main method?

Ans: No, Java class main method can have only void return type for the program to get successfully executed.

Nonetheless , if you absolutely must return a value to at the completion of main method , you can use System.exit(int status)

I want to re-reach and use an object once it has been garbage collected. How it’s possible?

Ans: Once an object has been destroyed by garbage collector, it no longer exists on the heap and it can’t be accessed again. There is no way to reference it again.

In Java thread programming, which method is a must implementation for all threads?

Ans: Run() is a method of Runnable interface that must be implemented by all threads.

I want to control database connections in my program and want that only one thread should be able to make database connection at a time. How can I implement this logic?

Ans: This can be implemented by use of the concept of synchronization. Database related code can be placed in a method which hs synchronized keyword so that only one thread can access it at a time.

How can an exception be thrown manually by a programmer?

Ans: In order to throw an exception in a block of code manually, throw keyword is used. Then this exception is caught and handled in the catch block.

public void topMethod() {

try {

excMethod();

} catch (ManualException e) {}

}

 

public void excMethod {

String name = null;

if (name == null) {

throw (new ManualException(“Exception thrown manually “);

}

}

I want my class to be developed in such a way that no other class (even derived class) can create its objects. How can I do so?

Ans: If we declare the constructor of a class as private, it will not be accessible by any other class and hence, no other class will be able to instantiate it and formation of its object will be limited to itself only.

How objects are stored in Java?

Ans: In java, each object when created gets a memory space from a heap. When an object is destroyed by a garbage collector, the space allocated to it from the heap is re-allocated to the heap and becomes available for any new objects.

How can we find the actual size of an object on the heap?

Ans: In java, there is no way to find out the exact size of an object on the heap.

Which of the following classes will have more memory allocated?

Class A: Three methods, four variables, no object

Class B: Five methods, three variables, no object

Ans: Memory isn’t allocated before creation of objects. Since for both classes, there are no objects created so no memory is allocated on heap for any class.

What happens if an exception is not handled in a program?

Ans: If an exception is not handled in a program using try catch blocks, program gets aborted and no statement executes after the statement which caused exception throwing.

I have multiple constructors defined in a class. Is it possible to call a constructor from another constructor’s body?

Ans: If a class has multiple constructors, it’s possible to call one constructor from the body of another one using this().

What’s meant by anonymous class?

Ans: An anonymous class is a class defined without any name in a single line of code using new keyword.

For example, in below code we have defined an anonymous class in one line of code:

public java.util.Enumeration testMethod()

 

{

 

return new java.util.Enumeration()

 

{

 

@Override

 

public boolean hasMoreElements()

 

{

 

// TODO Auto-generated method stub

 

return false;

 

}

 

@Override

 

public Object nextElement()

 

{

 

// TODO Auto-generated method stub

 

return null;

 

}

 

}

Is there a way to increase the size of an array after its declaration?

Ans: Arrays are static and once we have specified its size, we can’t change it. If we want to use such collections where we may require a change of size ( no of items), we should prefer vector over array.

If an application has multiple classes in it, is it okay to have a main method in more than one class?

Ans: If there is main method in more than one classes in a java application, it won’t cause any issue as entry point for any application will be a specific class and code will start from the main method of that particular class only.

I want to persist data of objects for later use. What’s the best approach to do so?

Ans: The best way to persist data for future use is to use the concept of serialization.

What is a Local class in Java?

Ans: In Java, if we define a new class inside a particular block, it’s called a local class. Such a class has local scope and isn’t usable outside the block where its defined.

String and StringBuffer both represent String objects. Can we compare String and StringBuffer in Java?

Ans: Although String and StringBuffer both represent String objects, we can’t compare them with each other and if we try to compare them, we get an error.

Which API is provided by Java for operations on set of objects?

Ans: Java provides a Collection API which provides many useful methods which can be applied on a set of objects. Some of the important classes provided by Collection API include ArrayList, HashMap, TreeSet and TreeMap.

Can we cast any other type to Boolean Type with type casting?

Ans: No, we can neither cast any other primitive type to Boolean data type nor can cast Boolean data type to any other primitive data type.

Can we use different return types for methods when overridden?

Ans: The basic requirement of method overriding in Java is that the overridden method should have same name, and parameters.But a method can be overridden with a different return type as long as the new return type extends the original.

For example , method is returning a reference type.

Class B extends A {

 

A method(int x) {

 

//original method

 

}

 

B method(int x) {

 

//overridden method

 

}

 

}

What’s the base class of all exception classes?

Ans: In Java, Java.lang.Throwable is the super class of all exception classes and all exception classes are derived from this base class.

What’s the order of call of constructors in inheritance?

Ans: In case of inheritance, when a new object of a derived class is created, first the constructor of the super class is invoked and then the constructor of the derived class is invoked.

What is Object-Oriented Programming? 

OOPs is a programming paradigm centred around objects rather than functions. It is not a tool or a programming language it is a paradigm that was designed to overcome the flaws of procedural programming. There are many languages that follow OOPs concepts, some popular ones are Java, Python, Ruby and more. Some frameworks also follow OOPs concepts, Angular is one such framework.

Could you explain the Oops concepts?

Following are the various OOPS Concepts:

  • Abstraction– Representing essential features without the need to give out background details. The technique is used for creating a new suitable data type for some specific application
  • Aggregation– All objects have their separate lifecycle, but ownership is present. No child object can belong to some other object except for the parent object
  • Association– The relationship between two objects, where each object has its separate lifecycle. There is no ownership
  • Class– A group of similar entities
  • Composition– Also called the death relationship, it is a specialized form of aggregation. Child objects don’t have a lifecycle. As such, they automatically get deleted if the associated parent object is deleted
  • Encapsulation– Refers to the wrapping up of data and code into a single entity. Allows the variables of a class to be only accessible by the parent class and no other classes
  • Inheritance– When an object acquires the properties of some other object, it is called inheritance. It results in the formation of a parent-child relationship amongst classes involved. Offers a robust and natural mechanism of organizing and structuring software
  • Object– Denotes an instance of a class. Any class can have multiple instances. An object contains the data as well as the method that will operate on the data
  • Polymorphism– refers to the ability of a method, object, or variable to assume several forms

Differentiate between break and continue

 

Break Continue
Used with both loop and switch statement Used with only loop statements.
It terminates the loop or switch block. It does not terminate but skips to the next iteration.

What is an Object?

An instance of a Java class is known as an object. Two important properties of a Java object are behaviour and state. An object is created as soon as the JVM comes across the new keyword.

Define classes in Java 

A class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language.

Syntax of a class: 

class Sample{
member variables
methods()
}

Example of Class:

public class Shape
{
String Shape name;
void area()
{
}
void volume ()
{
}
void num_sides()
{
}
}

Explain what are static methods and variables?

A class has two sections one declares variables, and other declares method, and these are called instance variables and instance methods, respectively. They are termed so because every time a class is instantiated, a new copy of each of them is created.

Variables and methods can be created that are common to all objects and accessed without using a particular object by declaring them static. Static members are also available to be used by other classes and methods.

What do you mean by Constructor?

A constructor is a method that has the same name as that of the class to which it belongs. As soon as a new object is created, a constructor corresponding to the class gets invoked. Although the user can explicitly create a constructor, it is created on its own as soon as a class is created. This is known as the default constructor. Constructors can be overloaded.

Note: – If an explicitly-created constructor has a parameter, then it is necessary to create another constructor without a parameter.

Please explain Local variables and Instance variables in Java.

Variables that are only accessible to the method or code block in which they are declared are known as local variables. Instance variables, on the other hand, are accessible to all methods in a class. While local variables are declared inside a method or a code block, instance variables are declared inside a class but outside a method. Even when not assigned, instance variables have a value that can be null, 0, 0.0, or false. This isn’t the case with local variables that need to be assigned a value, where failing to assign a value will yield an error. Local variables are automatically created when a method is called and destroyed as soon as the method exits. For creating instance variables, the new keyword must be used.

Please explain Method Overriding in Java?

Method Overriding in Java allows a subclass to offer a specific implementation of a method that has already been provided by its parent or superclass. Method overriding happens if the subclass method and the Superclass method have:

  • The same name
  • The same argument
  • The same return type

What do you mean by Overloading?

Overloading is the phenomenon when two or more different methods (method overloading) or operators (operator overloading) have the same representation. For example, the + operator adds two integer values but concatenates two strings. Similarly, an overloaded function called Add can be used for two purposes

  1. To add two integers
  2. To concatenate two strings

Unlike method overriding, method overloading requires two overloaded methods to have the same name but different arguments. The overloaded functions may or may not have different return types.

What role does the final keyword play in Java? What impact does it have on a variable, method, and class?

The final keyword in Java is a non-access modifier that applies only to a class, method, or variable. It serves a different purpose based on the context where it is used.

  • With a class

When a class is declared as final, then it is disabled from being subclassed i.e., no class can extend the final class.

  • With a method

Any method accompanying the final keyword is restricted from being overridden by the subclass.

  • With a variable

A variable followed by the final keyword is not able to change the value that it holds during the program execution. So, it behaves like a constant.

Could you draw a comparison between Array and ArrayList?

An array necessitates for giving the size during the time of declaration, while an array list doesn’t necessarily require size as it changes size dynamically. To put an object into an array, there is the need to specify the index. However, no such requirement is in place for an array list. While an array list is parameterized, an array is not parameterized.

Please explain the difference between String, String Builder, and String Buffer.

String variables are stored in a constant string pool. With the change in the string reference, it becomes impossible to delete the old value. For example, if a string has stored a value “Old,” then adding the new value “New” will not delete the old value. It will still be there, however, in a dormant state. In a String Buffer, values are stored in a stack. With the change in the string reference, the new value replaces the older value. The String Buffer is synchronized (and therefore, thread-safe) and offers slower performance than the String Builder, which is also a String Buffer but is not synchronized. Hence, performance is fast in String Builder than the String Buffer.

What is String Pool in Java?

The collection of strings stored in the heap memory refers to the String pool. Whenever a new object is created, it is checked if it is already present in the String pool or not. If it is already present, then the same reference is returned to the variable else new object is created in the String pool, and the respective reference is returned.

What do you know about Interface in Java?

A Java interface is a template that has only method declarations and not method implementations. It is a workaround for achieving multiple inheritances in Java. Some worth remembering important points regarding Java interfaces are:

  • A class that implements the interface must provide an implementation for all methods declared in the interface
  • All methods in an interface are internally public abstract void
  • All variables in an interface are internally public static final
  • Classes do not extend but implement interfaces

How is an Abstract class different from an Interface?

There are several differences between an Abstract class and an Interface in Java, summed up as follows:

  • Constituents – An abstract class contains instance variables, whereas an interface can contain only constants.
  • Constructor and Instantiation – While an interface has neither a constructor nor it can be instantiated, an abstract class can have a default constructor that is called whenever the concrete subclass is instantiated.
  • Implementation of Methods – All classes that implement the interface need to provide an implementation for all the methods contained by it. A class that extends the abstract class, however, doesn’t require implementing all the methods contained in it. Only abstract methods need to be implemented in the concrete subclass.
  • Type of Methods – Any abstract class has both abstract as well as non-abstract methods. Interface, on the other hand, has only a single abstract method.

Please explain what do you mean by an Abstract class and an Abstract method?

An abstract class in Java is a class that can’t be instantiated. Such a class is typically used for providing a base for subclasses to extend as well as implementing the abstract methods and overriding or using the implemented methods defined in the abstract class. To create an abstract class, it needs to be followed by the abstract keyword. Any abstract class can have both abstract as well as non-abstract methods. A method in Java that only has the declaration and not implementation is known as an abstract method. Also, an abstract method name is followed by the abstract keyword. Any concrete subclass that extends the abstract class must provide an implementation for abstract methods.

What is multiple inheritance? Does Java support multiple inheritance? If not, how can it be achieved?

If a subclass or child class has two parent classes, that means it inherits the properties from two base classes, it is multiple inheritances. Java does not multiple inheritances as in case if the parent classes have the same method names, then at runtime, it becomes ambiguous, and the compiler is unable to decide which method to execute from the child class.

What are the packages in Java? State some advantages of Packages in Java?

Packages are Java’s way of grouping a variety of classes and/or interfaces together. The functionality of the objects decides how they are grouped. Packagers act as “containers” to classes.

Enlisted below are the advantages of Packages:

  1. Classes of other programs can be reused.
  2. Two classes with the same can exist in two different packages.
  3. Packages can hide classes, thus denying access to certain programs and classes meant for internal use only.
  4. They also separate design from coding.

How do you make a thread in Java? Give examples.

To make a thread in Java, there are two options:

  • Extend the Thread Class  The thread is available in the java.lang.Thread class. To make a thread, you need to extend a thread class and override the run method. For example,

public class Addition extends Thread {
public void run() {
}
}

A disadvantage of using the thread class is that it becomes impossible to extend any other classes.

Nonetheless, it is possible to overload the run() method in the class

  • Implement Runnable Interface – Another way of making a thread in Java is by implementing a runnable interface. For doing so, there is the need to provide the implementation for the run() method that is defined in the

interface. For example,
public class Addition implements Runnable {
public void run() {
}
}

Why do we use the yield() method?

The yield() method belongs to the thread class. It transfers the currently running thread to a runnable state and also allows the other threads to execute. In other words, it gives equal priority threads a chance to run. Because yield() is a static method, it does not release any lock.

Can you explain the thread lifecycle in Java?

The thread lifecycle has the following states and follows the following order:

  • New – In the very first state of the thread lifecycle, the thread instance is created, and the start() method is yet to be invoked. The thread is considered alive now.
  • Runnable – After invoking the start() method, but before invoking the run() method, a thread is in the runnable state. A thread can also return to the runnable state from waiting or sleeping state.
  • Running – The thread enters the running state after the run() method is invoked. This is when the thread begins execution.
  • Non-Runnable – Although the thread is alive, it is not able to run. Typically, it returns to the runnable state after some time.
  • Terminated – The thread enters the terminated state once the run() method completes its execution. It is not alive now.

When is the Runnable interface preferred over thread class and vice-versa?

In Java, it is possible to extend only one class. Hence, the thread class is only extended when no other class needs to be extended. If it is required for a class to extend some other class than the thread class, then we need to use the Runnable interface.

Please draw a comparison between notify() and notifyAll() methods.

The notify() method is used for sending a signal to wake up a single thread in the waiting pool. Contrarily, the notifyAll() method is used for sending a signal to wake up all threads in a waiting pool.

How will you distinguish processes from threads?

There are several fundamental differences between a process and a thread, stated as follows:

  • Definition – A process is an executing instance of a program whereas, a thread is a subset of a process.
  • Changes – A change made to the parent process doesn’t affect child processes. However, a change in the main thread can yield changes in the behavior of other threads of the same process.
  • Communication – While processes require inter-process communication for communicating with sibling processes, threads can directly communicate with other threads belonging to the same process.
  • Control – Processes are controlled by the operating system and can control only child processes. On the contrary, threads are controlled by the programmer and are capable of exercising control over threads of the same process to which they belong.
  • Dependence – Processes are independent entities while threads are dependent entities
  • Memory – Threads run in shared memory spaces, but processes run in separate memory spaces.

What is the join() method? Give an example.

We use the join() method for joining one thread with the end of the currently running thread. It is a non-static method and has an overloaded version. Consider the example below:

public static void main (String[] args) {
Thread t = new Thread();
t.start();
t.join();
}

The main thread starts execution in the example mentioned above. As soon as the execution reaches the code t.start(), then the thread t starts its stack for execution. The JVM switches between the main thread and the thread there. Once the execution reaches the t.join(), then the thread t alone is executed and allowed to complete its task. Afterward, the main thread resumes execution.

How do you make a thread stop in Java?

There are three methods in Java to stop the execution of a thread:

  • Blocking – This method is used to put the thread in a blocked state. The execution resumes as soon as the condition of the blocking is met. For instance, the ServerSocket.accept() is a blocking method that listens for incoming socket connection and resumes the blocked thread only when a connection is made.
  • Sleeping – This method is used for delaying the execution of the thread for some time. A thread upon which the sleep() method is used is said to enter the sleep state. It enters the runnable state as soon as it wakes up i.e., the sleep state is finished. The time for which the thread needs to enter the sleep state is mentioned inside the braces of the sleep() method. It is a static method.
  • Waiting – Although it can be called on any Java object, the wait() method can only be called from a synchronized block.

Could you explain various types of Exceptions in Java? Also, tell us about the different ways of handling them.

Java has provision for two types of exceptions:

  • Checked Exceptions – Classes that extend Throwable class, except Runtime exception and Error, are called checked exceptions. Such exceptions are checked by the compiler during the compile time. These types of exceptions must either have appropriate try/catch blocks or be declared using the throws keyword. ClassNotFoundException is a checked exception.
  • Unchecked Exceptions – Such exceptions aren’t checked by the compiler during the compile time. As such, the compiler doesn’t necessitate handling unchecked exceptions. Arithmetic Exception and ArrayIndexOutOfBounds Exception are unchecked exceptions.

Exceptions in Java are handled in two ways:

Declaring the throws keyword – We can declare the exception using throws keyword at the end of the method. For example:

class ExceptionCheck{
public static void main(String[] args){
add();
}
public void add() throws Exception{
addition();
}
}

Using try/catch – Any code segment that is expected to yield an exception is surrounded by the try block. Upon the occurrence of the exception, it is caught by the catch block that follows the try block. For example,

class ExceptionCheck{
public static void main (String[] args) {
add();
}
public void add(){
try{
addition();
}
catch(Exception e)
{
e.printStacktrace();
}
}
}

Could you draw the Java Exception Hierarchy?

 

Is it possible to write multiple catch blocks under a single try block?

Yes, it is possible to write several catch blocks under a single try block. However, the approach needs to be from specific to general. Following example demonstrates the same:

public class Example {
public static void main(String args[]) {
try {
int a[]= new int[10];
a[10]= 10/0;
}
catch(ArithmeticException e)
{
System.out.println(“Arithmetic exception in first catch block”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index out of bounds in second catch block”);
}
catch(Exception e)
{
System.out.println(“Any exception in third catch block”);
}
}

How does the throw keyword differ from the throws keyword?

While the throws keyword allows declaring an exception, the throw keyword is used to explicitly throw an exception. Checked exceptions can’t be propagated with throw only, but throws allow doing so without the need for anything else. The throws keyword is followed by a class, whereas the throw keyword is followed by an instance. The throw keyword is used within the method, but the throws keyword is used with the method signature. Furthermore, it is not possible to throw multiple exceptions, but it is possible to declare multiple exceptions.

Explain various exceptions handling keywords in Java?

There is two crucial exception handling keywords in Java, followed by the third keyword final, which may or may not be used after handling exceptions.

try:

If and when a code segment has chances of having and abnormality or an error, it is placed within a try block. When the exception is raised, it is handled and caught by the catch block.

Try block must have a catch() or a final() or both blocks after it.

catch:

When an exception is raised in the try block, it is handled in the catch block.

final:

This block is executed regardless of the exception. It can be placed either after try{} or catch {} block.

Explain exception propagation?

The method at the top of the stack throws an exception if it is not caught. It moves to the next method and goes on like this until caught.

Example:

public class Sum()
{
public static void main(String args[])
{
addition()
}
public void addition()
{
add();
}
}

The stack of the above code is:

add()
addition()
main()

If an exception occurred in the add() method is not caught, then it moves to the method addition(). It is then moved to the main() method, where the flow of execution stops. It is called Exception Propagation.

Does an empty file name with .java extension a valid file name?

Yes, Java permits to save our java file by .java only. It is compiled by javac .java and run by java class name.

Let’s take a simple example:

public class Any()
{
public static void main(String args[])
{
System.out.println(“Hello Java File here!”);
}
}

To compile: javac.java

To run: Java Any

What do you mean by Collections in Java? What are the constituents of Collections in Java?

A group of objects in Java is known as collections. Java.util package contains, along with date and time facilities, internationalization, legacy collection classes, etc., the various classes and interfaces for collecting. Alternatively, collections can be considered as a framework designed for storing the objects and manipulating the design in which the objects are stored. You can use collections to perform the following operations on objects:

  • Deletion
  • Insertion
  • Manipulation
  • Searching
  • Sorting

Following are the various constituents of the collections framework:

  • Classes – Array List, Linked List, Lists, and Vector
  • Interfaces – Collection, List, Map, Queue, Set, Sorted Map, and Sorted Set
  • Maps – HashMap, HashTable, LinkedHashMap, and TreeMap
  • Queues – Priority Queue
  • Sets – Hash Set, Linked Hash Set, and Tree Set

How will you differentiate HashMap from HashTable?

HashMap in Java is a Map-based collection class, used for storing key & value pairs. It is denoted as HashMap<Key, Value> or HashMap<K, V> HashTable is an array of a list, where each list is called a bucket. Values contained in a HashTable are unique and depend on the key. Methods are not synchronized in HashMap, while key methods are synchronized in HashTable. However, HashMap doesn’t have thread safety, while HashTable has the same. For iterating values, HashMap uses iterator and HashTable uses enumerator. HashTable doesn’t allow anything that is null, while HashMap allows one null key and several null values. In terms of performance, HashTable is slow. Comparatively, HashMap is faster.

Please explain Map and their types in Java.

A Java Map is an object that maps keys to values. It can’t contain duplicate keys, and each key can map to only one value. In order to determine whether two keys are the same or distinct, Map makes use of the equals() method. There are 4 types of Map in Java, described as follows:

  • HashMap – It is an unordered and unsorted map and hence, is a good choice when there is no emphasis on the order. A HashMap allows one null key and multiple null values and doesn’t maintain any insertion order.
  • HashTable – Doesn’t allow anything null and has methods that are synchronized. As it allows for thread safety, the performance is slow.
  • LinkedHashMap – Slower than a HashMap but maintains insertion order and has a faster iteration.
  • TreeMap – A sorted Map providing support for constructing a sort order using a constructor.

What do you mean by Priority Queue in Java?

Priority queue, like a regular queue, is an abstract data type except having a priority associated with each element contained by it. The element with the high priority is served before the element with low priority in a priority queue. Elements in a priority queue are ordered either according to the comparator or naturally. The order of the elements in a priority queue represents their relative priority.

What is Set in Java? Also, explain its types in a Java Collections.

In Java, a Set is a collection of unique objects. It uses the equals() method to determine whether two objects are the same or not. Various types of Set in Java Collections are:

  1. Hash Set– An unordered and unsorted set that uses the hash code of the object for adding values. Used when the order of the collection isn’t important
  2. Linked Hash Set– This is an ordered version of the hash set that maintains a doubly-linked list of all the elements. Used when iteration order is mandatory. Insertion order is the same as that of how elements are added to the Set.
  3. Tree Set– One of the two sorted collections in Java, it uses Read-Black tree structure and ensures that the elements are present in the ascending order.

What is ordered and sorted concerning collections?

 

  1. Ordered

It means that values are stored in a collection in a specific order, but the order is independent of the value. Eg. List

  1. Sorted

It means the collection has an order which is dependent on the value of an element.

Eg. SortedSet

Please explain the various types of garbage collectors in Java?

The Java programming language has four types of garbage collectors:

  1. Serial Garbage Collector– Using only a single thread for garbage collection, the serial garbage collector works by holding all the application threads. It is designed especially for single-threaded environments. Because serial garbage collector freezes all application threads while performing garbage collection, it is most suitable for command-line programs only. For using the serial garbage collector, one needs to turn on the -XX:+UseSerialGC JVM argument.
  2. Parallel Garbage Collector – Also known as the throughput collector, the parallel garbage collector is the default garbage collector of the JVM. It uses multiple threads for garbage collection, and like a serial garbage collector freezes all application threads during garbage collection.
  3. CMS Garbage Collector– Short for Concurrent Mark Sweep, CMS garbage collector uses multiple threads for scanning the heap memory for marking instances for eviction, followed by sweeping the marked instances. There are only two scenarios when the CMS garbage collector holds all the application threads:
    1. When marking the referenced objects in the tenured generation space
    2. If there is some change in the heap memory while performing the garbage collection, CMS garbage collector ensures better application throughput over parallel garbage collectors by using more CPU. For using the CMS garbage collector, the XX:+USeParNewGC JVM argument needs to be turned on.
  4. G1 Garbage Collector  Used for large heap memory areas, G1 garbage collector works by separating the heap memory into multiple regions and then executing garbage collection in them in parallel. Unlike the CMS garbage collector that compacts the memory on STW (Stop The World) situations, G1 garbage collector compacts the free heap space right after reclaiming the memory. Also, the G1 garbage collector prioritizes the region with the most garbage. Turning on the –XX:+UseG1GC JVM argument is required for using the G1 garbage collector.

What do you understand by Synchronization in Java? What is its most significant disadvantage?

If several threads try to access a single block of code, then there is an increased chance of producing inaccurate results. Synchronization is used to prevent this. Using the synchronization keyword makes a thread need a key to access the synchronized code. Simply, synchronization allows only one thread to access a block of code at a time. Each Java object has a lock, and every lock has only one key. A thread can access a synchronized method only if it can get the key to the lock of the object. Following example demonstrates synchronization:

public class ExampleThread implements Runnable {
public static void main (String[] args){
Thread t = new Thread();
t.start();
}
public void run(){
synchronized(object){
{
}
}

Note: It is recommended to avoid implementing synchronization for all methods. This is because when only one thread can access the synchronized code, the next thread needs to wait. Consequently, it results in slower performance of the program.

Can you tell the difference between execute(), executeQuery(), and executeUpdate()?

 

  • execute() – Used for executing an SQL query. It returns TRUE if the result is a ResultSet, like running Select queries, and FALSE if the result is not a ResultSet, such as running an Insert or an Update query.
  • executeQuery() – Used for executing Select queries. It returns the ResultSet, which is not null, even if no records are matching the query. The executeQuery() method must be used when executing select queries so that it throws the java.sql.SQLException with the ‘executeQuery method cannot be used for update’ message when someone tries to execute an Insert or Update statement.
  • executeUpdate() – Used for executing Delete/Insert/Update statement or DDL statements that returns nothing. The output varies depending on whether the statements are Data Manipulation Language (DML) statements or Data Definition Language (DDL) statements. The output is an integer and equals the total row count for the former case, and 0 for the latter case.

Note: The execute() method needs to be used only in a scenario when there is no certainty about the type of statement. In all other cases, either use executeQuery() or executeUpdate() method.

Provide an example of Hibernate architecture:

Could you demonstrate how to delete a cookie in JSP with a code example?

Following code demonstrates deleting a cookie in JSP:

Cookie mycook = new Cookie(“name1″,”value1”);
response.addCookie(mycook1);
Cookie killmycook = new Cookie(“mycook1″,”value1”);
killmycook . set MaxAge ( 0 );
killmycook . set Path (“/”);
killmycook . addCookie ( killmycook 1 );

Write suitable code examples to demonstrate the use of final, final, and finalize.

Final:  The final keyword is used for restricting a class, method, and variable. A final class can’t be inherited, a final method is disabled from overriding, and a final variable becomes a constant i.e., its value can’t be changed.

class FinalVarExample {
public static void main( String args[])
{
final int a=10;
a=50; /* Will result in an error as the value can’t be changed now*/
}

Finally: Any code inside the final block will be executed, irrespective of whether an exception is handled or not.

class FinallyExample {
public static void main(String args[]){
try {
int x=100;
}
catch(Exception e) {
System.out.println(e);
}
finally {
System.out.println(“finally block is executing”);}
}
}
}

Finalize: The finalize method performs the clean up just before the object is garbage collected.

class FinalizeExample {
public void finalize() {
System.out.println(“Finalize is called”);
}
public static void main(String args[])
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1= NULL;
f2=NULL;
System.gc();
}
}

What purpose do the Volatile variable serve in Java?

The value stored in a volatile variable is not read from the thread’s cache memory but from the main memory. Volatile variables are primarily used during synchronization.

Please compare Serialization with Deserialization in Java.

Serialization is the process by which Java objects are converted into the byte stream. Deserialization is the exact opposite process of serialization where Java objects are retrieved from the byte stream. A Java object is serialized by writing it to an ObjectOutputStream and deserialized by reading it from an ObjectInputStream.

What do you understand by OutOfMemoryError in Java?

Typically, the OutOfMemoryError exception is thrown when the JVM is not able to allocate an object due to running out of memory. In such a situation, no memory could be reclaimed by the garbage collector. There can be several reasons that result in the OutOfMemoryError exception, out of which most notable ones are:

  • Holding objects for too long
  • Trying to process too much data at the same time
  • Using a third-party library that caches strings
  • Using an application server that doesn’t perform a memory cleanup post the deployment
  • When a native allocation can’t be satisfied

That completes the list of top Java interview questions. What do you think about the list we compiled? Let us know by dropping your comments in the dedicated window below. Also, check out these best Java tutorials to further refine your Java skill set.

Explain public static void main(String args[ ]) in Java

The execution Java program starts with public static void main(String args[ ]), also called the main() method.

  • public: It is an access modifier defining the accessibility of the class or method. Any Class can access the main() method defined public in the program.
  • static: The keyword indicates the variable, or the method is a class method. The method main() is made static so that it can be accessed without creating the instance of the class. When the method main() is not made static, the compiler throws an error because the main() is called by the JVM before any objects are made, and only static methods can be directly invoked via the class.
  • void: It is the return type of the method. Void defines the method does not return any type of value.
  • main: JVM searches this method when starting the execution of any program, with the particular signature only.
  • String args[]: The parameter passed to the main method.

What are wrapper classes in Java?

Wrapper classes are responsible for converting the Java primitives into the reference types (objects). A class is dedicated to every primitive data type. They are known as wrapper classes because they wrap the primitive data type into an object of that class. It is present in Java.lang package. The table below displays the different primitive types, wrapper class.

Simple Type Wrapper Class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long

Explain the concept of boxing, unboxing, autoboxing, and auto unboxing.

 

  • Boxing: The concept of putting a primitive value inside an object is called boxing.
  • Unboxing: Getting the primitive value from the object.
  • Autoboxing: Assigning a value directly to an integer object.
  • Auto unboxing: Getting the primitive value directly into the integer object.

public class BoxUnbox
{
public static void main(String args[])
{
int i = 5;
Integer ii = new Integer(i);            /*Boxing*/
Integer jj = i; /*Unboxing*/
int j = jj.intValue();      /*Unboxing*/
int k = jj; /*AutoUnboxing*/
}
}

Define the Singleton class in Java. How can a class be made Singleton?

A Singleton class allows only one instance of the class to be created.

A class can be made singleton with the following steps:

  1. Creating a static instance of the class with the class.
  2. By not allowing the user to create an instance with default constructor by defining private constructor.
  3. Create a static method to return the object of an instance of A.

public class Singleton
{
public static void main(String args[])
{
Single obj1 = Single.getInstance();  /* both would point to one and same instance of the class */
Single obj2 = Single.getInstance();
}
}
class Single
{
static Single obj = new Single(); /* step a*/
private Single() /* step b*/
{
}
public static Single getInstance()
{
return obj; /* step c*/
}
}

What if the public static void is replaced by static public void, will the program still run?

Yes, the program would compile and run without any errors as the order of the specifiers don’t matter.

Differentiate between == and equals() ?

Equals() ==
It is a method of String class It is an operator.
Content comparison Address comparison
class Operator {
public static void main(String[] args)
{
/* integer-type*/
System.out.println(10 == 20);
/* char-type*/
System.out.println(‘a’ == ‘b’);
/* char and double type*/
System.out.println(‘a’ == 97.0);
/* boolean type*/
System.out.println(true == true);
}
}
public class Equals{
public static void main(String[] args)
{
String s1 = new String(“HELLO”);
String s2 = new String(“HELLO”);
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}

Why don’t we use pointers in Java?

Pointers are considered to be unsafe, and increase the complexity of the program, add

ing the concept of pointers can be contradicting. Also, JVM is responsible for implicit memory allocation; thus, to avoid direct access to memory by the user, pointers are discouraged in Java.

Differentiate between this() and super()

 

this() super()
Represents the current instance of the class. Represents the current instance of the parent/base class.
It is used to call the default constructor of the same class It is used to call the default constructor of the parent/base class.
Accesses method of the current class Accesses method of the base class
Points current class instance Points to the superclass instance.
Must be the first line of the block It must be the first line of the block.

 

Apart from having good knowledge about concepts of Java programming, you are also tested for your skills in coding in Java programming language. Given below are Java Coding Interview Questions that are relevant for freshers and are quite popular amongst Java programming interviews.

Take a look at the two code snippets below:

i.

class Adder {
Static int add(int a, int b)
{
return a+b;
}
Static double add( double a, double b)
{
return a+b;
}
public static void main(String args[])
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

ii.

class Car {
void run(){
System.out.println(“car is running”);
}
Class Audi extends Car{
void run()
{
System.out.prinltn(“Audi is running safely with 100km”);
}
public static void main( String args[])
{
Car b=new Audi();
b.run();
}
}

What is the important difference between the two?

Code snippet i. is an example of method overloading while the code snippet ii. demonstrates method overriding.

Program for string reversal without using inbuilt function

 

public class Reversal
{
public static void main(String args[])
{
String input = “Java Interview”;
System.out.println(“Given String -> ” + “Java Interview”);
char charArray[] = input.toCharArray();
System.out.println(“Reversed String -> “);
for(int i = charArray.length-1;i>=0; i–)
{
System.out.print(charArray[i]);
}
System.out.println();
}
}

Program to delete duplicate from an array

 

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
class RemoveDuplicates
{
public static void main(String args[])
{
/*create ArrayList with duplicate elements*/
ArrayList duplicate = new ArrayList();
duplicate.add(5);
duplicate.add(7);
duplicate.add(1);
duplicate.add(4);
duplicate.add(1);
duplicate.add(7);
System.out.println(“Given array: “+ duplicate);
Set <Integer> withoutDuplicates = new LinkedHashSet<Integer>(duplicate)
duplicate.clear();
duplicate.addAll(withoutDuplicates);
System.out.println(“Array without duplicates: “+ duplicate);
}
}

Program to reverse a number

 

import java.util.Scanner;
public class NumberReversal
{
public static void main(String args[])
{
System.out.println(“Please enter the number to be reversed”);
Scanner sc = new Scanner (System.in);
int number = sc.nextInt();
int reverse = reverse(number);
System.out.println(“Reverse of number: ” + number + ” is ” + reverse(number));
}
public static int reverse(int number){
int reverse = 0;
int remainder = 0;
do{
remainder = number%10;
reverse = reverse*10 + remainder;
number = number/10;
}while(number > 0);
return reverse;
}
}

Program for binary search

 

import java.util.Scanner;
import java.util.Arrays;
public class Binary {
public static void main(String[] args) {
System.out.println(“Enter total number of elements : “);
Scanner s = new Scanner (System.in);
int length = s.nextInt();
int[] input = new int[length];
System.out.printf(“Enter %d integers”, length);
for (int i = 0; i < length; i++) {
input[i] = s.nextInt();
}
/* binary search requires the input array to be sorted so we must sort the array first*/
Arrays.sort(input);
System.out.print(“the sorted array is: “);
for(int i= 0; i<= length-1;i++)
{
System.out.println(input[i] + ” ,”);
}
System.out.println(“Please enter number to be searched in sorted array”);
int key = s.nextInt();
int index = BSearch(input, key);
if (index == -1) {
System.out.printf(“Sorry, %d is not found in array %n”, key);
} else {
System.out.printf(“%d is found in array at index %d %n”, key,
index);
}
}
public static int BSearch(int[] input, int number) {
int low = 0;
int high = input.length – 1;
while (high >= low) {
int middle = (low + high) / 2;
if (input[middle] == number) {
return middle;
} else if (input[middle] < number) {
low = middle + 1;
} else if (input[middle] > number) {
high = middle – 1;
}
}
return -1;
}
}

Program to check if a number is prime.

 

import java.util.Scanner;
public class Prime
{
public static void main(String args[])
{
System.out.println(“Enter the number to check: “);
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
boolean isPrime = false;
if(num!=0)
{
isPrime = checkPrime(num);
}else
{
System.out.println(“Enter valid number”);
}
if(isPrime == false)
{
System.out.println(” NOT PRIME!!”);
}
else
{
System.out.println(“PRIME!!”);
}
}
public static boolean checkPrime(int number)
{
int sqrt = (int) Math.sqrt(number) + 1;
for(int i = 2; i<sqrt; i++)
{
if(number % i== 0)
{
return false;
}
}
return true;
}
}

Program to print Fibonacci Series

 

import java.util.Scanner;
public class Fibo
{
public static void main(String args[])
{
System.out.println(“Enter the number upto which Fibonacci series should be printed “);
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println(“Fibonacci Series upto %d is” + num);
for(int i=1; i<=num; i++)
{
System.out.print(fib(i) + ” “);
}
}
public static int fib(int n)
{
if(n ==1 || n==2)
{
return 1;
}
return fib(n-1) + fib(n-2);
}
}

Program to check if the given string is a palindrome.

 

import java.util.Scanner;
public class PalinDrome
{
public static void main(String args[])
{
System.out.println(“Enter the string to check”);
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
boolean isPalindrome;
isPalindrome = checkPalindrome(str);
if(str.equals(” “))
{
System.out.println(“Enter valid string”);
}
else
{
if(isPalindrome)
{
System.out.println(“PALINDROME!!”);
}
else
{
System.out.println(“NOT A PALINDROME!!”);
}
}
}
public static boolean checkPalindrome(String input)
{
int str_length = input.length();
int i=0, j= str_length-1;
while(i<j)
{
if(input.charAt(i) != input.charAt(j))
return false;
i++;
j–;
}
return true;
}
}

Questions: Pattern printing

*
* *
* * *
* * * *
* * * * *

 

public class Pattern
{
public static void main(String args[])
{
for(int i=5; i>=0; i–)
{
System.out.println();
for(int j=i; j<5;j++)
{
System.out.print(” * “);
}
}
System.out.println();
}
}

Program to swap two numbers

 

import java.util.Scanner;
public class Swap
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println(“Enter a number: “);
int a = s.nextInt();
System.out.println(“Enter second number: “);
int b = s.nextInt();
System.out.println(“Value of a and b before swapping: ” + “a = ” +a  + ” b = ” + b);
swap(a,b);
}
public static void swap(int a , int b)
{
int swap_variable;
swap_variable = a;
a = b;
b = swap_variable;
System.out.println(“Value of a and b after swapping: ” + “a = ” +a  + ” b = ” + b);
}
}

Program to check if the given number is an Armstrong number.

 

import java.util.Scanner;
public class Armstrong
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println(“Enter a number: “);
int number = s.nextInt();
int a=number, sum = 0, num=0;
while(a%10 !=0)
{
num = a%10;
sum = sum + (num*num*num);
a = a/10;
}
if(sum == number)
{
System.out.println(“Armstrong Number!”);
}
else
{
System.out.println(“Not an Armstrong Number!”);
}
}
}

How does Java enable high performance?

Java uses Just In Time compiler to enable high performance. It is used to convert the instructions into bytecodes.

Name the Java IDE’s?

Eclipse and NetBeans are the IDE’s of JAVA.

What do you mean by Constructor?

Constructor can be explained in detail with enlisted points:

  • When a new object is created in a program a constructor gets invoked corresponding to the class.
  • The constructor is a method which has the same name as the class name.
  • If a user doesn’t create a constructor implicitly a default constructor will be created.
  • The constructor can be overloaded.
  • If the user created a constructor with a parameter then he should create another constructor explicitly without a parameter.

What is meant by the Local variable and the Instance variable?

Local variables are defined in the method and scope of the variables that exist inside the method itself.

Instance variable is defined inside the class and outside the method and the scope of the variables exists throughout the class.

What is a Class?

All Java codes are defined in a Class. It has variables and methods.

Variables are attributes which define the state of a class.

Methods are the place where the exact business logic has to be done. It contains a set of statements (or) instructions to satisfy the particular requirement.

Example:

public class Addition{ //Class name declaration

int a = 5; //Variable declaration

int b= 5;

public void add(){ //Method declaration

int c = a+b;

}

}

What is an Object?

An instance of a class is called an object. The object has state and behavior.

Whenever the JVM reads the “new()” keyword then it will create an instance of that class.

Example:

public class Addition{

public static void main(String[] args){

Addion add = new Addition();//Object creation

}

}

The above code creates the object for the Addition class.

What are the OOPs concepts?

OOPs concepts include:

  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction
  • Interface

What is Inheritance?

Inheritance means one class can extend to another class. So that the codes can be reused from one class to another class. The existing class is known as the Super class whereas the derived class is known as a sub class.

Example:

Super class:

public class Manupulation(){

}

Sub class:

public class Addition extends Manipulation(){

}

Inheritance is only applicable to the public and protected members only. Private members can’t be inherited.

What is Encapsulation?

Purpose of Encapsulation:

  • Protects the code from others.
  • Code maintainability.

Example:

We are declaring ‘a’ as an integer variable and it should not be negative.

public class Addition(){

int a=5;

}

If someone changes the exact variable as “a = -5” then it is bad.

In order to overcome the problem we need to follow the steps below:

  • We can make the variable private or protected.
  • Use public accessor methods such as set<property> and get<property>.

So that the above code can be modified as:

public class Addition(){

private int a = 5; //Here the variable is marked as private

}

The code below shows the getter and setter.

Conditions can be provided while setting the variable.

get A(){

}

set A(int a){

if(a>0){// Here condition is applied

………

}

}

For encapsulation, we need to make all the instance variables private and create setter and getter for those variables. Which in turn will force others to call the setters rather than access the data directly.

What is Polymorphism?

Polymorphism means many forms.

A single object can refer to the super-class or sub-class depending on the reference type which is called polymorphism.

Example:

Public class Manipulation(){ //Super class

public void add(){

}

}

public class Addition extends Manipulation(){ // Sub class

public void add(){

}

public static void main(String args[]){

Manipulation addition = new Addition();//Manipulation is reference type and Addition is reference type

addition.add();

}

}

Using the Manipulation reference type we can call the Addition class “add()” method. This ability is known as Polymorphism. Polymorphism is applicable for overriding and not for overloading.

What is meant by Method Overriding?

Method overriding happens if the sub-class method satisfies the below conditions with the Super-class method:

  • Method name should be the same
  • The argument should be the same
  • Return type should also be the same

The key benefit of overriding is that the Sub-class can provide some specific information about that sub-class type than the super-class.

Example:

public class Manipulation{ //Super class

public void add(){

………………

}

}

 

Public class Addition extends Manipulation(){

Public void add(){

………..

}

Public static void main(String args[]){

Manipulation addition = new Addition(); //Polimorphism is applied

addition.add(); // It calls the Sub class add() method

}

}

addition.add() method calls the add() method in the Sub-class and not the parent class. So it overrides the Super-class method and is known as Method Overriding.

What is meant by Overloading?

Method overloading happens for different classes or within the same class.

For method overloading, sub-class method should satisfy the below conditions with the Super-class method (or) methods in the same class itself:

  • Same method name
  • Different argument types
  • There may be different return types

Example:

public class Manipulation{ //Super class

public void add(String name){ //String parameter

………………

}

}

 

Public class Addition extends Manipulation(){

Public void add(){//No Parameter

………..

}

Public void add(int a){ //integer parameter

 

}

Public static void main(String args[]){

Addition addition = new Addition();

addition.add();

}

}

Here the add() method has different parameters in the Addition class is overloaded in the same class as with the super-class.

Note: Polymorphism is not applicable for method overloading.

What is meant by Interface?

Multiple inheritances cannot be achieved in java. To overcome this problem the Interface concept is introduced.

An interface is a template which has only method declarations and not the method implementation.

Example:

Public abstract interface IManupulation{ //Interface declaration

Public abstract void add();//method declaration

public abstract void subtract();

}

  • All the methods in the interface are internally public abstract void.
  • All the variables in the interface are internally public static final that is constants.
  • Classes can implement the interface and not extends.
  • The class which implements the interface should provide an implementation for all the methods declared in the interface.
public class Manupulation implements IManupulation{ //Manupulation class uses the interface

Public void add(){

……………

}

Public void subtract(){

…………….

}

}

What is meant by Abstract class?

We can create the Abstract class by using the “Abstract” keyword before the class name. An abstract class can have both “Abstract” methods and “Non-abstract” methods that are a concrete class.

Abstract method:

The method which has only the declaration and not the implementation is called the abstract method and it has the keyword called “abstract”. Declarations ends with a semicolon.

Example:

public abstract class Manupulation{

public abstract void add();//Abstract method declaration

Public void subtract(){

}

}

  • An abstract class may have a non- abstract method also.
  • The concrete Subclass which extends the Abstract class should provide the implementation for abstract methods.

 

Difference between String, String Builder, and String Buffer.

String: String variables are stored in a “constant string pool”. Once the string reference changes the old value that exists in the “constant string pool”, it cannot be erased.

Example:

String name = “book”;

Constant string pool

.

If the name-value has changed from “book” to “pen”.

Constant string pool

Then the older value remains in the constant string pool.

String Buffer:

  • Here string values are stored in a stack. If the values are changed then the new value replaces the older value.
  • The string buffer is synchronized which is thread-safe.
  • Performance is slower than the String Builder.

Example:

String Buffer name =”book”;

Once the name value has been changed to “pen” then the “book” is erased in the stack.

String Builder:

This is the same as String Buffer except for the String Builder which is not threaded safely that is not synchronized. So obviously the performance is fast.

Explain about Public and Private access specifiers.

Methods and instance variables are known as members.

Public:

Public members are visible in the same package as well as the outside package that is for other packages.

Public members of Class A are visible to Class B (same package) as well as Class C (different packages).

Private:

Private members are visible in the same class only and not for the other classes in the same package as well as classes in the outside packages.

Private members in class A are visible only in that class. It is invisible for class  B as well as class C.

Difference between Default and Protected access specifiers.

 

Default: Methods and variables declared in a class without any access specifiers are called default.

Default members in Class A are visible to the other classes which are inside the package and invisible to the classes which are outside the package.

So Class A members are visible to Class B and invisible to Class C.

Protected:

.

Protected is the same as Default but if a class extends then it is visible even if it is outside the package.

Class A members are visible to Class B because it is inside the package. For Class C it is invisible but if Class C extends Class A then the members are visible to Class C even if it is outside the package.

Difference between HashMap and HashTable.

The difference between HashMap and HashTable can be seen below:

HashMap HashTable
Methods are not synchronized Key methods are synchronized
Not thread safety Thread safety
Iterator is used to iterate the values Enumerator is used to iterate the values
Allows one null key and multiple null values Doesn’t allow anything that is null
Performance is high than HashTable Performance is slow

Difference between HashSet and TreeSet.

The difference between HashSet and TreeSet can be seen below:

HashSet TreeSet
Inserted elements are in random order Maintains the elements in the sorted order
Can able to store null objects Couldn’t store null objects
Performance is fast Performance is slow

Difference between Abstract class and Interface.

The differences between Abstract Class and Interface are as follows:

Abstract Class:

  • Abstract classes have a default constructor and it is called whenever the concrete subclass is instantiated.
  • It contains Abstract methods as well as Non-Abstract methods.
  • The class which extends the Abstract class shouldn’t require the implementation of all the methods, only Abstract methods need to be implemented in the concrete sub-class.
  • Abstract class contains instance variables.

Interface:

  • It doesn’t have any constructor and couldn’t be instantiated.
  • The abstract method alone should be declared.
  • Classes that implement the interface should provide the implementation for all the methods.
  • The interface contains only constants.

What is the meaning of Collections in Java?

Collection is a framework that is designed to store the objects and manipulate the design to store the objects.

Collections are used to perform the following operations:

  • Searching
  • Sorting
  • Manipulation
  • Insertion
  • Deletion

A group of objects is known as collections. All the classes and interfaces for collecting are available in Java util package.

What are all the Classes and Interfaces that are available in the collections?

Given below are the Classes and Interfaces that are available in Collections:

Interfaces:

  • Collection
  • List
  • Set
  • Map
  • Sorted Set
  • Sorted Map
  • Queue

Classes:

  • Lists:
  • Array List
  • Vector
  • Linked List

Sets:

  • Hash set
  • Linked Hash Set
  • Tree Set

Maps:

  • Hash Map
  • Hash Table
  • TreeMap
  • Linked Hashed Map

Queue:

  • Priority Queue

What is meant by Ordered and Sorted in collections?

 

Ordered: It means the values that are stored in a collection is based on the values that are added to the collection. So we can iterate the values from the collection in a specific order.

Sorted: Sorting mechanisms can be applied internally or externally so that the group of objects sorted in a particular collection is based on the properties of the objects.

Explain the different lists available in the collection.

Values added to the list are based on the index position and it is ordered by index position. Duplicates are allowed.

The types of Lists are:

  1. a) Array List:
  • Fast iteration and fast Random Access.
  • It is an ordered collection (by index) and not sorted.
  • It implements the Random Access Interface.

Example:

public class Fruits{

public static void main (String [ ] args){

ArrayList <String>names=new ArrayList <String>();

names.add (“apple”);

names.add (“cherry”);

names.add (“kiwi”);

names.add (“banana”);

names.add (“cherry”);

System.out.println (names);

}

}

Output:

[Apple, cherry, kiwi, banana, cherry]

From the output, Array List maintains the insertion order and it accepts the duplicates. But it’s not sorted.

  1. b) Vector:

It is the same as Array List.

  • Vector methods are synchronized.
  • Thread safety.
  • It also implements Random Access.
  • Thread safety usually causes a performance hit.

Example:

public class Fruit {

public static void main (String [ ] args){

Vector <String> names = new Vector <String> ( );

names.add (“cherry”);

names.add (“apple”);

names.add (“banana”);

names.add (“kiwi”);

names.add (“apple”);

System.out.println (“names”);

}

}

Output:

[cherry,apple,banana,kiwi,apple]

Vector also maintains the insertion order and accepts the duplicates.

  1. c) Linked List:
  • Elements are doubly linked to one another.
  • Performance is slower than the Array list.
  • Good choice for insertion and deletion.
  • In Java 5.0 it supports common queue methods peek( ), Pool ( ), Offer ( ) etc.

Example:

public class Fruit {

public static void main (String [ ] args){

Linkedlist <String> names = new linkedlist <String> ( ) ;

names.add(“banana”);

names.add(“cherry”);

names.add(“apple”);

names.add(“kiwi”);

names.add(“banana”);

System.out.println (names);

}

}

Output:

[ banana,cherry,apple,kiwi,banana]

Maintains the insertion order and accepts the duplicates.

Explain about Set and their types in a collection.

Set cares about uniqueness. It doesn’t allow duplications. Here “equals ( )” method is used to determine whether two objects are identical or not.

  1. a) Hash Set:
  • Unordered and unsorted.
  • Uses the hash code of the object to insert the values.
  • Use this when the requirement is “no duplicates and don’t care about the order”.

Example:

public class Fruit {

public static void main (String[ ] args){

HashSet<String> names = new HashSet <=String>( ) ;

names.add(“banana”);

names.add(“cherry”);

names.add(“apple”);

names.add(“kiwi”);

names.add(“banana”);

System.out.println (names);

}

}

Output:

[banana, cherry, kiwi, apple]

It doesn’t follow any insertion order. Duplicates are not allowed.

  1. b) Linked Hash set:
  • An ordered version of the hash set is known as Linked Hash Set.
  • Maintains a doubly-Linked list of all the elements.
  • Use this when an iteration order is required.

Example:

public class Fruit {

public static void main (String[ ] args){

LinkedHashSet<String>; names = new LinkedHashSet <String>( ) ;

names.add(“banana”);

names.add(“cherry”);

names.add(“apple”);

names.add(“kiwi”);

names.add(“banana”);

System.out.println (names);

}

}

Output:

[banana, cherry, apple, kiwi]

It maintains the insertion order in which they have been added to the Set. Duplicates are not allowed.

  1. c) Tree Set:
  • It is one of the two sorted collections.
  • Uses the “Read-Black” tree structure and guarantees that the elements will be in ascending order.
  • We can construct a tree set with the constructor by using a comparable (or) comparator.

Example:

public class Fruits{

public static void main (String[ ]args) {

Treeset<String> names= new TreeSet<String>( ) ;

names.add(“cherry”);

names.add(“banana”);

names.add(“apple”);

names.add(“kiwi”);

names.add(“cherry”);

System.out.println(names);

}

}

Output:

[apple, banana, cherry, kiwi]

TreeSet sorts the elements in ascending order. And duplicates are not allowed.

Explain about Map and its types.

Map cares about the unique identifier. We can map a unique key to a specific value. It is a key/value pair. We can search a value, based on the key. Like the set, the map also uses the “equals ( )” method to determine whether two keys are the same or different.

Map is of following types:

  1. a) Hash Map:
  • Unordered and unsorted map.
  • Hashmap is a good choice when we don’t care about the order.
  • It allows one null key and multiple null values.

Example:

Public class Fruit{

Public static void main(String[ ] args){

HashMap<Sting,String> names =new HashMap<String,String>( );

names.put(“key1”,“cherry”);

names.put (“key2”,“banana”);

names.put (“key3”,“apple”);

names.put (“key4”,“kiwi”);

names.put (“key1”,“cherry”);

System.out.println(names);

}

}

Output:

{key2 =banana, key1=cherry, key4 =kiwi, key3= apple}

Duplicate keys are not allowed in Map.

It doesn’t maintain any insertion order and is unsorted.

  1. b) Hash Table:
  • Like the vector key, methods of the class are synchronized.
  • Thread safety and therefore slows the performance.
  • It doesn’t allow anything that is null.

Example:

public class Fruit{

public static void main(String[ ]args){

Hashtable<Sting,String> names =new Hashtable<String,String>( );

names.put(“key1”,“cherry”);

names.put(“key2”,“apple”);

names.put(“key3”,“banana”);

names.put(“key4”,“kiwi”);

names.put(“key2”,“orange”);

System.out.println(names);

}

}

Output:

{key2=apple, key1=cherry,key4=kiwi, key3=banana}

Duplicate keys are not allowed.

  1. c) Linked Hash Map:
  • Maintains insertion order.
  • Slower than Hash map.
  • I can expect a faster iteration.

Example:

public class Fruit{

public static void main(String[ ] args){

LinkedHashMap<Sting,String> names =new LinkedHashMap<String,String>( );

names.put(“key1”,“cherry”);

names.put(“key2”,“apple”);

names.put(“key3”,“banana”);

names.put(“key4”,“kiwi”);

names.put(“key2”,“orange”);

System.out.println(names);

}

}

Output:

{key2=apple, key1=cherry,key4=kiwi, key3=banana}

Duplicate keys are not allowed.

  1. d) TreeMap:
  • Sorted Map.
  • Like Tree set, we can construct a sort order with the constructor.

Example:

public class Fruit{

public static void main(String[ ]args){

TreeMap<Sting,String> names =new TreeMap<String,String>( );

names.put(“key1”,“cherry”);

names.put(“key2”,“banana”);

names.put(“key3”,“apple”);

names.put(“key4”,“kiwi”);

names.put(“key2”,“orange”);

System.out.println(names);

}

}

Output:

{key1=cherry, key2=banana, key3 =apple, key4=kiwi}

It is sorted in ascending order based on the key. Duplicate keys are not allowed.

Explain the Priority Queue.

Queue Interface

Priority Queue: Linked list class has been enhanced to implement the queue interface. Queues can be handled with a linked list. The purpose of a queue is “Priority-in, Priority-out”.

Hence elements are ordered either naturally or according to the comparator. The elements ordering represents their relative priority.

What is meant by Exception?

An Exception is a problem that can occur during the normal flow of execution. A method can throw an exception when something wails at runtime. If that exception couldn’t be handled, then the execution gets terminated before it completes the task.

If we handled the exception, then the normal flow gets continued. Exceptions are a subclass of java.lang.Exception.

Example for handling Exception:

try{

//Risky codes are surrounded by this block

}catch(Exception e){

//Exceptions are caught in catch block

}

What are the types of Exceptions?

There are two types of Exceptions. They are explained below in detail.

  1. a) Checked Exception:

These exceptions are checked by the compiler at the time of compilation. Classes that extend Throwable class except Runtime exception and Error are called checked Exception.

Checked Exceptions must either declare the exception using throws keyword (or) surrounded by appropriate try/catch.

For Example, ClassNotFound Exception

  1. b) Unchecked Exception:

These exceptions are not checked during the compile time by the compiler.  The compiler doesn’t force to handle these exceptions. It includes:

  • Arithmetic Exception
  • ArrayIndexOutOfBounds Exception

What are the different ways to handle exceptions?

Two different ways to handle exceptions are explained below:

  1. a) Using try/catch:

The risky code is surrounded by try block. If an exception occurs, then it is caught by the catch block which is followed by the try block.

Example:

class Manipulation{

public static void main(String[] args){

add();

}

Public void add(){

try{

addition();

}catch(Exception e){

e.printStacktrace();

}

}

}

  1. b) By declaring throws keyword:

At the end of the method, we can declare the exception using throws keyword.

Example:

class Manipulation{

public static void main(String[] args){

add();

}

public void add() throws Exception{

addition();

}

}

What are the advantages of Exception handling?

The advantages are as follows:

  • The normal flow of the execution won’t be terminated if an exception gets handled
  • We can identify the problem by using catch declaration

What are the Exception handling keywords in Java?

Enlisted below are the two Exception Handling Keywords:

  1. a) try:

When a risky code is surrounded by a try block. An exception occurring in the try block is caught by a catch block. Try can be followed either by catch (or) finally (or) both. But any one of the blocks is mandatory.

  1. b) catch:

This is followed by a try block. Exceptions are caught here.

  1. c) finally:

This is followed either by try block (or) catch block. This block gets executed regardless of an exception. So generally clean up codes are provided here.

Explain about Exception Propagation.

Exception is first thrown from the method which is at the top of the stack. If it doesn’t catch, then it pops up the method and moves to the previous method and so on until they are got.

This is called Exception propagation.

Example:

public class Manipulation{

public static void main(String[] args){

add();

}

public void add(){

addition();

}

From the above example, the stack looks like as shown below:

 

If an exception occurs in the addition() method is not caught, then it moves to the method add(). Then it is moved to the main() method and then it will stop the flow of execution. It is called Exception Propagation.

What is the final keyword in Java?

 

Final variable: Once a variable is declared as final, then the value of the variable could not be changed. It is like a constant.

Example:

final int = 12;

Final method: A final keyword in a method, couldn’t be overridden. If a method is marked as a final, then it can’t be overridden by the subclass.

Final class: If a class is declared as final, then the class couldn’t be subclassed. No class can extend the final class.

What is a Thread?

In Java, the flow of execution is called Thread. Every java program has at least one thread called the main thread, the main thread is created by JVM. The user can define their own threads by extending the Thread class (or) by implementing the Runnable interface. Threads are executed concurrently.

Example:

public static void main(String[] args){//main thread starts here

}

How do you make a thread in Java?

There are two ways available to make a thread.

  1. a) Extend Thread class: Extending a Thread class and override the run method. The thread is available in java.lang.thread.

Example:

Public class Addition extends Thread {

public void run () {

}

}

The disadvantage of using a thread class is that we cannot extend any other classes because we have already extended the thread class. We can overload the run () method in our class.

  1. b) Implement Runnable interface: Another way is by implementing the runnable interface. For that, we should provide the implementation for the run () method which is defined in the interface.

Example:

Public class Addition implements Runnable {

public void run () {

}

}

Explain about join () method.

Join () method is used to join one thread with the end of the currently running thread.

Example:

public static void main (String[] args){

Thread t = new Thread ();

t.start ();

t.join ();

}

Based on the above code, the main thread has started the execution. When it reaches the code t.start() then ‘thread t’ starts the own stack for the execution. JVM switches between the main thread and ‘thread t’.

Once it reaches the code t.join() then ‘thread t’ alone is executed and completes its task, then only the main thread starts the execution.

It is a non-static method. The Join () method has an overloaded version. So we can mention the time duration in join () method also “.s”.

What does the yield method of the Thread class do?

A yield () method moves the currently running thread to a runnable state and allows the other threads for execution. So that equal priority threads have a chance to run. It is a static method. It doesn’t release any lock.

Yield () method moves the thread back to the Runnable state only, and not the thread to sleep (), wait () (or) block.

Example:

public static void main (String[] args){

Thread t = new Thread ();

t.start ();

}

public void run(){

Thread.yield();

}

}

Explain about wait () method.

wait () method is used to make the thread to wait in the waiting pool. When the wait () method is executed during a thread execution then immediately the thread gives up the lock on the object and goes to the waiting pool. Wait () method tells the thread to wait for a given amount of time.

Then the thread will wake up after notify () (or) notify all () method is called.

Wait() and the other above-mentioned methods do not give the lock on the object immediately until the currently executing thread completes the synchronized code. It is mostly used in synchronization.

Example:

public static void main (String[] args){

Thread t = new Thread ();

t.start ();

Synchronized (t) {

Wait();

}

}

Difference between notify() method and notifyAll() method in Java.

The differences between notify() method and notifyAll() method are enlisted below:

notify() notifyAll()
This method is used to send a signal to wake up a single thread in the waiting pool. This method sends the signal to wake up all the threads in a waiting spool.

. How to stop a thread in java? Explain about sleep () method in a thread?

We can stop a thread by using the following thread methods:

  • Sleeping
  • Waiting
  • Blocked

Sleep: Sleep () method is used to sleep the currently executing thread for the given amount of time. Once the thread is wake up it can move to the runnable state. So sleep () method is used to delay the execution for some period.

It is a static method.

Example:

Thread. Sleep (2000)

So it delays the thread to sleep 2 milliseconds. Sleep () method throws an uninterrupted exception, hence we need to surround the block with try/catch.

public class ExampleThread implements Runnable{

public static void main (String[] args){

Thread t = new Thread ();

t.start ();

}

public void run(){

try{

Thread.sleep(2000);

}catch(InterruptedException e){

}

}

When to use the Runnable interface Vs Thread class in Java?

If we need our class to extend some other classes other than the thread then we can go with the runnable interface because in java we can extend only one class.

If we are not going to extend any class then we can extend the thread class.

Which methods are used during the Serialization and Deserialization process?

ObjectOutputStream and ObjectInputStream classes are higher level java.io. package. We will use them with lower level classes FileOutputStream and FileInputStream.

ObjectOutputStream.writeObject —->Serialize the object and write the serialized object to a file.

ObjectInputStream.readObject —> Reads the file and deserializes the object.

To be serialized, an object must implement the serializable interface. If superclass implements Serializable, then the subclass will automatically be serializable.

What is the purpose of a Volatile Variable?

Volatile variable values are always read from the main memory and not from thread’s cache memory. This is used mainly during synchronization. It is applicable only for variables.

Example:

volatile int number;

Difference between Serialization and Deserialization in Java.

These are the differences between serialization and deserialization in java:

Serialization Deserialization
Serialization is the process which is used to convert the objects into byte stream Deserialization is the opposite process of serialization where we can get the objects back from the byte stream.
An object is serialized by writing it an ObjectOutputStream. An object is deserialized by reading it from an ObjectInputStream.

What is SerialVersionUID?

Whenever an object is Serialized, the object is stamped with a version ID number for the object class. This ID is called the  SerialVersionUID. This is used during deserialization to verify that the sender and receiver that are compatible with the Serialization.

 

Difference between start() and run() method of thread class.

Start() method creates a new thread and the code inside the run () method is executed in the new thread. If we directly called the run() method then a new thread is not created and the currently executing thread will continue to execute the run() method.

What is Multi-threading?

Multiple threads are executed simultaneously. Each thread starts its own stack based on the flow (or) priority of the threads.

Example Program:

public class MultipleThreads implements Runnable

{

public static void main (String[] args){//Main thread starts here

Runnable r = new runnable ();

Thread t=new thread ();

t.start ();//User thread starts here

Addition add=new addition ();

}

public void run(){

go();

}//User thread ends here

}

On the 1st line execution, JVM calls the main method and the main thread stack looks as shown below.

Once the execution reaches, t.start () line then a new thread is created and the new stack for the thread is also created. Now JVM switches to the new thread and the main thread are back to the runnable state.

The two stacks look as shown below.

Now, the user thread executed the code inside the run() method.

Once the run() method has completed, then JVM switches back to the main thread and the user thread has completed the task and the stack was disappeared.

JVM switches between each thread until both the threads are completed. This is called Multi-threading.

Explain the thread life cycle in Java.

Thread has the following states:

  • New
  • Runnable
  • Running
  • Non-runnable (Blocked)
  • Terminated
  • New: In New state, a Thread instance has been created but start () method is not yet invoked. Now the thread is not considered alive.
  • Runnable: The Thread is in the runnable state after the invocation of the start () method, but before the run () method is invoked. But a thread can also return to the runnable state from waiting/sleeping. In this state, the thread is considered alive.
  • Running: The thread is in a running state after it calls the run () method. Now the thread begins the execution.
  • Non-Runnable(Blocked): The thread is alive but it is not eligible to run. It is not in the runnable state but also, it will return to the runnable state after some time. Example: wait, sleep, block.
  • Terminated: Once the run method is completed then it is terminated. Now the thread is not alive.

What is Synchronization?

Synchronization makes only one thread to access a block of code at a time. If multiple threads accesses the block of code, then there is a chance for inaccurate results at the end. To avoid this issue, we can provide synchronization for the sensitive block of codes.

The synchronized keyword means that a thread needs a key in order to access the synchronized code.

Locks are per objects. Every Java object has a lock. A lock has only one key. A thread can access a synchronized method only if the thread can get the key to the objects to lock.

For this, we use the “Synchronized” keyword.

Example:

public class ExampleThread implements Runnable{

public static void main (String[] args){

Thread t = new Thread ();

t.start ();

}

public void run(){

synchronized(object){

{

}

}

What is the disadvantage of Synchronization?

Ans: Synchronization is not recommended to implement all the methods. Because if one thread accesses the synchronized code then the next thread should have to wait. So it makes a slow performance on the other end.

What is meant by Serialization?

Converting a file into a byte stream is known as Serialization. The objects in the file are converted to bytes for security purposes. For this, we need to implement a java.io.Serializable interface. It has no method to define.

Variables that are marked as transient will not be a part of the serialization. So we can skip the serialization for the variables in the file by using a transient keyword.

What is the purpose of a transient variable?

Transient variables are not part of the serialization process. During deserialization, the values of the transient variables are set to the default value. It is not used with static variables.

Example:

transient int numbers;

So, this brings us to the end of the Java and JEE Interview Questions blog.This Tecklearn ‘Top JAVA and JEE Interview Questions and Answers’ helps you with commonly asked questions if you are looking out for a job in Programming Domain. If you wish to learn Java and build a career in Programming domain, then check out our interactive Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period.

 

https://www.tecklearn.com/course/java-and-jee-training/

Table of Contents

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Top Java and JEE Interview Questions and Answers"

Leave a Message

Your email address will not be published. Required fields are marked *