top of page
Search
Writer's pictureTuyen Nguyen

Nail Your Java Interview

Updated: Jul 29

Java is used by approximately 10 million developers worldwide to develop applications for 15 billion devices. And it still stays as high-demand language in job market.


Prepare for your Java interview but don't know where to start?


So in this post, I'm going to list some most frequently asked Java questions by interviewers and answer them.


I have classified those into those sections below:

Spring Framework and Hibernate are not intended to be included as this is not aimed for Java Developers but Automation Engineers in Java instead.

 

Basic Java Questions


Q1. JDK, JRE and JVM

JDK

JRE

JVM

Stands for Java Development Kit

Stands for Java Runtime Environment

​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 program 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

It is responsible for executing program line by line (known as interpreter)


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

main() is the entry point of execution for any Java program.

  • public: an access modifier, and public means that this method will be accessible by any class.

  • static: a keyword which identifies it is class-based (belongs to class, not instance). main() is made static so that it can be invoked directly by JVM through the class without creating the instance of the class.

  • void: a return type of method. Void defines the method which will not return any value.

  • main: name of the method - which is searched by JVM as starting point. This is where execution occurs.

  • String args[]: parameter set passed to the main method.


Q3. 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.


Q4. What are constructors in Java?

In Java, constructor refers to a block of code which is used to initialize an object. It has the same name of class, has no return type and automatically triggered when object is created.

Two type of constructor:

  • Default constructor: In case no other constructor is defined by user, this is triggered by default when initializing the instance variables with default values. It is no argument constructor (not take any inputs).

  • Parameterized constructor: It is capable of initializing instance variables with provided values. It take arguments.


Q5. What is singleton class in Java and hot to 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.


Q6. What is the difference between ArrayList and Vector in Java?

ArrayList

Vector

​ArrayList is not synchronized

​Vector is synchronized

​Fast as it's non-synchronized

​Slow as it is thread-safe

​If an element is inserted into ArrayList, it increases it Array size by 50%

​Vector defaults to doubling size of its array

​Does not define the increment size

​Define the increment size

​Can only use Iterator for traversing an ArrayList

​Can use both Enumeration and Iterator for traversing

Q7. Iterator and Enumeration

Iterator:

The Iterator interface provides methods to iterate over any Collection in Java. Iterator is the replacement of Enumeration in the Java Collections Framework. It can get an iterator instance from a Collection using the iterator() method.  It also allows the caller to remove elements from the underlying collection during the iteration.


Enumeration:

Enumeration is a user-defined data type. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. The main objective of the enum is to define user-defined data types.

// A simple enum example where enum is declared 
// outside any class (Note enum keyword instead of // class keyword) 
enum Color {
     RED, GREEN, BLUE; 
}

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

There are three main differences:

  • equals() is a method and == is a operator.

  • equals() method for content comparison whereas == for reference comparison (address comparison). == checks if both objects point to the same memory location whereas equals() evaluates values in the objects.

  • Should use == to compare primitive data types, while use equals() to compare objects in Java.

For more info, head to Equals() and == operators in Java.


Q9. What are differences between Heap and Stack Memory in Java?

​Stack

​Heap

Application

​Is only used by one thread of execution

​Is used by all parts of the application

Access

Can't be accessed by other threads

Objects stored in heap are globally accessible

Memory management

Follows LIFO manner to free memory

Is based on the complex generation techniques associated with each object

Lifetime

Exist until the end of execution of the thread

Lives from the start till the end of application execution

​Usage

​Only contains primitive variables and references to objects created in Heap space

All the newly created objects are stored here

Efficiency

Comparatively much faster then Heap

Slower to allocate compared to Stack

Allocation/Deallocation

​Automatically allocate and deallocate when a method is called and returned respectively

​Is allocated when new objects are created and deallocated by Garbage Collector when they are no longer referenced


Q10. What is a package in Java? List down advantages of it

Package are the collection of related classes, sub-packages and interfaces which are bundled together. By using them, developers can easily modularized the code and optimize its reuse. The code within packages can be imported by other classes and reused. Few of its advantages:

  • Helps in avoiding naming conflicts.

  • Provide easier access control on the code (access modifiers - default).

  • Can contain hidden classes which are not visible to outer classes and only used within the package.

  • Create a proper hierarchical structure which makes it easier to locate the related classes.


Q11. Why pointers are not used in Java?

Because pointers are unsafe and increases the complexity of 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 user, pointers are discouraged in Java.


Q12. What is JIT compiler in Java?

JIT stands for Just-In-Time complier. It's an integral part of JVM.

  • The JVM reads the .class file (bytecode) for interpretation.

  • If JIT not set, JVM load .class file at run time and transform that bytecode into binary code (machine code). Further, the machine code is used by interpreter. The interpretation of Java bytecode reduces the performance of the native application.

  • If JIT set, then it passes to JIT compiler for optimize performance by compiling that bytecode into native machine code at run time.

  • So when a methods is invoked, JVM directly calls the compiled code (native machine code) instead of interpreting it.

Advantages:

  • Requires less memory usages.

  • Code optimization is done at run time.

  • Uses different levels of optimization.

  • Reduce page faults.

Disadvantages:

  • Increases complexity of program.

  • Program with less line of code does not take benefits of JIT compilation.

  • It uses lots of cache memory.


Q13. What are access modifiers in Java?

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

  • public

  • protected

  • default (package-private/ no identifier)

  • private

this class nonsubbed

any class in same package

subclass in another package

any class

​public

V

V

V

V

​protected

V

V

V

X

default

V

V

X

X

private

V

X

X

X


Q14. Define a Java Class

Class is like an object constructor, a "blueprint" for creating objects. A class contains attributes (variables) and methods to describe the behaviors of an object.

Take a car as an example for class:

  • Attributes: weight, color, height, ..

  • Methods: drive(), brake(), ..


Q15. Define an object in Java and how is it created?

An object is a real-world entity that has a state and behavior and it is an instance of a class. An object has three characteristics:

  1. State: represent data (values) of an object.

  2. Behavior: represent behaviors (functionalities) of an object.

  3. Identity: is used internally by JVM to identify each object uniquely.

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

ClassName obj = new ClassName();


Q16. What is 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. The best benefit of having a local variable is that other methods in the class won’t be even aware of that variable.

Example:

if (x > 10) {
    String a = "One hundred";
}

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.

Example:

class Car {
    public String color;
    public int weight;
}

​Local Variable

Instance Variable

A variable that is typically used in a method or a constructor

A variable that is bounded to the object itself

Not possible to use access modifiers for local variables

Possible to use access modifiers for instance variables

Do not have default value

Can have default value

Be created when entering the method or a constructor

Be created when creating an object

Destroy when exiting the method or a constructor

Destroy when destroying the object


Q17. Differentiate between the constructors and methods in Java?

Methods

Constructors

Used to represent the behavior of an object

Used to initialize the state of an object

Can/Cannot have a return type

Do not have return type

Needs to be invoked explicitly

Is invoked implicitly

No default method is provided by the compiler

A default constructor is provided by compilers if the class has none

Method name should not be same as the class name

​Constructor name must be same as the class name


Q18. What is the final keyword in Java?

The final keyword is a non-access modifier that is used to restrict a class, variable and method.

  • final variable: when final keyword is used with a variable, it says that the value can't be changed once assigned. The most common approach is to initialize a final variable during its declaration. But if you don’t initialize it while declaring it, then we call it as a blank final variable (and then must be assigned value through constructor).

  • final method: when a method is declared final then it can’t be overridden by the inheriting class. The purpose of the final method is to declare methods of how’s definition can not be changed by a child or subclass that extends it.

  • 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.


Q19. What is the difference between break and continue statements?

break

continue

Can be used in switch and loop (for, while, do while) statements

Can be only used with loop statement

It causes the switch or loop statements to terminate the moment it is executed

I doesn't terminate the loop but cause the loop jump to the next iteration

It terminates the innermost enclosing loop or switch immediately

A continue within a loop nested with a switch will cause the next loop iteration to execute

Example break:

for (int i = 0; i < 3; i++) {
    if (i == 1) {
        break;
    }
    System.out.println(i);
}

Ouput:
0 
1

Example continue:

for (int i = 0; i < 3; i++) {
    if (i == 1) {
        continue;
    }
    System.out.println(i);
}

Ouput:
0 
1
2

Q19. 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 function exit condition 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.

Example:

while (1 < 3) {
    System.out.println(1);
}

This will run endlessly with infinite lines of "1".


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

​this()

super()

this() points to the reference of the current class

super() points to a reference of the parent class

​Used to access variables and methods of the current class

​Used to access variables and methods of the parent class from the subclass

Can be used to call default constructor of the same class

Can be used to call the default constructor of parent/base class

​Can be used for pointing the current class instance

Can be used for pointing the superclass instance


Q21. What is Java String Pool?

Java 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.

source: edureka

Q22. Differentiate between static and non-static methods in Java

​Static Method

Non-static Method

The static keyword must be used before the method name

No need to use static keyword before method name

It can called directly using class className.methodName() without creating instance

It can be called like any general method

It can't access any non-static instance variables or methods

It can access any static method and any static variable without creating an instance of the class


Q23. 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 through inheritance where subclass constructor is responsible for invoking the superclass's constructor first. There could be any number of classes in inheritance chain. Constructor chaining can be achieved by two ways:

  • Within same class: can be done using this() keyword for constructors in same class.

  • From base class: by using super() keyword to call constructor from the base class.


Q24. Difference between String, StringBuilder and StringBuffer

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

Usage

If a string is going to remain constant throughout the program, then use the String class object because a String object is immutable.

If a string can change (Ex: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough.

If a string can change and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous, so you have thread-safety.


Q25. What is class-loader in Java?

Class loaders are responsible for loading Java classes during runtime dynamically to the JVM (Java Virtual Machine).

Also, these Java classes aren't loaded into memory all at once, but when required by an application. This is where class loaders come into the picture. They are responsible for loading classes into memory.

There are 3 built-in class-loader in Java:

  • Bootstrap ClassLoader: It's mainly responsible for loading JDK internal classes. Bootstrap class loader serves as a parent of all the other ClassLoader instances.

  • Extension ClassLoader: The extension class loader is a child of the bootstrap class loader and takes care of loading the extensions of the standard core Java classes.

  • System/Application ClassLoader: The system or application class loader, on the other hand, takes care of loading all the application level classes into the JVM. It loads files found in the classpath environment variable and it's a child of Extensions classloader.


Q26. 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.



Q27. What is difference between an array and an array list?

​Array

ArrayList

Can be single-dimensional or multi-dimensional

Can only be single-dimensional

​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 index in order to add data

No need to specify the index

Arrays are not type parameterized Generics cannot be added. So type-unsafe

ArrayList are type parameterized. Generics can be added. So type-safe

Arrays can contain primitive data types as well as objects

ArrayList can contain only objects, no primitive data types are allowed. From Java 5, primitives are automatically converted in objects which is known as auto-boxing


Q28. What is 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 few of characteristics of Map interface:

  • Map doesn't contain duplicate keys.

  • Each key can map at max one value.


Q29. 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 manipulation 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 Java Collection.

Source: edureka

Following some sources, the Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes.

More info:

 

Java OOPs Questions


Q30. What is Object Oriented Programing?

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.


Q31. Four principles of OOPs in Java

The main principles of object-oriented programming are:

  • Inheritance: Inheritance is a process where one class acquires/inherits the properties of another. The idea behind this is that we can create new classes built on existing classes, i.e., when you inherit from an existing class, we can reuse methods and fields of the parent class. Inheritance represents the parent-child relationship.

  • Encapsulation: Encapsulation in Java is a mechanism of wrapping up the data and code together as a single unit. Encapsulation is achieved by declaring the variables as private and providing public setter and getter methods to modify and view the variable values.

  • Polymorphism: Polymorphism is the ability of a variable, function or object to take multiple forms. By using method overloading and method overriding, we can perform polymorphism.

  • Abstraction: Abstraction is the methodology of hiding the implementation details from the user and only providing the functionality to the users. An abstract class is a type of class that declares one or more abstract methods. An abstract method is a method that has a method definition but not implementation. Abstract methods are used when two or more subclasses do the same task in different ways and through different implementations.


Q32. Why Java is not 100% Object-Oriented?

Because it makes use of 8 primitive data types such as: int, byte, short, long, float, double, boolean and char - which are not objects.


Q33. What are wrapper classes?

They provides a way to use primitive data types as objects. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class.

  • byte -> Byte

  • short -> Short

  • int -> Integer

  • long -> Long

  • float -> Float

  • double -> Double

  • boolean -> Boolean

  • char -> Character

Sometimes you must use wrapper classes, for example when working with Collection objects, such as ArrayList, where primitive types cannot be used.


Q34. 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:

  • Compile time polymorphism

  • Runtime polymorphism

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

One of the examples in Compile time polymorphism is that when we overload a static method in java. Run time polymorphism is also called a dynamic method dispatch is a method in which a call to an overridden method is resolved at run time rather than compile time.



Q35. 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. Example:

class Car {
    void run() {
        System.out.println(“car is running”); 
    }
}

class Audi extends Car {
    @Override
    void run() {
        System.out.prinltn(“Audi is running safely with 100km”);
    }

    public static void main(String args[]) {
        Car b = new Audi();    //upcasting
        b.run();
    }
}

Q36. 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)


Q37. 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. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern. . Example:

public interface Animal {
    public void eat();
    public void sleep();
    public void run();
}

Q38. What is difference between abstract classes and interfaces?

​Abstract Classes

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

A class can only extend one abstract class

A class can implement many interfaces

Can have abstract and non-abstract methods

Can have only abstract methods

Can have final, non-final, static and non-static variables

Has only static and final variables

Can have any visibility: public, private, protected

Visibility must be public (or) none

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


Q39. 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:

  • Parent class (Super or Base class)

  • 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.



Q40. What are the different types of inheritance in Java?

Java supports four types of inheritance which are:

  • Single-level Inheritance: In single inheritance, one class inherits the properties of another. For example, there will be only one parent as well as one child class.

  • Multi-level Inheritance: When a class is derived from a class which is also derived from another class. For example, a class (child) inherits another class (parent) and that another class (parent) inherits one other class (grandparent).

  • 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.

  • Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance.



Q41. 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.

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.



Q42. 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 private method is visible to parent class only and it’s not accessible in subclass. What you can do is create another private method with the same name in the child class.

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");
    }
    
    @Override
    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();
    }
}

Output:
Static or class method from Derived
Non-static or instance method from Derived

More info:


Q43. 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.



Q44. 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.


Q45. What is an association?

Association is a relationship where all object have 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.


Q46. What is an aggregation?

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


Q47. What is composition in Java?

Composition is 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 can not belongs to two different houses if we delete the house room will automatically delete.



Q48. 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.

public interface Serializable {
}

Q49. 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.



Q50. 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.



Q51. 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.

class Worker {
    int weight;
    int height;
    String workerId;

    public Worker(int weight){
        this.weight = weight;
    }

    public Worker(int weight, int height, String workerId){
        this.weight = weight;
        this.height = height;
        this.workerId = workerId;
    }
}
 

Java JDBC Questions


Q52. 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)

Source: edureka

Q53. What are the steps to connect to a database in Java?

There are 5 steps:

  1. Registering the driver class

  2. Creating connection

  3. Creating statement

  4. Executing queries

  5. Closing connection


Q54. 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

  • ...

Classes:

  • DriverManager

  • Blob

  • Clob

  • Types

  • SQLException

  • ...


Q55. What is the role if JDBC DriverManager class?

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


Q56. 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.


Q57. 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.


Q58. What is JDBC ResultSetMetaData interface?

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


Q59. 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.


Q60. What do you mean by batch processing 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.


Q61. 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.


Q62. 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.

 

Java Exceptions and Thread Questions


Q63. 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.


Q64. 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


Q65. What are differences between Checked Exception and Unchecked Exception?

Checked Exception (Compile-time exceptions):

  • 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, ClassNotFoundException, etc.

Unchecked Exception (Runtime exceptions):

  • The classes that extend RuntimeException are known as unchecked exceptions.

  • Unchecked exceptions are not checked at compile-time.

  • Example: ArithmeticException, NullPointerException, ArrayIndexOutofBound, etc.



Q66. 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.

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.

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 always executed");
        }
    }
}

finalize:

Finalize is used to perform clean up processing just before the object is garbage collected. Finalize method performs the cleaning activities with respect to the object before its destruction.

public class FinalizeExample {    
     public static void main(String[] args)     
    {     
        FinalizeExample obj = new FinalizeExample();        
        obj = null;    

        // calling the garbage collector using gc()   
        System.gc();     
        System.out.println("End of the garbage collection");     
    }     
   // defining the finalize method   
    protected void finalize()     
    {     
        System.out.println("Called the finalize() method");     
    }     
} 
Output: 
End of garbage collection
Called the finalize() method


Q67. What are differences between throw and throws?

throw

throws

throw keyword is used to throw an exception explicitly

throws keyword is used to declare one or more exceptions, separated by commas

Checked exception cannot be propagated using throw only. Unchecked exception can be propagated using throw

For the propagation checked exception must use throws keyword followed by specific exception class name

Syntax wise throw keyword is followed by the instance variable

Syntax wise throws keyword is followed by exception class names

throw keyword is used within the method

throws keyword is used with the method signature

Only single exception is thrown by using throw

Multiple exceptions can be thrown by using throws

throw:

public class ThrowExample {
    public static void main(String[] args) {
        // Use of unchecked Exception
        try {
            // double x=3/0;
            throw new ArithmeticException();
        }
        catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }
}

Output: java.lang.ArithmeticException: by zero
    at UseOfThrow.main(UseOfThrow.java:8)

throws:

public class ThrowsExample {
    public static void main(String[] args) throws IOException, ArithmeticException 
    {
    }
}

Q68. What is Throwable?

Throwable is a super class for all types of errors and exceptions in java. This class is a member of java.lang package. Only instances of this class or it’s sub classes are thrown by the java virtual machine or by the throw statement. The only argument of catch block must be of this type or it’s sub classes. If you want to create your own customized exceptions, then your class must extend this class.

class MyException extends Throwable {
    //Customized Exception class
} 

class ThrowAndThrowsExample {
    void method() throws MyException {
        MyException e = new MyException(); 
        throw e;
    }
}

Q69. 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.

Source: edureka

Q. How to create a custom Exception?

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

  • class NewException 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



Q70. 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.

Q71. 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 (Java).

Dependence

Processes are independent.

Threads are dependent.


Q72. 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.


Q73. 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.


More info:


Q74. 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. For example in below code, we catch from specific ones (Arithmetic, ArrayIndexOutOfBounds) to general base one (Exception).

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");
        }
    }
}

Q75. What is OutOfMemoryError in Java?

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


Q76. 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.


Q77. 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.

	class Multi3 implements Runnable {  
		public void run(){  
    			System.out.println("thread is running...");  
		}  
  
		public static void main(String args[]) {  
			Multi3 m1=new Multi3();  
			// Using the constructor Thread(Runnable r)  
			Thread t1 =new Thread(m1);   
			t1.start();  
 		}  
	}  

  • By extending the Thread

	class Multi extends Thread{  
		public void run(){  
			System.out.println("thread is running...");  
		}  
		public static void main(String args[]){  
			Multi t1=new Multi();  
			t1.start();  
 		}  
	}  


Q78. 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



(More update soon)


Thank edureka for inspiring me.

75 views0 comments

Comments


bottom of page