Top 367 Core Java Interview Questions for 2021

This article will guide you to prepare to face interview questions related to Core Java. It covers all the topics like Basics of Java, OOPs concepts, String handling, multithreading, Collections, etc.

Table of Contents

1. What is Java?

Java is the simplest and the most commonly used programming language which is based on the object-oriented programming concept. It supports cross-platform, multithreading and is platform-independent, and robust. Sun Microsystems developed Java in the year 1995 and later acquired by Oracle Systems.

2. What are the features of the Java Programming language?

Java has the below features:

  • Simple: Java is easy to learn and does not require any complex programming concepts like pointers or multiple inheritance.
  • Platform-independent:ย Java is not dependent on any platform since the code we compile and execute is the same in any operating system. This means we can compile the code in one system and execute it in another.
  • Object-oriented:ย Java uses a collection of objects of a class to perform any operation and follows object-oriented methodology.
  • Secure:ย It is highly secure since it does not produce any security flaws like stack overflow, etc. This is because it does not use the concept of pointers.
  • Robust:ย Java is robust and reliable since it identifies errors at an early stage and avoids issues like garbage collection, memory allocation, exception handling, etc
  • Multithreaded:ย Supports multithreading concept which means we can execute 2 or programs simultaneously and thus utilizing CPU to the maximum.
  • High performance:ย Java uses a Just-in-time compiler and thereby providing high performance.
  • Distributed:ย Java supports distributed programming which means we can distribute java programs in more than 1 system which is connected through the internet. We can use features like EJB(Enterprise Java Bean) and RMI(Remote Method Invocation) in Java to support distributed features.
  • Dynamic:ย Java is more dynamic when we compare to other programming languages like C or C++. This is because it can carry a large amount of run time information which we can use to verify runtime object access.

3. What is the difference between C++ and Java?

Comparison MethodC++Java
Platform IndepenedenceIt is platform dependent. Should be compiled on every platformIt is platform independent. It can be compiled in one platform and executed in another
Compiler and InterpreterIt is a compiled languageIt is a compiled and interpreted language
PortabilityIt is not portableIt is portable since the bytecode output can be executed on any system
Memory managementMemory management is manualMemory management is system controlled
Multiple InheritanceSupports multiple inheritanceDoes not support multiple inheritance. But can be achieved through interface
OverloadingSupports operator overloadingDoes not support operator overloading
Virtual keywordIt uses virtual keyword to override functionIt does not use virtual keyword. By default all non-static methods are overridden or virtual
PointersUses the pointers conceptDoes not have pointers concept
Documentation commentsThere is no support for documentation commentsIt has built-in support for documentation comments(/** ... */
Thread supportC++ does not have in-built thread mechanism and uses third party librariesJava has in-built thread support using the class "Thread"
Call by value and Call by referenceSupports both Call by value and Call by ReferenceSupports only call by value
Structure and UnionSupports both structure and unionDoes not support Structures and union
Unsigned right shift >>> operatorDoes not support unsigned right shift operatorSupports unsigned right shift operator
Root hierarchyThere is no root hierarchyIt has a single root hierarchy which is java.lang.Object
Input mechanismUses Cin and Cout for I/O operationsUses System.in and System.out for I/O operations.
Goto statementSupports Goto statementDoes not support Goto statement
Data and functions scopeData and functions can reside outside the classData and functions should be present within the class
Object managementUses new and delete to manage objectsUses automatic garbage collection to manage objects
ApplicationsUsed for system programmingUsed for application programming like windows-based, web-based, enterprise and mobile applications.
TypeBoth procedural and object-oriented programming languageIt is only object-oriented programming language
ConceptWrite once compile anywhereWrite once run anywhere everywhere
Scope resolution operator (::)Supports scope resolution operatorDoes not support scope resolution operator
LibrariesSupports low-level functionalitySupports high level functionality
DestructorSupports destructorsDoes not support destructors
Runtime error handlingThe programmer is responsible for handling runtime errors and exceptionsJVM is responsible for runtime errors and exceptions

4. What is the Java Virtual Machine(JVM)?

JVM or Java Virtual Machine is a virtual machine that executes the java program. It executes the bytecode generated by the compiler while compiling the program. JVM acts like a run-time engine that executes the program by calling the main method. The output which the JVM produces after executing the bytecode is the same in all operating system. This is why Java is platform-independent.

5. What do the terminologies JDK, and JRE mean?

JDK means Java Development Kit which contains many components like JRE, compilers, various tools like JavaDoc, JavaDebugger, libraries, etc. It is mandatory to install the JDK in our systems to compile and run any java programs.

JRE means Java Runtime Environmentย which is part of the JDK that is used to execute any java program. It also includes browser plugins, applets support, and JVM.

6. What are the different types of memory areas allocated by JVM?

JVM contains 5 different memory areas as given below:

  • Class(Method) area: It stores all the class related data like variables, methods, runtime constant pool.
  • Heap: It allocates memory for objects during runtime.
  • Stack: It stores the result of the method execution like returning the value or value used for dynamic linking. Stack also stores frames and every thread has a private JVM stack.
  • Program counter register: Contains the address of the JVM instructions of the method.
  • Native method stack: It contains all native methods that are used in the application.

7. What is a JIT compiler?

JIT stands for Just-in-time. It is a compiler that is part of the JRE. It compiles all the bytecode that has similar functionality together and thereby reduces the compilation time. Hence JIT compiler supports performance optimization.

8. What is a platform?

A platform is a combination of a hardware and software environment that helps in software execution. Java has its own environment named JRE(Java Runtime Environment)

9. What is the difference between a Java platform and other platforms?

  • Java is a software-based platform while others may be hardware-software or only hardware-based.
  • Java runs on top of other hardware platforms while others can run only on hardware-based components.
  • We can run Java code on any OS while other platforms do not have this capability.
  • Java has its own environment(JRE) and JVM while other platforms do not have this functionality.

10. What does ‘Write once and Run anywhere’ mean?

Java is a platform-independent programming language where we can write Java code and compile in one platform and execute it on another platform. We can execute this java program on any operating system since the output of the compilation which is the bytecode is not platform-specific.

11. What is a class loader?

Java classloader is part of the JRE(Java Runtime Environment) that loads the class files into the JVM(Java Virtual Machine) whenever it is required by the application. A single classloader does not load all the classes. Based on the type of the class, the corresponding class loader loads the class files whenever needed.

Below are the different types of Java classloaders:

  • Bootstrap class loader: This is the first classloader which loads all the files from the location rt.jar. It is also called the primordial class loader which is the parent of all other classloaders.
  • Extension class loader: This is the child class of the bootstrap class loader which loads the extensions of the core java classes from the Extensions directory jre/lib/ext.
  • System class loader:ย It is also called as the Application class loader that loads the application type classes or class files from the CLASSPATH variable. It is the subclass of the Extension class loader.

12. Can a java file name be saved as an empty .java file?

Yes, we can save a java file without a filename by using only .java. To compile, we use the command javac .java , and to execute, we use the command java classname.

13. Are delete, null, next, main, and exit keywords in Java?

Yes, delete, null, exit, next, main, and null are the keywords in Java programming language.

14. When we do not pass any values in the String array arguments of the main method, does the value hold empty or null?

The value will be empty but not null when we do not pass any values to the String array arguments in the main method.

public static void main(String[] args)

15. What happens when we write a static public void instead of public static void for the main method?

It compiles and runs successfully since the order does not matter and both are correct.

16. What is the default value of a local variable?

The local variables do not have any default value since they are visible only within the method where it is declared. We must initialize the local variable before we use it else it will throw a compilation error.

17. What are the different types of access specifiers in Java?

Java has 4 different types ofย  access specifiers:

  • public: It is visible to any class in any package. We can declare public access type for class, variable, or method.
  • protected: It is accessible within any class of the same package or within the subclass of the class where it is declared. To access outside, we can achieve through inheritance.
  • default: The scope is within the package and does not require any keyword to specify.
  • private: It can be accessed only within the same class.

Java Access Modifiers

You can refer Java access modifier tutorial for more details.

18. What is the use of static methods and variables?

When we declare a variable or a method using the static keyword, it becomes a static method or static variable. This means it belongs to a class and not the object. In other words, we do not need to create an object to access a static method or variable. It is shared among all objects within a class. For example, all students in a school use the same school name. Hence we can declare the school name as a static variable. You can refer to Java static keyword for more details on this topic.

19. What are the advantages of using packages in Java?

Using packages in Java provides the below advantages:

  • Avoids naming conflicts of classes. This means we can use the same class names in 2 different packages.
  • Provides reusability by accessing a class from 1 package in another.
  • Easy maintenance since the classes will be organized
  • Provides access protection for protected and default classes.
  • It helps in encapsulation or data hiding.

20. What is the output of the following Java program?

public class StringExample {

  public static void main(String[] args) {
    System.out.println(90 + 10 + "Java");
    System.out.println("Java" + 15 + 15);

  }

}
100Java
Java1515

In the first case, it first adds the 2 integers and then concatenates the output with the string value. Hence it results in “100Java”.

In the second case, it concatenates the string value with the integers instead of first adding the integers. Hence it results in “Java1515”. This is because since all operators are + it follows left to right precedence for concatenation.

21. What is the output of the below Java code?

public class StringExample {

  public static void main(String[] args) {
          System.out.println(10 * 10 + "Java");
    System.out.println("Java" + 10 * 10);
    
  }

}
100Java
Java100

In the first case, the output is “100Java” since the multiplication operator precedes the addition operator. Hence it first multiplies 10 and 10 and then concatenates the product with the string.

The same logic applies to the second case as well. Since the multiplication operator precedes the addition operator, it multiplies the 2 values and then concatenates with the string. Hence the result “Java 100”.

22. What is the output of the below Java code?

public class Sample {

  public static void main(String[] args) {
    for(int i=0;5;i++)
      System.out.println("Java");
  }

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  Type mismatch: cannot convert from int to boolean

  at Sample.main(Sample.java:4)

It throws a compilation error since the second argument in for loop needs to be a boolean condition. In the above code, it is an integer value instead of a boolean expression.

23. What is object-oriented programming?

Object-oriented programming uses objects that contain methods and variables. Every class contains objects that are instances of class using which we can access methods or data. It promotes reusability and improves the code readability and thereby results in faster product development. Java follows the object-oriented programming concept.

Below are the features of object-oriented programming:

  • Contains methods with data that we can use along with the object.
  • Supports encapsulation and abstraction functionality that hides data to the users.
  • Implements inheritance and polymorphism and hence increase the code reusability.

24. What is an object?

An object represents a real-life entity which is an instance of a class. It contains both dataย andย methods(behaviors). Objects have mainly 2 characteristics ofย stateย andย behaviors. The state is nothing but an identity of the object(data) and behavior describes the function(method) of the object. We can create an object in Java using the new keyword. An object is one of the important features of OOPs.

25. What is the difference between object-oriented programming and object-based programming language?

Object-oriented programmingObject-based programming
Uses all concepts of OOPs.Does not use few OOPs concepts like inheritance, polymorphism
It does not have built-in objectsIt has built-in objects like windows object in JavaScript
Eg: Java, C, C++, etcEg: JavaScript, VBScript, etc

26. What will be the initial value of an object reference which is defined as an instance variable?

All object references will have a null value by default in Java during initialization.

27. What is a constructor?

A constructor in Java is a special method that is executed during instance creation of a class. Whenever we create an object for the class, the java compiler calls the default constructor of that class implicitly. We can use the constructor to initialize arguments for the object which we use within the class. The constructor should have the same name as its class name.

28. What are the different types of constructors in Java?

There are 3 different types of constructors in Java:

  • Default constructor: When we do not create any constructor, the Java compiler internally creates a default constructor that has an empty body. This constructor will not be visible to us.
  • No argument constructor: This constructor does not have any arguments or parameters but can contain code within the constructor.
  • Parameterized constructor: It contains arguments or parameters that are used to initialize or assign values to variables.

29. What is the use of a default constructor?

The main purpose of a default constructor is to assign default values to objects. The Java compiler internally creates a default constructor if we do not create it. This code will not be visible to us. The default value for integer value is 0 and for String is null.

Constructor in Java

30. Does a constructor return any value?

The constructor implicitly returns the current class instance. But we cannot explicitly use a return type with a constructor.

31. Is constructor inherited?

The constructor does not support inheritance and cannot be inherited.

32. Can we create a final constructor?

No, we cannot create a constructor as a final.

33. Can we overload a constructor?

Yes, we can overload a constructor based on the number of arguments or type of parameters. Below is a simple example of constructor overloading. The first constructor does not have any arguments. The second has 2 arguments and the third has only 1 argument. Based on the parameter, it calls the corresponding constructor.

public class Employee {
  int empId;
  String empName;
  String empRole;
  
  public Employee() {
    this.empId = 100;
  }
  
  public Employee(int id, String name) {
    this.empId = id;
    this.empName = name;
  }
  
  public Employee(String designation) {
    this.empRole = designation;
  }
  
  public static void main(String[] args) {
    Employee e1 = new Employee();
    Employee e2 = new Employee(102,"Rakesh");
    Employee e3 = new Employee("Java Developer");
    Employee e4 = new Employee("Tester");
    System.out.println("Default value of Empid: " + e1.empId);
    System.out.println("Employee id: " + e2.empId + " " + "Employee Name:" + e2.empName);
    System.out.println("Employee Role: " + e3.empRole + " and " + e4.empRole);
    
  }
}
Default value of Empid: 100
Employee id: 102 Employee Name:Rakesh
Employee Role: Java Developer and Tester

34. What is a copy constructor in Java?

There is no copy constructor as such in Java but we can copy values of one object to another using the constructor which is similar to a copy constructor in C++. There are different ways to copy values:

  • By using constructor
  • Using the clone() method
  • Assigning values of one object to another.

Below is an example of copy constructor where we pass the object as parameter to a constructor and there by we can copy the values from one object to another.

public class Employee {
  int empId;
  String empName;
  public Employee(int id, String name) {
    this.empId = id;
    this.empName = name;
  }
  
   //Copy constructor
  public Employee(Employee emp) {
    empId = emp.empId;
    empName = emp.empName;
  }
  
  public void displayDetails() {
    System.out.println("Employee ID:" + empId);
    System.out.println("Employee Name:" + empName);
  }
  
  public static void main(String[] args) {
    Employee e1 = new Employee(102,"Dev");
    //Create a copy of another object
    Employee e2 = new Employee(e1);
    e1.displayDetails();
    e2.displayDetails();
  }
}
Employee ID:102
Employee Name:Dev
Employee ID:102
Employee Name:Dev

35. What are the differences between a constructor and a method?

Even though we call a constructor as a special method, there are several differences between a constructor and a method.

Java ConstructorJava Method
Initializes a state of objectDescribes the behavior of the object
Does not have return typeIt has return type
It is invoked implicitlyIt is invoked explicitly
Constructor name should be same as class nameMethod name can be anything irrespective of class name

36. What is the output of the following code?

public class Sample {
  
  Sample(int a) {
    System.out.println("Value of a: " + a);
  }
  
  Sample(float a) {
    System.out.println("Value of a: " + a);
  }

  public static void main(String[] args) {
    byte x = 5;
    Sample s = new Sample(5);

  }

}
Value of a: 5

In the above code, we have 2 constructors, one with argument type int and the other with a float data type. During object creation, we pass a byte value. In this case, it invokes the first constructor of integer type as the byte type gets promoted to an integer type.

37. What is the output of the following code?

class Result {
  int a;
  String s;
}
public class Demo {

  public static void main(String[] args) {
    Result r = new Result();
    System.out.println(r.a);
    System.out.println(r.s);

  }

}
0
null

We have 2 variables of data type integer and String. Since there is no constructor, the JVM internally calls the default constructor and initializes these variables with a default value which is 0 and null respectively.

38. What is the output of the below code?

class Result {
  int a;
  String s;
  
  Result(int a, String s) {
    this.a = a;
    this.s = s;
  }
}
public class Demo {

  public static void main(String[] args) {
    Result r = new Result();
    System.out.println(r.a);
    System.out.println(r.s);

  }

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  The constructor Result() is undefined

  at Demo.main(Demo.java:13)

In this scenario, we get a compilation error. This is because when we define any constructor, the JVM does not internally call the default constructor. Hence if we define a constructor, we need to create the object using that constructor, else it will result in a compilation error.

39. What is a static variable?

When we declare a variable with a static keyword, we call it a static variable. These are also called class variables which means it is not specific to any object and does not require any object to access the static variables. It is mainly used to manage memory efficiently since it allocates memory only once(class area) for static variables which happen when the class loads. We can use a static variable when we want the same value to be shared among different objects or instances of a class. Eg: school name, college name, company name, etc

40. What is a static method?

When we declare a method using the static keyword, it becomes a static method. We can directly access the static methods and their variables without using the object. These methods belong to a class. We cannot call a non-static method or instance variable from a static method since it will throw a compilation error. Static methods can be used only to initialize static variables and not instance(object) variables.

41. What are the restrictions of using a static method?

  • We cannot access non-static members within a static method
  • Cannot call any non-static methods from a static method
  • Cannot useย superย keyword within a static method

42. Why do we declare the main method as static?

We declare the main method as static since it does not require any object and loads the methods during class loading. Also, the main method is the entry point for any execution in Java

43. Can we override static methods?

No, we cannot override static methods and it will result in compilation error.

44. What is a static block?

When a block contains the name as java keywordย static, we call it a static block. We use static block when we want to initialize any static members while loading the class. It first executes this static block before it calls the main method.

public class StaticBlockExample {
  static int i;
  static {
    System.out.println("Inside the static block");
    i = 10;
  }
  public static void main(String[] args) {
    System.out.println("Inside the main method");
    System.out.println("Value of i: " + i);
  }
}
Inside the static block
Inside the main method
Value of i: 10

45. Is it possible to execute a java program without the main method?

We can execute a java program without the main method by using the static block. A static block is executed before the main method and when the class loads. But if we do not have a static block, then the compiler will look for the main() method and throws compilation error if not found.

Note: This is not possible for the Java 7 version.

46. What happens when we define the main method without a static keyword?

The java code compiles successfully but however, it will throw “NoSuchMethodError”.

47. What is the difference between static(class) method and instance method?

Static MethodInstance method
Method declaration contains the static keywordMethod declaration does not have static keyword
Does not require object to access static methodObject is required to access instance method
We cannot access non-static methods or variables within a static methodWe can access both static and non static members within an instance method
Static method belongs to the class. Hence it is also called as class methodInstance methods belong to object.

48. Can we create a static constructor?

We cannot make a constructor static since we need objects to invoke a constructor. Static does not require any objects hence it will throw compilation error as “Illegal access modifier”.

49. Can we make abstract methods as static?

No, we cannot make abstract methods as static because we cannot override static methods. We need to override abstract methods to provide its implementation or functionality in the class that extends the abstract class.

50. Can we declare static methods and static variables inside an abstract class?

We can declare static methods and static variables inside an abstract class because we do not need any object to access them. We can directly access them from the subclass using the abstract class name.

51. What is this keyword in Java?

In Java, this keyword refers to the current instance or variable in a method or constructor. It is called as a reference variable. The main use it to differentiate between the instance variable and the local variable. This occurs mainly when we use the same variable name for the parameter in a constructor and the same name for the instance variable.

52. What are the uses of this keyword in Java?

The main objective of using the java thiskeyword is to differentiate between the instance variable and local variable. Below are other different usages:

  • To refer to the current class instance variable
  • Invoke current class method implicitly
  • To invoke the current class constructor
  • Pass as an argument in the method call
  • Pass as an argument in the constructor call
  • Return current class instance from method

53. Is it possible to assign any reference to this variable?

We cannot assign any reference value to the java this keyword because by default it refers to the current class instance. If we try to assign any value, it will throw a compilation error.

public class SampleTest {

  public SampleTest()
  {
    this = 5;
  }
  public static void main(String[] args) {
    SampleTest s = new SampleTest();

  }

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  The left-hand side of an assignment must be a variable

54. Can we use this keyword to refer to static variables?

We can use the java this keyword to refer to the static variables and it will not throw any error. However, it is not the best practice to do so since static variables can be accessed directly and do not require any object or reference variable.

55. How to achieve constructor chaining using this keyword?

We use the java this keyword to invoke a constructor mainly to implement constructor chaining which is calling a constructor within another constructor. This helps in code reusability. Based on the constructor type, we can pass the parameters. Calling a constructor using the javaย thisย keyword should always be the first statement, else it will throw compilation error.

We can call a constructor using 2 different ways:

this() โ€“ default constructor

this(parameter) โ€“ parameterized constructor

You can refer here for more details.

56. What is the advantage of passing this to a method instead of the current class object?

This also refers to the current class instance which is similar to the current object. But it has a few differences as below:

  • This is a final variable and hence we cannot change any values but this is not the case with the current object.
  • It can also be used in a synchronized block

57. What is inheritance?

Inheritance is an important feature of OOPs. It is a feature that helps to reuse the methods and variables of one class in another class. In other words, it allows a new class to inherit the properties and functions of an existing class without rewriting the code. It implements the parent-childย relationship. This means that the child class can directly reuse the variables and functions of the parent class along with its own methods and variables.

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

Below are the different types of inheritance in Java:

  • Single inheritance
  • Multilevel inheritance
  • Hybrid inheritance
  • Hierarchical inheritance
  • Multiple inheritance – Not supported using Java class but can be achieved through an interface.

59. Why do we use inheritance in Java?

  • Ability to reuse the existing code of a class
  • Supports method overriding
  • Allows calling methods of superclass within methods of a subclass using the super keyword.
  • Does not allow to inherit the final class or override final methods.
  • Supports multiple inheritance using interfaces

60. Which class is the superclass for all the classes?

The Object class is the superclass for all the classes.

61. Why Java does not support multiple inheritance?

Java does not support multiple inheritance due to the complexity and ambiguity it creates during the execution. Multiple inheritance means one class can extend more than 1 class. In other words, a child class can have more than 1 parent class. We can understand this if we compare this to real life. It is impossible for a child to have more than 1 mother. In the same way, inheritance in java cannot have 1 child class having more than 1 parent.

For example, if this was allowed in java, consider the below example. When we call obj.show(), it wonโ€™t know which class method to call since it is present in both the classes.

class classA {
  public void show() {
    System.out.println("Class A");
  }
}
class classB {
  public void show() {
    System.out.println("Class B");
  }
}
public class MultipleInheritance extends classA,classB { //Suppose if allowed
  public static void main(String[] args) {
    MultipleInheritance obj = new MultipleInheritance();
    obj.show();
  }
}
Compile-time error

We can implement multiple inheritance using an interface in Java.

62. What is aggregation?

Aggregation in Java allows us to provide a reference for one class within another class. In other words, it supports aย one-wayย relationship and implements aย HAS-Aย relation.

When two classes have a HAS-A relation, we say it implements aggregation. One best example we can think of is โ€œEmployee has a Carโ€œ. We say this is unidirectional since a car cannot have an employee and only an employee can have a car.

In the below example you can see that the Employee class has a reference to the Car class. Hence there is aggregation between the Employee and Car class.

class Car {
  String carname;
  String color;
  String regno;
  
  Car(String carname, String color, String regno) {
    this.carname = carname;
    this.color = color;
    this.regno = regno;
  }
  
}
public class Employee {
  
  String empname;
  int empid;
  Car car;
  
  Employee(String empname, int empid, Car car) {
    this.empname = empname;
    this.empid = empid;
    this.car = car;
  }
  public static void main(String[] args) {
    Car car = new Car("Dezire","blue","KA 02 B 5544");
    Employee e = new Employee("Raj",456234,car);
    System.out.println("----------Employee Details:------------");
    System.out.println("Employee Name: " + e.empname);
    System.out.println("Employee ID: " + e.empid);
    System.out.println("----------Employee's car details-------");
    System.out.println("Car Name: " + e.car.carname);
    System.out.println("Car color: " + e.car.color);
    System.out.println("Car Reg No: " + e.car.regno);
  }
}
----------Employee Details:------------
Employee Name: Raj
Employee ID: 456234
----------Employee's car details-------
Car Name: Dezire
Car color: blue
Car Reg No: KA 02 B 5544

63. What is composition?

Composition denotes aย belong-to or part-ofย type of association. In other words, we can say, one object contains or is composed of another object.ย  This implements a strong type of associationย which means that if the inner object cannot exist if the main outer object is destroyed.

For example, we cannot have a school without students. This means a school cannot exist without students in it. Hence it establishes a composition between school and students.

64. What is the difference between aggregation and composition?

CompositionAggregation
Strong type of associationWeak type of association
Implements part-of or belongs-to relationshipImplements has-a relationship
Both classes are dependent on each other.
Child class cannot exist without parent class
Child class can exist independently even without parent class

65. Why Java does not support the use of pointers?

Pointers refer to the memory address location. If we use them in Java, it makes is unsafe and also increases the complexity and does not allow us to implement abstraction. This is not required for general-purpose OOP since memory management is taken care of by garbage collection.

66. What is a super keyword in Java?

Java super keyword is aย reference variable that we use in inheritance to refer to the immediate parent class object from the child class. We can use the super keyword to access the parent class variable, parent class method, and parent class constructor. Whenever we create a subclass instance, the compiler internally calls the parent class constructor using the super keyword even if we do not call it explicitly.

67. How to implement constructor chaining using the Java super keyword?

We can implement constructor chaining by calling the parent class constructor from the subclass which has different arguments using the super keyword. It is always important to note that the super statement should be the first statement in the child constructor. When we make an explicit constructor call, then the compiler does not make another implicit call to the parent class.

In the below example, we make an explicit super call to the parent class constructor Shapes(String name) that has arguments from the child class constructor Square().

class Shapes {
  Shapes() {
    System.out.println("This is a shape");
  }
  
  Shapes(String name) {
    System.out.println("Shape name is: " + name);
  }
}
public class Square extends Shapes {
  
  Square() {
    super("Square");
    System.out.println("Square constructor");
  }
  public static void main(String[] args) {
    Square s = new Square();
  }
}
Shape name is: Square
Square constructor

68. What are the uses of the Java super keyword?

  • Access the parent class variable
  • To invoke the parent class method
  • To invoke the parent class constructors with and without argument.

69. What are the differences between this and super keyword?

this keywordsuper keyword
It refers to the current class contextIt refers to the base class or parent class context
Mainly used to differentiate between the local and instance variables within a constructorIt is used to initialize the base class variables within the derived class constructor

70. What is the output of the below java program?

class College {
  
  College() {
    System.out.println("College Name is BITS Pilani");
  }
}

public class Department extends College {
  public String dept;
  public Department(String deptname) {
    dept = deptname;
  }
  public static void main(String[] args) {
    Department d = new Department("Computer Science");
    System.out.println("Department Name:" + d.dept);
  }
}
College Name is BITS Pilani
Department Name:Computer Science

When an instance of the subclass is created, it first invokes the parent class constructor using the super keyword implicitly and then executes the child class constructor.

71. Can we use both this and super keyword in a constructor?

No, we cannot use both the statements together in the same constructor since this and super needs to be the first statement within a constructor. If we try to use both, we will get a compilation error.

72. What is object cloning?

Object cloning is the process of creating an exact copy of the object. It uses the clone method of the Object class. The class needs to implement the Cloneable interface to use the clone method else it will throw CloneNotSupportedException. The clone method saves more time than creating an object using the new keyword if we want an exact copy of the created object.

73. What is method overloading?

When there are several methods in the same class with the same name, we call it method overloading. It is one of the static polymorphism technique. It identifies which method to call during compile time based on the parameters passed. We can implement method overloading in 2 different ways:

  • By passing a different number of parameters
  • By passing different types of parameters.

74. Why is method overloading not possible by changing the return type?

Java does not support method overloading by only changing the return type because it will create ambiguity and the compiler will not know which method to call.

75. Can we overload methods by just making them static?

No, we cannot overload methods by just making them static. This is because the compiler will again throw an error stating that the method is already defined.

public class College {
  
  public void getCollegeName() {
    System.out.println("CollegeName is BITS Pilani");
  }
  
//Throws compilation error as duplicate method name
  public static void getCollegeName() {
    System.out.println("CollegeName is BITS Pilani");
  }

}

76. Can we overload the main method in Java?

Yes, we can overload the main method in Java. But the Java compiler calls the public static void main method only during class loading. To execute the overloaded main method, we need to invoke from the actual main method.

77. What is method overloading with type promotion?

Method overloading with type promotion means, when no matching parameter type method is found, it implicitly promotes the data type to the next level and calls that corresponding method. For example, if we call a method with a short parameter data type and if there is no matching method with a short type but if int is present, then it calls the method with int parameter datatype.

Core Java Interview Questions

public class Sample {

  public void add(int a, int b) {
    int sum = a + b;
    System.out.println("Integer addition");
    System.out.println("Sum: " + sum);
  }
  
  public void add(float a, float b) {
    float sum = a + b;
    System.out.println("Float addition");
    System.out.println("Sum: " + sum);
  }
    
  public static void main(String[] args) {
    Sample s = new Sample();
    short x,y;
    s.add(4, 5);

  }

}
Integer addition
Sum: 9

78. What is the output of the below java program?

public class Sample {

  public void add(int a, float b) {
    System.out.println("Integer addition");
  }
  
  public void add(float a, int b) {
    System.out.println("Float addition");
  }
    
  public static void main(String[] args) {
    Sample s = new Sample();
    s.add(4, 5);
  }

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  The method add(int, float) is ambiguous for the type Sample

This code will throw a compilation error since there is an ambiguity of which method has to be called. Since we are just passing 2 integer values, the compiler does not know whether to call the first or the second add method.

79. What is method overriding?

When the subclass has the same method of the base class along with the signature, we call it a method overriding which means that the subclass has overridden the base class method. Based on the type of object we create, it calls the method of that corresponding class. This means, if we create an object of the superclass and refer it using the subclass, then it calls the method of the subclass. Since it computes this during runtime, we call it as runtime polymorphism in java.

80. Can we override a static method?

No, we cannot override a static method as it will throw a compilation error.

81. Why Java does not allow to override static method?

We cannot override a static method since overriding happens during runtime and static methods are bonded during the compile time. Also static methods belong to the class memory area since it is part of the class whereas normal methods are part of the object which belongs to the heap memory area.

82. Can we override an overloaded method?

Yes, Java allows overriding an overloaded method.

83. What is the difference between method overloading and method overriding?

Method overloadingMethod overriding
This implements static polymorphismThis implements dynamic polymorphism
This happens during compile timeThis happens during runtime
Same methods are present in the same classSame methods are present in different classes

84. Can we override private methods in Java?

No, we cannot override private methods since the scope of private methods is restricted within the same class and we cannot access it from other classes.

85. Can we change the scope of the overridden methods in the subclass?

Yes, we can change the scope of the overridden methods in the subclass provided that we do not decrease its accessibility.

  • Private can be changed to protected, default, or public.
  • We can change protected to default or public.
  • A default modifier can be changed to public.
  • The public modifier can be declared only as public.

86. Can we modify the throws clause of the superclass method by overriding it in the subclass?

We can modify the throws clause of the superclass method by overriding in the subclass but need to follow the below rules for exception handling:

  • If the method in the superclass does not declare any exception, then the base class overridden method can declare only unchecked exceptions.
  • If the method in the superclass declares an exception, then the base class can declare the same or subclass exception but not the parent class exception.

87. What is the output of the below Java program?

class parent {
  
  public void print(int a) {
    System.out.println("Prints base class integer number");
  }
  
  public void print(double a) {
    System.out.println("Prints base class double number");
  }
}
public class child extends parent{
  
  public void print(double a) {
    System.out.println("Prints child class double number");
  }

  public static void main(String[] args) {
    child c = new child();
    c.print(5);
    c.print(5.5);

  }

}
Prints base class integer number
Prints child class double number

The first statement calls the print method in the parent class since we are passing an integer value. The second calls the base class overridden print method since we are passing a double value and initialized a derived class object.

88. Can we have virtual functions in Java?

Yes, by default are functions are virtual in Java.

89. What is a covariant return type?

When we override a method in the subclass by declaring the return type as a subclass type, we call it a covariant return type. Java supports covariant return type only from JDK 5.0 and above.

class Base {
  Base display() {
    return this;
  }
}
public class Derived extends Base{

  Derived display() {
    return this;
  }
  
  public void show() {
    System.out.println("Covariant return type");
  }
  public static void main(String[] args) {

    new Derived().display().show();

  }

}
Covariant return type

90. What is the output of the below code?

class Base {
  public void display() {
    System.out.println("Base method");
  }
}
public class Derived extends Base {

  public void display() {
    System.out.println("Derived method");
  }
  
  public static void main(String[] args) {

    Base b = new Derived();
    b.display();

  }

}
Derived method

The output prints the derived class method since we are creating an object of the derived class.

91. What is the final keyword in Java?

Java final keyword is a non-access modifier that provides few restrictions or limitations to the user. In other words, when we use the keywordย final,ย we cannot reassign or reinitialize them. This means we cannot change the values once it is initialized. We can use the Java final keyword for variables, methods, class, and parameter variables.

public class Circle {
  final double PI= 3.14;
  
  public void area(int r) {
    PI= 2.14;
    double area = PI*r*r;
    System.out.println("Area of circle: " + area);
  }
  public static void main(String[] args) {
    Circle c = new Circle();
    c.area(4);
  }
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  The final field Circle.PI cannot be assigned

92. What is the final method?

When we use the java final keyword before the method, we call it a final method. In this case, we cannot override the final method. We can call the final method directly from a subclass, but we cannot override it since it will result in a compilation error.

class Vehicle {
  final void speed() {
    System.out.println("Default speed");
  }
}
public class Car extends Vehicle{
  void speed() {
    System.out.println("Car speed");
  }
  public static void main(String[] args) {
  }
}
Error: LinkageError occurred while loading main class Car
  java.lang.VerifyError: class Car overrides final method Vehicle.speed()V

93. What is a final class?

When we use the final keyword while creating a class in java, we call it a final class. We cannot extend a final class and does not support inheritance. Most of the java core libraries have a final class like String class for example.

final class Vehicle {
  public void speed() {
    System.out.println("Default speed");
  }
}
public class Car extends Vehicle{
  public static void main(String[] args) {
    
  }
}
The type Car cannot subclass the final class Vehicle

94. What is a final blank variable?

When we do not assign any value to the final variable during declaration, we call it a blank final variable in java. If we do not initialize the final variable during declaration, then we can do the same only in a constructor, else we will get a compilation error. We cannot initialize the final variable inside any other method. The main use of a final blank variable is when we want to have different values for each instance creation.

95. Can we initialize a final blank variable?

Yes, we can initialize a final blank variable only in a constructor if we do not initialize it during the variable declaration. If it is a static final variable, we can initialize the same only in a static block.

public class Circle {
  final double PI;
  
       //Initialize final variable in the constructor
  Circle() {
    PI= 3.14;
  }
  
  public void area(int r) {
    double area = PI*r*r;
    System.out.println("Area of circle: " + area);
  }
  public static void main(String[] args) {
    Circle c = new Circle();
    c.area(4);
  }
}
Area of circle: 50.24

96. Can you declare the Java main method as final?

Yes, we can declare the main method as final since we do not need to override the main method in Java.

97. What is the output of the below Java code?

public class Test {

  public static void main(String[] args) {
    final String value;
    value = "Hello";
    System.out.println(value);

  }

}
Hello

It prints the output as “Hello” since we are initializing it only once.

98. What is the output of the following code?

class Sample {
  public final void display() {
    System.out.println("Sample display method");
  }
}
public class Test extends Sample{
  
  public final void display() {
    System.out.println("Test display method");
  }

  public static void main(String[] args) {
    Sample s = new Sample();
    s.display();

  }

}
Error: LinkageError occurred while loading main class Test
  java.lang.VerifyError: class Test overrides final method Sample.display()V

It throws a compilation error since we cannot override a final method on Java.

99. Can we declare a constructor or interface as final?

No, we cannot declare a constructor or interface as final. It will throw a compilation error if we try to do so.

100. What is the difference between a final method and an abstract method?

The main difference is that the final method cannot be overridden while the abstract method has to be overridden in the subclass that implements the abstract class.

101. What is the difference between compile-time and runtime polymorphism?

Compile-time polymorphismRuntime polymorphism
The call happens during compile timeThe call happens during runtime.
It is also called as static polymorphism or early bindingIt is also called as dynamic polymorphism or late binding
Method overloading is an example of compile-time polymorphismMethod overriding is an example of runtime polymorphism
Faster executionSlower execution
Provides less flexiblityProvides more flexibility
Methods with same name is present in the same classMethods with same name is present in the derived class

102. What is runtime polymorphism?

When polymorphism resolves during runtime, we call itย dynamicย orย runtimeย polymorphism. In this type of polymorphism in java, it uses the reference variable of the superclass to call the overridden method. This means, based on the object that is referred by the reference variable, it calls the overridden method of that corresponding class. We can use theย method overridingย concept to implement Dynamic polymorphism.

103. Is it possible to achieve runtime polymorphism with data members?

No, we cannot achieve runtime polymorphism by overriding the data members. Only methods can be overridden and not the variables.

class Bank {
  public double interestRate = 7.5;
}
class SBI extends Bank {
  public double interestRate = 6.4;
}
public class BankDemo {
  public static void main(String[] args) {
    Bank b = new SBI();
    System.out.println(b.interestRate);
    SBI s = new SBI();
    System.out.println(s.interestRate);
  }
}
7.5
6.4

When we have the same variable name in the superclass and the subclass, based on the reference variables, it calls the corresponding variable. In this example, b is an instance of the superclass, hence first it prints the superclass variable value. Next, s is an instance of a subclass which prints the value of the subclass variable.

104. What is the difference between static and dynamic binding?

Static BindingDynamic Binding
Also called early binding or compile-time bindingAlso called late binding or runtime binding
Method overloading is static bindingMethod overriding is dynamic binding
Uses type of class to resolve the bindingUses type of object to resolve binding
Faster executionSlow execution

105. What is the output of the following program?

class Vehicle {
  public void speed() {
    System.out.println("Default speed");
  }
}
class Bike extends Vehicle {
  public void speed() {
    System.out.println("Bike speed");
  }
}
class Car extends Vehicle {
  public void speed() {
    System.out.println("Car speed");
  }
}
public class VehicleType {
  public static void main(String[] args) {
    //Create an instance of Vehicle
    Vehicle v = new Vehicle();
    v.speed();
    
    //Create an instance of Bike
    Vehicle b = new Bike();
    b.speed();
    
    //Create an instance of Car
    Vehicle c = new Car();
    c.speed();
  }
}
Default speed
Bike speed
Car speed

When we create an instance of the subclass, then it calls the subclass overridden method during runtime.

106. What is Java instanceOf operator?

Java instanceOf operator is a comparison operator that checks if the object is an instance of some type of class. The return value is either true or false. If there is no value, then it returns false.

public class SpecialOperator {

  public static void main(String[] args) {
    String value = "";
    Boolean b;
    b = (value instanceof String);
    System.out.println(b);
  }

}
true

107. What is abstraction?

Abstraction in Java, which is one of theย OOPs concepts, is the process of showing only the required information to the user by hiding other details. It displays what the method does rather than how it is done. For example, consider a mobile phone, we just know that pressing on the call button, will dial the required number. But we actually donโ€™t know the actual implementation of how a call works. This is because the internal mechanism is not visible to us. We can achieve abstraction using abstract class or an interface.

108. What is the difference between abstraction and encapsulation?

The main difference is abstraction hides the implementation details while encapsulation binds the data and methods together

109. What is an abstract class?

When we declare a class with anย abstractย keyword, we call it an abstract class.ย abstractย is a non-access modifier keyword that we can use along with a class and method. An abstract class is a special class that is a superclass that contains unimplemented methods. Hence the subclass that inherits the parent abstract class should implement all the abstract methods.

110. Can there be an abstract method without an abstract class?

No, if there is an abstract method, then we need to declare that class as an abstract class.

111. What is the output of the following code?

abstract class Area {
  abstract void square(int x);
}
public class Test {

  int area;
  
  public static void main(String[] args) {
    new Area() {
      void square(int x) {
        int area = x * x;
        System.out.println("Area is: " + area);
      }
    }.square(5);

  }

}
Area is: 25

The above code prints the output as 25. The Test class implements the abstract method square.

112. Can we declare a method as both abstract and final?

No, we cannot declare a method as both abstract and final since abstract methods need to be overridden while final methods cannot be overridden.

113. Can we instantiate an abstract class?

No, we cannot instantiate an abstract class which means we cannot create an instance or object for an abstract class.

114. What is an interface?

Java interface is a keyword that allows us to achieve full abstraction. An interface tells us what it does rather than how it does. This means, an interface contains only function declaration and does not contain function implementation. The class which implements the interface contains the function definition. We cannot create an instance or have instance variables in an interface. All variables in an interface are public, static, and final by default and must be initialized during declaration. All methods are public and abstract by default.

115. Can we declare an interface method as static?

No, interface methods cannot be declared as static since it is abstract by default.

116. Can we declare an interface as final?

No, we cannot declare an interface as final since it needs to be implemented by another class. The final keyword does not support this.

117. What is a marker interface?

When we define an empty interface, we call it a tag or marker interface. This type of java interface does not have any properties or methods. Few existing tag interfaces in java are EventListener, Serializable, Remote(java.rmi.Remote). The main use of tag interface is that when the class implements such an interface, it can use the membership of that interface. This means the JVM (Java Virtual Machine) performs a special operation to support that interface. For example, serialization or deserialization process.

package java.uti;
public interface EventListener 
{ }

118. What are the differences between an abstract class and an interface?

Abstract classInterface
Abstract class can have both abstract and non-abstract methodsInterface can have only abstract methods. From Java 8, supports default methods
Does not support multiple inheritanceSupports multiple inheritance
Uses abstract keywordUses interface keyword
Uses extends keyword to inherit the abstract classUses implements keyword to implement the interface
It can extend another Java class and also implement interfaceIt can only extend another interface
Members can have access modifiers like private, protected, etcMembers can have only public
It can have static, non-static, final or non-final variables.It can have only static and final variables

119. Can we declare the variables in an interface as private or protected?

No, we cannot declare the variables in an interface as private or protected since they are public by default.

120. When can an object reference be cast to an interface reference?

When an object implements the referenced interface, we can cast an object reference to interface reference.

121. How to create a read-only class in Java?

We can create a read-only class in Java by making all the variables as private. The class will contain only getter methods that are used to read the private variable values. Since there are no setter methods, we cannot modify the values.

de class Account {
  private int accountnumber;
  
  public int getAccountNumber() {
    return accountnumber;
  }
}

122. How to create a write-only class in Java?

We can create a write-only class by declaring all variables as private and having only setter methods to assign values to these variables. We cannot retrieve the values since we do not have getter methods.

class Account {
  private int accountnumber;
  
  public void setAccountNumber(int accno) {
    this.accountnumber = accno;
  }

}

123. What are the advantages of Encapsulation in Java?

  • Provides security by not allowing outside class to modify the private fields.
  • We can have either read-only or write-only methods also hence providing restrictions to other classes to access them. This means, if a class has only aย getย method, we can only read the variables. Similarly, we can have only aย setย method to only set the variable.
  • Provides flexibility and reusability through the getter and setter methods.
  • Implementation details are not visible to other classes.
  • Easy for unit testing

124. What is a package in Java?

Packages in Java groups multiple classes, interfaces, or packages, etc together in a single place. We can consider a package similar to a folder. A folder can contain multiple files. Similarly, in Java, a package contains a group of classes. The main purpose is to avoid class name conflicts. There are two types of packages in Java: built-in and user-defined.

125. What are the advantages of using a package in Java?

  • Avoids naming conflicts of classes. This means we can use the same class names in 2 different packages.
  • Provides reusability by accessing a class from 1 package in another.
  • Easy maintenance since the classes will be organized
  • Provides access protection for protected and default classes. Please refer toย access modifiersย for more details.
  • It helps in encapsulation or data hiding.

126. How to create a package in Java?

If we are using IDE like Eclipse, we can create a package by following the below steps:

  1. Create a new Java project โ€“ Eg: โ€œPackageDemoโ€.
  2. Right-click on the project -> New -> Package
  3. Enter the package name. Eg: com.tutorial.packagedemo
  4. Click on Finish

If we are using notepad, then follow the below steps:

  1. Define a package package_name. Create a class class_name and save it as class_name.java
  2. Compile the code using command prompt: javac -d . class_name.java
  3. Run the code using command prompt: java package_name.class_name

127. How can we access a class in a package from another class?

  • By using the fully qualified name – Use a fully qualified name or import the package that contains the class.
  • By using the relative path – Specify the path that is related to the class in the package.

128. Is it mandatory to import java.lang package?

No, it is not mandatory to import java.lang package as it is imported by the JVM by default.

129. Can we import the same package/class twice and how does the JVM load it?

Yes, we can import the same package/class multiple times. However, the JVM will load it only once internally irrespective of how many ever times we import it.

130. What is a static import?

Java 5 and above supportsย static import.ย  This means when using the static import, we don’t need to specify the class name while accessing its fields or methods.

import static java.lang.System.*;
public class StaticImportDemo {
  public static void main(String[] args) {
    out.println("Exmaple of static import");
    
  }
}

131. What is exception handling in Java?

Exception handling in Java is one of the most important concepts in Java programming. Whenever we develop software we must ensure that we handle the java exceptions correctly. In Java, an exception is a condition that stops or terminates the execution process when it encounters an unexpected condition. This interrupts the normal execution flow and throws a system-generated message which the user might not understand. We can handle this situation in java by providing a meaningful message to the user when an exception occurs without interrupting the execution flow.

132. What are the different types of exceptions that can occur in Java?

There are two types of exceptions that can occur in Java:

  • Checked exceptions: We can also name them asย compilationย exceptions which means the compiler handles them during the code compilation. In other words, it checks the exception during compilation and warns the developer that there are chances for an exception to occur. In this case, the developer has to handle it in the code.
  • Unchecked exceptions: We can also call themย runtime exceptions sinceย it occurs during the execution of the program. It is very important for the developer to handle these to exit safely from the code execution when it encounters an unexpected condition. Example: ArrayIndexOutOfBoundException, NullPointerException, etc.

133. What is the hierarchy of Java Exception classes?

The root class of the Java Exceptions is the java.lang.Throwable class which contains two subclasses: Error and Exception.

Exception handing in Java

134. What is the difference between checked and unchecked exceptions?

The main difference is that checked exceptions are handled during compile time while the unchecked exceptions are handled during runtime.

135. What is the base class for Exception and Error?

The base class for Exception and Error is the Throwable class that belongs to the java.lang package.

136. Is it necessary that every try block must be followed by a catch block?

No, it is not necessary. A try block must be followed by either a catch block or a finally block. The method should declare the type of exceptions that can occur using the throws keyword.

public class Test {

  public static void main(String[] args) {
    try {
      int a = 5;
      System.out.println(a/0);
    }
    finally {
      System.out.println("Finally block");
    }	

  }

}
Finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
  at Test.main(Test.java:6)

137. What is the output of the below code?

public class UncheckedException {
  
  int a = 10;
  int b = 0;
  public void divide() {
    try {
      int result = a/b;
      System.out.println("Result: " + result);
    }
    catch(Exception e) {
      System.out.println(e);
    }
    catch(ArithmeticException e) {
      System.out.println("Division by 0 is not allowed");
    }
    finally {
      System.out.println("Divide method executed");	
    }
    
  }

  public static void main(String[] args) {
    UncheckedException uce = new UncheckedException();
    uce.divide();

  }

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception

The above code throws compilation error since we are first catching the exception using the Exception class. In this case, it will never reach the ArithmeticException catch block since Exception is the parent class for all the types of exceptions. We should use Exception class catch block always as the last block.

138. What is finally block?

The finally block always follows a try-catch block. It executes the important code irrespective of whether an exception occurs or not. It is mainly used to clean up the code like closing a file, releasing object, etc. Finally block is executed towards the end after the try-catch is executed. If any system exit or abort occurs before, then the finally block will not get executed.

139. Can we use finally block without a catch block?

Yes, we can use finally block without a catch block but it must follow the try block instead.

140. In which situation the finally block will never be executed?

There are 2 situations in which the finally block will never get executed:

  • When system exits occurs using the System.exit()
  • When fatal error occurs that makes the process to abort.

141. What is the difference between throw and throws keyword in Java?

Java throwJava throws
Used inside the methodUsed in method declaration
It is used to throw a new exception inside the methodIt is used to declare an exception that might occur inside the method
We can throw only single exception at a timeWe can handle multiple exceptions at a time in the method declaration
It can be used only with unchecked exception.It can be used for both checked and unchecked exceptions
It does not require try-catch to handle the exceptionIt is the responsibility of the called method to handle the exception using the try-catch

142. What is the output of the below code?

public class Test {

  public static void main(String[] args) {
    try {
      throw 10;
    }
    catch(Exception e) {
      System.out.println(e);
    }
    finally {
      System.out.println("Finally block");
    }	

  }

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  No exception of type int can be thrown; an exception type must be a subclass of Throwable

  at Test.main(Test.java:5)

It will throw a compilation error since we cannot throw an integer value. The exception thrown must be a subclass of Throwable.

143. What is the output of th below code?

import java.util.LinkedList;

class OwnException extends Exception {
  String message;
  OwnException(String s) {
    message = s;
  }
  
  public String toString() {
    return ("Exception: " + message);
  }
}
public class CustomException {

  public static void main(String[] args) {
    try {
      throw new OwnException("My own custom exception");
    }
    catch(Exception e) {
      System.out.println(e);
    }

  }

}
Exception: My own

custom exception

It prints the exception message that we pass using the throw keyword. Here we are creating a custom exception and throwing the exception in the try block.

144. Can we rethrow an exception?

Yes, we can rethrow an exception.

145. Can an overriding method is subclass declare an exception even if the parent class does not throw an exception?

Yes, the overriding method in subclass can throw an exception provided it is an unchecked exception. In this case, it does not allow to throw checked excpetion.

146. What is exception propagation?

Exception propagation is the procedure where the exception handling moves from the top to the bottom of the stack until it finds the right handler to catch.

public class PropagationDemo {

  void display() {
    int a = 10/0;
  }
  void test() {
    display();
  }
  void show() {
    try {
      test();
    }
    catch(Exception e) {
      System.out.println("Exception handled in show method");
    }
  }
  public static void main(String[] args) {
    PropagationDemo p = new PropagationDemo();
    p.show();

  }

}
Exception handled in show method

In the above example, an exception occurs in the display() method. Since it is not handled in this method, it is propagated to the test() method from where it was called. It is not handled here as well, it further checks in the next method from where the test was called. Finally, it handles in the show method.

147. What is the output of the below code?

public class Test {

  void m() {
    try {
      System.out.println("Inside m method");
      n();
    }
    catch(Exception e) {
      System.out.println("Exception caught in m method");
    }
  }
  void n() throws Exception{
    try {
      System.out.println("Inside n method");
      p();
    }
    catch(Exception e) {
      throw new Exception();
    }
    
  }
  void p() throws Exception {
    try {
      System.out.println("Inside p method");
      throw new Exception();
    }
    finally {
      System.out.println("Inside finally block");
    }
    
  }
  public static void main(String[] args) {
    Test t = new Test();
    t.m();
  }

}
Inside m method
Inside n method
Inside p method
Inside finally block
Exception caught in m method

From the main method, it calls the m() method which prints a line and then calls the n() method. Inside this method, it prints another line and then calls the p() method. It prints a line and then throws an exception. Since finally block is always executed, it executes this first and transfers the exception to the n() method. This again propagates the exception to the m() method which handles the exception.

148. What is the output of the below code?

public class Demo {

  int x;
  Demo(int x) {
    this.x = x;
  }
  
  public int sum() {
    x = x  + 5;
    try {
      x = x + 5;
      
      try {
        x = x * 5;
        throw new Exception();
      }
      catch(Exception e) { 
        x = x - 5;
      }
    }
    catch(Exception e) {
      x = x - 5;
    }
    
    return x;
  }
  public static void main(String[] args) {
    Demo d = new Demo(5);
    int result = d.sum();
    System.out.println("Value of x: " + result);

  }

}
Value of x: 70

The constructor first initializes the x value to 5 during instance creation. Then it calls the sum method where it adds 5. Now x=10. Inside the first try block, it adds another 5 which means x = 15. Inside nested try, it multiplies by 5 hence x = 75. Now, it throws a new exception, which is caught by the inner catch block where it subtracts 5. Hence the final result is 70. The outer catch block will never be executed since there is no exception thrown here.

149. What is a String pool?

String constant pool is a special memory to store the String objects. When we create a string literal, JVM first checks in the โ€œstring constant poolโ€ if the string exists. If it does not exist, JVM creates a new string instance, else only a reference to the pooled instance will be returned. For example, in the below case, both string objects hold the same value. Hence only 1 object is created (i.e s1) and s2 will have the reference to s1. This means, irrespective of how many ever string variables we create with the same value, only 1 instance will be created in the string constant pool.

String s1 = "Java language"; 
String s2 = "Java language";

String in java

150. What is an immutable String in Java?

Immutable string in Java means we cannot change the value of the String. This means once we assign a value to a string object, we cannot change its value.

public class StringConcat {

  public static void main(String[] args) {
    String s1 = "Hello,";
    String s2 = s1.concat("How are you?");
    System.out.println(s1);
    System.out.println(s2);
  }

}
Hello,
Hello,How are you?

Even though we concatenate a new string to s1 object, the value of s1 object remains unchanged. But however, we can store the concatenated value to a new string object.

151. Why are the String objects immutable in Java?

Java string objects are immutable since it uses the concept of string literals. String literals mean assigning a string value to a variable without using the new keyword. Hence we have different variables all pointing to the same object, then if anyone variable value changes then it affects all the others as well. Hence String objects are immutable.

152. What are the different ways to create a string object?

We can create a string object in the below 2 ways:

  • Using string literal:ย This is the most direct way of creating aย string in Java. We can create a string by enclosing the value in double-quotes. Here the variable โ€œvalueโ€ of type String holds the string named โ€œJava languageโ€.
    String value = "Java language";

    When we create a string literal, the JVM first checks in the “string constant pool”. If it exists, then it returns only the reference to the instance pool else it creates a new instance.

  • Using the new keyword: When we want to have 2 different objects holding the same string value, then we create a string using theย new keyword as described below. In this case, JVM creates 2 different string objects in heap memory.
    String s1 = new String("Java");
    String s2 = new String("Java");

153. How many objects will be created in the below code?

String a = "Java";
String b = "Java";
String c = "Java";

Only 1 object will be created since we are creating string literals. When a new string literal is created, it checks if the value is already present in the string literal pool. Since it is present, it just returns the reference to that instance.

154. Why Java uses the concept of String literals?

Java uses String literals to manage memory efficiently since it does not create new instances for the same value.

155. How many objects will be created in the below code?

String s = new String("Java");

Since we are creating a string using the new keyword, it creates 2 objects, one in the heap memory and one in the string constant pool.

156. What is the output of the following code?

public class Test {

  public static void main(String[] args) {
    String s1 = "Java language";
    String s2 = new String("Java language");
    if(s1 == s2)
      System.out.println("s1 == s2");
    if(s1.equals(s2))
      System.out.println("s1.equal(s2)");

  }

}
s1.equal(s2)

Even though both string objects have the same content, their references are different since they are created in different ways. Hence == returns false since it checks for references and the equals() method returns true since it checks for the content.

157. What is the output of the below code?

public class Test {

  public static void main(String[] args) {
    String s1 = "Java language";
    String s2 = new String("Java language");
    s2 = s2.intern();
    System.out.println(s1==s2);
    
  }

}
true

The intern method returns a canonical representation of the string which means it returns a reference to the string equivalent from the pool. Hence both s1 and s2 will have the same reference.

158. What are the differences between String and StringBuffer?

StringStringBuffer
It is immutableIt is mutable
Concatenation process is slowerConcatenation process is faster
It overrides the equals method of the Object class to comapreIt does not override the equals method
Consumes more memoryConsumes less memory

159. What are the differences between StringBuffer and StringBuilder?

StringBufferStringBuilder
It is thread-safeIt is not thread-safe
It is synchronizedIt is not synchronized
Performance is slowerPerformance is faster
It is available from JDK 1.0It is available from JDK 1.5

160. How to create an immutable class in Java?

We can create an immutable class in Java by making all the fields as final along with the class as final. This is because we cannot change the values of the final members.

public final class Sample {

  final int accountNumber;
  
  public Sample(int accno) {
    this.accountNumber = accno;
  }

  public int getAccountNumber() {
    return accountNumber;
  }
}

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

In Java, the toString() method returns a string representation of the object. The compiler internally calls the toString() method whenever we print an object. This makes it easier to write code.

162. Why charArray() is preferred over String to store password?

A string is stored in the memory until it is garbage collected. Hence if we store passwords in String, it stays in the memory for a longer duration and can result in a security threat because we can extract the memory dump. On the other hand, if a password is stored in a charArray, we can immediately set it to blank once it is used which prevents security threats.

163. Write a Java program to count the number of words in a String.

public class CountWords {

  public static void main(String[] args) {
    String s = "Welcome to Java programming";
    String[] arr = s.split(" ");
    System.out.println("Number of words: " + arr.length);

  }

}
Number of words: 4

We can retrieve the number of words by using the split method with space as a delimiter. This returns an array of words and we can get the count using the length method of an array.

164. List down a few classes present in the java.util.regex package

The following classes or interfaces are present in the java.util.regex package

  • MatchResult Interface
  • Matcher class
  • Pattern class
  • PatternSyntaxException class

165. How do the metacharacters differ from ordinary characters?

Metacharacters are special characters in terms of a regular expression. Few metacharacters are $^*,{[). To treat them as normal characters, we need to use a backslash before these characters else it will be considered as special characters.

166. Write a regular expression to validate a password with conditions: Password must start with the alphabet, followed by alphanumeric whose length should be between 8 and 15.

Regular expression is ^[a-zA-Z][a-zA-Z0-9]{8-15} where ^ denotes a regular expression then followed by alphabet and then alphanumeric. {8-15} denotes that length should be between 8 and 15.

167. What is the output of the following code?

import java.util.regex.Pattern;

public class RegEx {

  public static void main(String[] args) {
    System.out.println(Pattern.matches(".a..", "Java"));
    System.out.println(Pattern.matches("..a.", "Java"));
    System.out.println(Pattern.matches("a...", "Java"));
    System.out.println(Pattern.matches("...a", "Java"));

  }

}
true
false
false
true

The first and last statements are true since the pattern matches the input string. It checks if “a” is present in the second and 4th position of the string. The second and third statements are false since the pattern does not match the input string which means “a” is not present in the second and first position.

168. What are the advantages of the Java inner classes?

  • It is useful if a class needs access to only one class which can be implemented using inner classes or nested classes
  • The inner class can access all the fields and members of the outer class including the private fields.
  • Promotes code optimization and maintenance.

169. What is a nested class?

A class within another class is called a nested class. It logically groups similar classes together so that the inner classes can access all the members of the outer classes as well.

public class classA {
  //code
  public class classB {
    //code
  }
}

170. What are the disadvantages of nested classes?

  • It increases the total number of classes.
  • Increases the load on JVM since it has to perform certain operations related to classes.

171. What are the types of inner classes used in Java?

  • Nested inner classes
  • Method local inner classes
  • Anonymous inner classes
  • Static nested classes

172. What is the difference between the nested class and the inner class?

The main difference is inner classes are non-static nested classes which means they are part of nested classes.

173. Can we access the non-final local variable inside the local inner class?

No. To access inside the local inner class, we need to declare the local variable as constant.

174. How many class files are created on compiling the outer class file in the below code?

public class classA {
  int a;
  class classB {
    int b;
  }
  class classC {
    int c;
  }
  
  public static void main(String[] args) {
    classA ca = new classA();
  }
}

3 class files will be created – classA.class, classA$classB.class and classA$classC.class

175. What is an anonymous inner class?

Anonymous classes helps to declare and instantiate a class at the same time. It is similar to a local class except that it does not have a class name. It is useful if we need to use them only once.

class Test {
  public void print() {
    System.out.println("Test print method");
  }
}

class AnonymousDemo {
  
  public void showDemo() {
    //Anonymous class
    Test t = new Test() {
      public void print() {
        System.out.println("Anonymous Demo print method");
      }
    };
    t.print();
  }
}
public class AnonymousClass {
  
  public static void main(String[] args) {
    AnonymousDemo a = new AnonymousDemo();
    a.showDemo();

  }

}
Anonymous Demo print method

Inside the class AnonymousDemo we are creating an anonymous class by extending the Test class and overriding the print method. Hence while calling the showDemo() method, it calls the anonymous print() method.

176. What is a nested interface?

An interface within another interface or a class is a nested interface. One best example is theย Entryย interface. This is defined inside theย Mapย interface. This is why we access it usingย Map.Entry and cannot access the Entry interface directly. The main use of the nested interface is it allows to implement only a particular interface within a grouped interface. We can always access the inner interface only by using the outer interface. By default, nested interfaces are static and public. However, we can change the access type of the inner interface.

177. Can a class have an interface?

Yes, we can define an interface within a class. This is also called a nested interface.

178. Can an interface have a class?

Yes, an interface can have a class which is static by default.

179. What is garbage collection?

Garbage collection is an automatic memory management process that frees up memory by deleting the unused objects. In this way it effectively manages the memory and there is no need of manual destruction or deletion of object. This is the reason that variables whose values are only declared and not initialized returns a value 0.

180. What is gc()?

The gc() method is part of the System and Runtime class that is used to invoke the garbage collector explicitly for cleanup process. By invoking this method, it frees up the memory of the unused objects.

public class GarbageDemo {

  public void finalize() {
    System.out.println("Garbage collected");
  }
  public static void main(String[] args) {
    GarbageDemo g1 = new GarbageDemo();
    GarbageDemo g2 = new GarbageDemo();
    
    g1 = null;
    g2 = null;
    System.gc();

  }

}

It calls the finalize method when gc() method is invoked and frees up the space of g1 and g2 objects. Hence it calls the finalize method twice.

181. How is garbage collection controlled?

Garbage collection process is controlled by the Java Virtual Machine(JVM) automaticallywhen there is less memory or running out of memory. We can also control it externally by calling the System.gc() method to clean up the unused objects and thereby free the memory.

182. How can we unreference an object in Java?

There are 3 ways to unreferenced an object in Java:

  • Nullifying the object or assigning null value to the object.
    Student s = new Student();
    s = null;
  • Assigning reference to another object.
    Student s1 = new Student();
    Student s2 = new Student();
    s1 = s2;
  • Anonymous object.
    new Student();

183. What is the use of the finalize() method?

The finalize() method is part of the Garbage collection process which is called once the garbage is collected. The Garbage collector clears the objects that are created using the new keyword. For others, we can use the finalize method to clean up. The finalize method is present in the Object class and hence can be overridden by any class since the Object class is the superclass for all the classes.

184. Can we reference an unreferenced object again?

Yes, we can reference an unreferenced object again.

185. What is the name of the Garbage collector thread?

The garbage collector thread uses Daemon thread.

186. What is the difference between final, finally, and finalize?

final: final is a keyword that is used to impose restrictions on a class, method, or variable. We cannot inherit a final class, cannot override a final method, and cannot change a final value.

finally:ย finally is a block that is used to execute important code during exception handling.

finalize:ย finalize is a method that is used as part of garbage collection to free up memory by deleting or destroying the unused objects.

187. What is the use of Runtime class?

The Runtime class is a subclass of the Object class that provides information about the current running environment. We can use the getRuntime() method to get a reference to the current runtime object. It has several methods like gc(), exit(), halt(), etc.

188. How to invoke an external process in Java?

import java.io.IOException;

public class Sample {

  public static void main(String[] args) throws IOException {
    Runtime.getRuntime().exec("notepad");

  }

}

189. What is the hierarchy of InputStream and OutputStream classes?

StreamClass Hierarchy

190. What is an IOStream?

Java IOStream is a process to perform read and write operations. A stream is a sequence of data in the form of bytes. An InputStream is used to read data and an OutputStream is used to write data. There are 3 different types of streams in Java:

  • Input stream: System.in – This is used to read data from the input stream.
  • Output stream: System.out – This is used to write data to the output stream.
  • Error stream: System.err – It prints error messages.

191. What are the differences between Reader/Writer classes and the InputStream/OutputStream classes?

Reader/Writer class:

  • It is character-oriented and called a CharacterStream class
  • Performs input/output operation for the 16-bit Unicode system.
  • The most commonly used classes are FileReader and FileWriter.

InputStream/OutputStream class:

  • It is byte-oriented and called a ByteStream class.
  • Performs input/output operation for 8-bit bytes.
  • The most commonly used classes are FileInputStream and FileOutputStream.

192. What are the super most classes for all the streams?

The stream classes can be divided into two types: ByteStream and CharacterStream.

The ByteStream classes contain InputStream and OutputStream classes. The superclass for these streams is java.io.InputStream and java.io.OutputStream.

The CharacterStream contains Reader and Writer classes. The superclass is java.io.Reader and java.io.Writer.

193. What is FileInputStream and FileOutputStream?

The FileInputStream class is used to read data from the input file. It reads data in the form of bytes. It can also be used to read characters but FileReader is a better option for character-oriented data.

The FileOutputStream class is used to write data into the file.

194. What is the use of BufferedInputStream and BufferedOutputStream classes?

BufferedInputStream and BufferedOutputStream classes are used to read and write data using buffer mechanism. It writes data into a buffer instead of directly writing it to a stream. Hence it makes reading and writing operation faster.

195. How to set permissions to a file in Java?

We can alter the permissions to a file in Java using the FilePermission class. This class contains permissions related to a directory or a file. We need to set the permissions related to the file path.

196. What are FilterStreams?

FilterStream classes provides additional functionalities to the stream classes. It acts like an interface where it reads the data, filters it and then passes the filtered data to the caller.

197. What is an I/O filter?

I/O filter performs filtering operation on the input/output streams like data manipulation or modificaton. It reads the data, filters it and then passes the filtered data. There are different IO filter streams like FilterInputStream and FilterOutputStream.

198. What are the different ways of reading input from the console in Java?

There are 3 different ways to read input from the console in Java:

    • BufferedInputStream: This reads the input from System.in and wraps it to InputStreamReader and then passes it to the BufferedReader.
      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStreamReader;
      
      public class BufferedReaderDemo {
      
        public static void main(String[] args) throws IOException {
          System.out.println("Enter a word: ");
          BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));   
              String value = reader.readLine();   
              System.out.println("Word is: " + value);     
      
        }
      
      }
      
      Enter a word: 
      Java
      Word is: Java
      

 

  • Scanner class: The Java Scanner class is used to get user input from different streams like user input, file, and the input string.

 

    • This class is part of the java.util package. By using various in-built methods, it can read different types of input.

 

import java.util.Scanner;
public class ScannerDemo1 {
  public static void main(String[] args) {
    System.out.println("Enter your name:");
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    System.out.println("Your name is " + s);
    sc.close();
  }
}
Enter your name:
Ravi Kumar
Your name is Ravi Kumar
  • Console class: It is used to get the input from the console.

199. What is serialization?

Serialization is the process of converting the state of the object into a byte stream that includes the object’s data and its type and the type of data it stores. The ObjectInputStream and ObjectOutputStream contain methods to serialize and deserialize an object. This process is JVM independent which means we can serialize in one platform and deserialize in another platform.

200. How can you make a class serializable?

We can make a class serializable by implementing the Serializable interface.

201. How can you avoid serialization in child class if the base class implements the Serializable interface?

It is not possible to avoid serialization directly in a child class if the base class implements the Serializable interface. But we can perform by implementing the writeObject and readObject methods in the subclass and throw NotSerializableException.

202. Can a serialized object be transferred via network?

Yes, it is possible to transfer a serialized object via network since it is stored in the memory in the form of bytes. It is also possible to write to a database or a disk.

203. What is deserialization?

Deserialization is the process of restoring the object state from the bytes form or serialized state.

204. What is a transient keyword?

A transient keyword is used to avoid the serialization process. This means if a variable is declared as transient, we cannot serialize it and cannot write its value or retains its value.

205. What is externalizable?

Externalizable is an interface that is used to write an object state into a byte stream in a compressed format.

206. What is the difference between Serializable and Externalizable interface?

SerializableExternalizable
It is a marker interface which means it does not contain any methods.It is not a marker interface and contains methods like writeExternal() and readExternal()
It does not call any class constructor during serializationIt calls the public default constructor
Performance is slowPerformance is fast and better
The class that implements the interface gives the responsibility to the JVM for serializing an object.It provides the responsibility to the developer to write their own logic.

207. What is socket programming in Java?

Socket programming the communication between 2 different nodes(socket) over a network. In other words, it establishes communication between applications running on different JREs. like a client and a server. It may be connection-oriented or connectionless. For connection-oriented, we use the Socket and SocketServer classes and for connectionless, we use DatagramSocket and DatagramPacket classes. The client must know the IP address of the server and the port number to establish a connection.

208. What is a socket?

A socket is an end-point that facilitates communication between 2 applications using TCP. We use the Socket class to create a socket. A socket uses the port number and IP address to establish the communication.

209. What are the steps to connect two computers using TCP?

  • Create a ServerSocket object in the server which denotes the port number with which the connection has to be made.
  • Invoke the accept() method in the server which waits until the client attempts to connect to the server on the given port.
  • Meanwhile, create a socket in the client class using the Socket class. The Socket class constructor takes the server port number and server name as the parameters.
  • The Socket class constructor tries to connect to the server with the specified name. If successful, the client will have a socket object to connect with the server.
  • The accept() method of the server now returns a reference to the new socket which the client created.

210. Write a Java program to establish a connection between client and server.

Server side:

import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {

  public static void main(String[] args) {
    try {
      ServerSocket ss = new ServerSocket(5555);
      Socket s = ss.accept();
      DataInputStream di = new DataInputStream(s.getInputStream()); 
      String str = (String)di.readUTF();
      System.out.println("Message: " + str);
      ss.close();
    }
    catch(Exception e) {
      System.out.println(e);
    }

  }

}

Client side:

import java.io.DataOutputStream;
import java.net.Socket;

public class ClientDemo {

  public static void main(String[] args) {
    try {
      Socket s = new Socket("localhost",5555);
      DataOutputStream dos = new DataOutputStream(s.getOutputStream());
      dos.writeUTF("Socket connection program");
      dos.flush();
      s.close();
    }
    catch(Exception e) {
      System.out.println(e);
    }

  }

}
Message: Socket connection program

211. How to convert numeric IP address into a hostname?

We can use the InetAddress class to get the host name by using methods getByName(“ipaddress”).getHostName().

import java.io.*;
import java.net.*;
public class ConvertNumericToHost {

  public static void main(String[] args) {
    try {
      InetAddress ia = InetAddress.getByName("192.18.97.39");
      System.out.println("Host Name: " + ia.getHostName());
    }
    catch(Exception e) {
      System.out.println(e);
    }

  }

}
Host Name: oc-192-18-97-39.compute.oraclecloud.com

212. What is a reflection in Java?

Reflection in Java is a mechanism to modify the behavior of methods, classes, or interfaces at runtime. The supporting classes are present in the java.lang.reflect package. It also provides information about the classes and the methods of the object to which it belongs.

213. What is the use of java.lang.Class class?

  • It provides many utility methods like getClass(), forName(), etc.
  • Allows creating an instance of a class without using the new operator.
  • Provides methods to change the runtime behavior of a class
  • Also provides methods to get the metadata of a class during runtime.

214. What are the different ways to instantiate the Class class?

There are 3 different ways to create an object for the Class class:

  • Class.forName(“class_name”): forName is the factory method to create an instance since the Class class does not have any constructor. We need to specify the fully qualified class name in the parameter for which we need to create an instance.
  • MyClass.class: This is mainly used for primitive data types when we know its class name. If we specify .class after a class name, it represents an object for that class.
  • obj.getClass():ย It is present in the Object class and returns the runtime class of the specified object.

215. What is the output of the below code?

class TestDemo {
  TestDemo() {
    System.out.println("Test class constructor");
  }
  
  public void print() {
    System.out.println("Print method in Test class");
  }
}
public class ReflectionDemo {

  public static void main(String[] args) throws InstantiationException, IllegalAccessException {
    try {
      Class a = Class.forName("TestDemo");
      TestDemo t = (TestDemo)a.newInstance();
      t.print();
      
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    

  }

}
Test class constructor
Print method in Test class

216. What is the use of javap?

The javap command provides details about the constructors, methods, fields of the class in the class file.

217. Can you access the private method from outside the class?

Yes, it is possible to change the runtime behavior of the class provided the class is not secure.

218. What are wrapper classes?

Wrapper classes in Java are used to access primitive data types as Objects. This is mainly used while using along with Collections like ArrayList or LinkedList where we need to specify the wrapper class and not primitive data type. There are 8 wrapper classes available for 8 primitive data types in the java.lang package.

Primitive Data typeWrapper class
booleanBoolean
byteByte
charChar
doubleDouble
floatFloat
intInteger
longLong
shortShort

219. What do you mean by autoboxing and unboxing and where do we use it?

Autoboxing is the process in which we convert primitive data type into objects. Eg: int to Integer Unboxing is the process in which we convert the object back into a primitive data type. Eg: Integer to int.

Both processes occur automatically in Java, however, we can externally do as well in the below situations:

  • While using Collections like ArrayList or LinkedList.
  • Creating an instance of parameterized classes like ThreadLocal
  • When we assign a primitive type to an object type.

220. What is the output of the below code?

public class WrapperDemo {

  public static void main(String[] args) {
    Double d = new Double(45.45);
    Double f = new Double(55.55);
    if(d == f) {
      System.out.println("Both Double objects are equal");
    }
    else
      System.out.println("Both Double objects are not equal");
    

  }

}
Both Double objects are not equal

The output print “Both Double objects are not equal” since it has 2 different references using the new keyword.

221. What is object cloning?

Object cloning is the process of creating a shallow copy of the object. We can use the clone() method of the Object class to clone an object. The class has to implement the Cloneable interface where the object has to be cloned else it will throw CloneNotSupportedException.

222. What are the advantages and disadvantages of object cloning?

Advantages:

  • Both objects(the original object and the cloned object) can be modified independently.
  • The clone() method is the fastest way to copy an array
  • It requires only creating an abstract class with the clone() method and hence does not require repetitive code.

Disadvantages:

  • It supports only shallow copying.
  • Does not have any constructor.
  • We have to include many syntaxes to our code in order to implement the clone method like implementing the Cloneable interface, define the clone method, and handle the exception.
  • Since the Cloneable interface does not have any methods, we need to instruct the JVM that we need to perform a clone operation.

223. What is a native method?

A native method is a method in Java where we can write implementations in languages other than Java.

224. What is the use of strictfp keyword?

The strictfp keyword in Java provides the same result for the floating-point arithmetic operation in any platform. This means it gives results with the same precision value in any platform.

225. What is the use of the System class?

We can use the System class to access the system resources like Standard input and output. We cannot create an instance for the System class. It provides support like Standard input, Standard Output, and Standard error.

226. What is the term used for shallow copy in Java?

Object cloning

227. What is a singleton class?

A singleton class in Java means we cannot create more than one instance for a class. This means we can create only one object for the singleton class. Even if we try to create a second instance, it will refer to the first instance and performs operations based on that. We can create a singleton class by the below way:

  • Declare the constructor as private.
  • Use static getInstance() method.

228. Write a program to print all the values provided in the command line.

public class TestClass {

  public static void main(String[] args) {
    for(int i=0;i<args.length;i++)
      System.out.println(args[i]);

  }

}

 

C:\Users\Downloads>javac TestClass.java

C:\Users\Downloads>java TestClass welcome to java programming
welcome
to
java
programming

229. Which containers use a border layout as the default layout?

The Window, Frame, and Dialog classes.

230. Which containers use FlowLayout as the default layout?

The Panel and Applet classes.

231. What are peerless components?

Peerless components are the lightweight components. Swing has its own libraries that do not use the components from the operating systems. These are called as lightweight or peerless components.

232. What is the difference between a Scrollbar and a ScrollPane?

The Scrollbar is a component whereas a ScrollPane is a container that handles events and performs scrolling operations.

233. What is a lightweight component?

Lightweight components purely use the Java code to render graphical units and do not depend on the native operating system. For example, Swing uses drawLine and drawImage to perform graphical drawings.

234. What is a heavyweight component?

The Operating system that is dependent on the UI discovery tools is called heavyweight components. For example, AWT uses graphical classes provided by the operating system and is limited to use a minimal subset of the screen elements supported by all platforms.

235. What is an applet?

Applets are small programs that are present in the browser and execute automatically. It provides interactive features to web applications and runs on the client-side when ever the web application is invoked. It can be executed on many platforms that support browsers and executes much faster. The applet does not have or define a main() method. When an applet is created, it executes the init(), start(), and paint() methods, and when it is destroyed, executes the stop() and destroy() methods.

236. Can we write a Java class that can be used as both applet and an application?

Yes, we can use a Java class as both an applet and an application by defining the main() method.

237. What is a Locale?

A Locale represents geographical information where we can get details like country name, language, etc. The Locale class is present in the java.util package. We can instantiate a Locale object by using the getDefault() method. It has various methods like getLanguage(), getCountry(), etc

import java.util.Locale;

public class LocaleDemo {

  public static void main(String[] args) {
    Locale l = Locale.getDefault();
    System.out.println(l.getCountry());
    System.out.println(l.getDisplayLanguage());
    System.out.println(l.getDisplayName());
    System.out.println(l.getLanguage());

  }

}
IN
English
English (India)
en

238. How to load a specific locale?

We can use the ResourceBundle.getBundle() method to load a specific locale.

239. What is a Java Bean?

Java Bean is a reusable software component that encapsulates several objects into a single object. It is a class that has a no-argument constructor along with the getter and setter methods. The Java bean class should also implement java.io.Serializable.

240. What is the use of a Java Bean?

The main use of Java bean is to provide reusability and easy code maintenance. It encapsulates several objects into a single object which is called a bean.

241. What is bean persistent property?

The Java bean persistent property occurs when the fields, properties, and state information is stored and retrieved from the storage.

242. What is RMI?

RMI stands for Remote Method Invocation is an API that is used to create distributed applications in Java. It supports communication between two applications using object stubs and skeleton. RMI is a mechanism that allows one object to invoke another object that resides in a different JVM. We can use the java.rmi package to implement RMI.

243. What is the use of stub and skeleton?

A stub is a class that is present on the client-side and represents the remote object. It acts as a gateway for the client.

A skeleton is the counterpart of the stub and resides on the server-side.

244. What are the steps to write an RMI program?

Below are the steps to write an RMI program:

  • Create a remote interface
  • Implement the remote interface
  • Compile the implementation class and create a stub and skeleton using the rmic tool
  • Start the registry service
  • Create and start the remote application
  • Create and start the client application.

245. What is the use of HTTP tunneling in RMI?

HTTP tunneling in RMI handles the HTTP connections using the proxy servers and does not require any setup to work within the firewall environment.

246. What is JRMP?

JRMP stands for Java Remote Method Protocol that is used to refer to remote objects. It is a Java-specific and stream-based protocol that runs under RMI. It requires both client and server to use the remote objects.

247. Can RMI and CORBA based applications interact with each other?

Yes, RMI and CORBA based applications can interact with each other.

248. Write a Java program to perform a bubble sort.

public class BubbleSort {

  public static void main(String[] args) {
    int[] numbers = {25,12,89,45,65,35};
    int temp;
    for(int i=0;i<numbers.length;i++) {
      for(int j=0;j<numbers.length;j++) {
        if(numbers[i] < numbers[j]) {
          temp = numbers[i];
          numbers[i] = numbers[j];
          numbers[j] = temp;
        }
      }
    }

    System.out.println("Sorted list:");
    for(int i=0;i<numbers.length;i++)
      System.out.println(numbers[i]);
  }

}
Sorted list:
12
25
35
45
65
89

249. Write a Java program to perform Binary search.

import java.util.Scanner;

public class BinarySearch {

  public static void main(String[] args) {
    int count, num[], searchValue,first,last,middle;
    Scanner sc = new Scanner(System.in);
    
    //Get the number of elements to create a tree
    System.out.println("Enter the number of elements: ");
    count = sc.nextInt();
    
    //Create an array
    num = new int[count];
    
    //Store the elements in an array
    System.out.println("Enter the elements: ");
    for(int i=0; i<count; i++)
      num[i] = sc.nextInt();
    
    System.out.println("Enter the search element: ");
    searchValue = sc.nextInt();
    
    first = 0;
    last = count - 1;
    middle = (first+last)/2;
    
    while(first<=last) {
      if(num[middle]< searchValue) {
        first = middle + 1;
      }
      else if(num[middle] == searchValue) {
        System.out.println("The search element is present in the location: " + (middle + 1));
        break;
      }
      else {
        last = middle - 1;
      }
      middle = (first+last)/2;
    }
    if(first>last)
      System.out.println("The search element " + searchValue + " is not found in the tree.");

  }
  
  

}
Enter the number of elements: 
5
Enter the elements: 
10
20
30
40
50
Enter the search element: 
30
The search element is present in the location: 3

250. Write a Java program to perform the Selection sort.

public class SelectionSort {

  public static void main(String[] args) {
    int[] numbers = {30,50,10,40,20};
    int min;
    for(int i=0;i<numbers.length;i++) {
      min = i;
      for(int j=i+1; j< numbers.length; j++) {
        if(numbers[j] < numbers[min])
          min = j;
      }
      
      int temp = numbers[min];
      numbers[min] = numbers[i];
      numbers[i] = temp;
    }
    
    System.out.println("Selection sort:");
    for(int i =0;i<numbers.length;i++) {
      System.out.println(numbers[i]);
    }

  }

}
Selection sort:
10
20
30
40
50

251. Write a Java program to perform Linear search.

import java.util.Scanner;
public class LinearSearch {

  public static void main(String[] args) {
    int[] numbers = {10,40,30,20,50};
    int index=0;
    Boolean bFlag = false;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the search element: " );
    int val = sc.nextInt();
    
    for(int i=0;i<numbers.length;i++) {
      if(numbers[i] == val) {
        bFlag = true;
        index = i+1;
        break;
      }
      else
        bFlag = false;
    }
    if(bFlag)
      System.out.println("The search element " + val + " is found at position " + index);
    else
      System.out.println("The search element " + val + " is not found");

  }

}
Enter the search element: 
30
The search element 30 is found at position 3

252. Write a Java program to perform Merge sort.

public class MergeSort {

  public void merge(int[] arr, int first, int middle, int last) {
    int l = middle - first + 1;
    int r = last - middle;
    
    int LA[] = new int[l]; //Create left array
    int RA[] = new int[r]; //Create right array
    
    //Copy data to both arrays
    for(int i=0;i<l;++i)
      LA[i] = arr[first+i];
    
    for(int j=0;j<r;++j)
      RA[j] = arr[middle+1+j];
    
    int i=0,j=0;
    int k = first;
    
    while(i<l && j<r) {
      if(LA[i] <= RA[j]) {
        arr[k] = LA[i];
        i++;
      }
      else {
        arr[k] = RA[j];
        j++;
      }
      k++;
    }
    
    while(i<l) {
      arr[k] = LA[i];
      i++;
      k++;
    }
    
    while(j<r) {
      arr[k] = RA[j];
      j++;
      k++;
    }
    
  }
  
  public void sort(int[] arr, int first, int last) {
    if(first<last) {
      int middle = (first+last)/2;
      //Sort the first half array
      sort(arr,first,middle);
      
      //Sort the second half array
      sort(arr,middle+1,last);
      
      //Merge both the arrays
      merge(arr,first,middle,last);
    }
  }
  public static void main(String[] args) {
    int[] numbers = {10,50,40,60,30,20};
    MergeSort m = new MergeSort();
    m.sort(numbers, 0, numbers.length-1);

    System.out.println("Merge sort: ");
    for(int n=0;n<numbers.length;n++)
      System.out.println(numbers[n]);
  }

}
Merge sort: 
10
20
30
40
50
60

253. Write a Java program to perform a quick sort.

public class QuickSort {
  
  //Partioning the array
  public int partition(int[] arr, int low, int high) {
    //Pivot value
    int pivot = arr[high];
    
    //index of small element
    int i = low-1;
    
    for(int j=low;j<high;j++) {
      if(arr[j]<=pivot) {
        i++;
        
        //swap the elements
        int t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
      }
    }
    
    //Swap the next element and last element
    int t = arr[i+1];
    arr[i+1] = arr[high];
    arr[high] = t;
    
    return i+1;
  }
  
  //Quick sort functionality
  public void quicksort(int[] arr, int low, int high) {
    if(low<high) {
      int p = partition(arr,low,high);
      
      //Recursively sort the elements
      quicksort(arr,low,p-1);
      quicksort(arr,p+1,high);
    }
  }

  public static void main(String[] args) {
    int[] num = {80,30,50,10,60,20};
    
    QuickSort q = new QuickSort();
    q.quicksort(num, 0, num.length-1);
    
    //Print the sorted elements
    for(int i=0;i<num.length;i++)
      System.out.println(num[i]);
  }

}
10
20
30
50
60
80

254. Write a Java program to create a doubly linked list containing n nodes.

public class DoublyLinkedList {
  
  //Create a node class
  class Node {
    int value;
    Node prev;
    Node next;
    
    Node(int value) {
      this.value = value;
    }
  }
  
  //Initialize head and tail as null
  Node head,tail = null;
  
  //Add a node to doubly linked list
  void addNode(int value) {
    
    //Create a new node;
    Node n = new Node(value);
    
    //If list is empty, head and tail points to new node n
    if(head == null) {
      head = tail = n;
      
      //The prev and next value will be null
      head.prev = null;
      tail.next = null;
    }
    
    //Add the new node n to the end of the list
    else {
      tail.next = n;
      n.prev = tail;
      tail = n;
      tail.next = null;
    }
  }
  
  void print() {
    Node current = head;
    if(head == null) {
      System.out.println("Doubly linked list is empty");
      return;
    }
    System.out.println("Elements in

Doubly linked

 list:");
    while(current!= null) {
      System.out.println(current.value);
      current = current.next;
    }
  }

  public static void main(String[] args) {
    DoublyLinkedList d = new DoublyLinkedList();
    d.addNode(40);
    d.addNode(20);
    d.addNode(30);
    d.addNode(10);
    d.addNode(50);
    
    d.print();
    
  }

}
Elements in Doubly linked list:
40
20
30
10
50

255. Write a Java program to find the maximum and minimum value node from a circular linked list.

public class CircularLinkedList {
  
  public class Node {
    int value;
    Node next;
    
    public Node(int value) {
      this.value = value;
    }
  }
  
  //Initialize head and tail node as null
  public Node head = null;
  public Node tail = null;
  
  //Add new node at the end of the list	
  void add(int value) {
    Node n = new Node(value);
    
    //Check if list is empty, then assign head and tail as new node
    if(head == null) {
      head = n;
      tail = n;
      n.next = head; //Next node value will point back to head since it is circular linked list
    }
    
    //Assign new node to the tail
    else {
      tail.next = n;
      tail = n;
      tail.next = head;
    }
  }
  
  //Find minimum node value
  public void minNodeValue() {
    Node current = head;
    
    //Assign min as current node value
    int min = head.value;
    
    if(head == null) {
      System.out.println("List is empty");
    }
    
    else {
      do {
        if(min > current.value) {
          min = current.value; //Reassign min value if current value is lesser than min
        }
        current = current.next;
      }while(current != head);
      
      System.out.println("Minimum node value is: " + min);
    }
  }
  
  //Find maximum node value
  public void maxNodeValue() {
    Node current = head;
    
    //Assign max as current node value
    int max = head.value;
    
    if(head == null) {
      System.out.println("List is empty");
    }
    else {
      do {
        if(max < current.value) {
          max = current.value; //Reassign max value if current value is greater than max
        }
        current = current.next;
      }while(current != head);
      
      System.out.println("Maximum node value is: " + max);
    }
  }

  public static void main(String[] args) {
    CircularLinkedList c = new CircularLinkedList();
    c.add(20);
    c.add(30);
    c.add(10);
    c.add(50);
    c.add(40);
    
    //Find min node value
    c.minNodeValue();
    
    //Find max node value
    c.maxNodeValue();
  }

}
Minimum node value is: 10
Maximum node value is: 50

256. Write a Java program to find the difference between the sum of odd level and even level nodes of a Binary tree.

import java.util.LinkedList;
import java.util.Queue;

public class BinaryTreeDifference {

  public static class Node{
    int value;
    Node left;
    Node right;
    
    public Node(int value) {
      this.value = value;
      this.left = null;
      this.right = null;
    }
  }
  
  //Root of binary tree
  public Node root;
  
  public BinaryTreeDifference() {
    root = null;
  }
  
  public int diff() {
    int oLevel = 0, eLevel = 0, diffOddEven = 0;
    
    //To track number of nodes in each level
    int nodesInLevel = 0;
    
    //Tracks the current level
    int curLevel = 0;
    
    //Queue to track nodes level in a tree
    Queue<Node> queue = new LinkedList<Node>();
    
    //Check if root is null
    if(root == null) {
      System.out.println("Tree is empty");
      return 0;
    }
    
    else {
      //Add root node to queue to represent first level
      queue.add(root);
      curLevel++;
      
      while(queue.size() != 0) {
        //Holds number of elements in the queue
        nodesInLevel = queue.size();
        
        while(nodesInLevel > 0) {
          Node current = queue.remove();
          
          //Check if level is even
          if(curLevel%2 == 0)
            eLevel += current.value;
          else
            oLevel += current.value;
          
          //Add left child to queue
          if(current.left != null)
            queue.add(current.left);
          
          if(current.right != null)
            queue.add(current.right);
          nodesInLevel--;
        }
        curLevel++;
      }
      
      //Calculate the difference
      diffOddEven = Math.abs(oLevel - eLevel);
    }
    
    return diffOddEven;
    
  }
  public static void main(String[] args) {
    BinaryTreeDifference bt = new BinaryTreeDifference();
    
    bt.root = new Node(10);
    bt.root.left = new Node(20);
    bt.root.right = new Node(30);
    bt.root.left.left = new Node(40);
    bt.root.left.right = new Node(50);
    bt.root.right.left = new Node(60);
    
    System.out.println("Difference between odd and even level: " + bt.diff());
  }

}
Difference between odd and even level: 110

257. What is multithreading?

Multithreading is a multitasking technique where one or more processes are executed concurrently at the same time. This results in maximum CPU utilization and hence provides better performance and consumes less memory. Each process is called a thread that executes independently. It is also called as Thread-based multithreading.

258. What is a thread in multithreading?

A thread is an individual subprogram or process that executes independently during multithreading process. It shares the same resources but still executes separately. It is light-weight and has several states such as NEW, BLOCKED, RUNNABLE, WAITING, TERMINATED, TIMED_WAITING. A thread can be only in one state at a time.

259. What is the difference between a thread and a process?

ProcessThread
The main program in execution is called a processA thread is a subset or part of a process
It has different addresses and occupies different memoryIt shares same resources and memory
Context switching is slowerContext switching is faster
Inter-process communication is slower and expensiveInter-thread communication is faster and less expensive
Change in parent process does not affect child processChange in parent thread can affect the child thread

260. What is inter-thread communication?

Inter-thread communication is the process in which synchronized threads communicate with each other at the same time. This occurs when one thread is paused in a critical condition and another thread enters the same critical condition to continue the execution process. We can achieve this by using the wait(), notify(), and notifyAll() methods.

261. What is the use of the wait() method in Java?

The wait() method is part of the Object class which is used in the inter-thread communication process. When the wait method is executed, it waits until another thread invokes the notify() or notifyAll() method or until a specified time is elapsed.

262. Why should we call the wait() method from a synchronized block?

We use the wait() method in a synchronized block for inter-thread communication else it will throw java.lang.IllegalMonitorStateException exception. This wait() method is used in a synchronized block along with notify() or notifyAll() methods to ensure proper communication.

263. What are the advantages of multithreading?

  • Minimized system resource usage
  • Improved server responsiveness
  • Better communication
  • Improved throughput
  • Decreased maintenance cost
  • Simplified program structure

264. What are the different states in a lifecycle of a thread?

A thread can be in any one of the below states. At a time, it can be only in one state.

  • NEW: A thread is created in this state using the new operator. A thread starts only when it calls the start() method.
  • RUNNABLE: The thread is ready to run after it calls the start method. It starts running once it is picked by the scheduler.
  • RUNNING: The thread is in a running state when it is picked up by the scheduler.
  • WAITING/BLOCKED: The thread is not running and waiting for another thread to complete.
  • TERMINATED: The thread is terminated after it exits from the run() method.

265. What is the difference between preemptive scheduling and time slicing?

Preemptive scheduling: A high priority task is executed until it goes to the waiting/dead state or another high priority task comes for execution.

Time slicing: A task is executed for a specific time and then enters the pool of ready tasks again. The scheduler determines which task to pick based on the priority.

266. What is context switching?

Context switching means the CPU time is shared across all processes and switches between processes in a time-bound manner. This means it saves the state of the process and can resume from where it was halted and continue the execution.

267. What is the difference between the Thread class and Runnable interface for creating a thread?

We can create a thread in 2 different ways:

  • Extending Thread class – If it extends a Thread class, then it cannot extend any other class since Java does not support multiple inheritance. Each thread has a unique object. It supports various built-in methods like getPriority(), isAlive(), etc.
  • Implementing Thread class using Runnable interface – If we implement the Runnable interface, we can also extend other classes. Multiple threads share the same object. It supports only a single method which is the run() method.

268. What is a join() method?

The join method is part of the Thread class that waits for the current thread execution to complete before another thread is executed. For example, if t is a thread object of the current thread, then t.join will ensure that t is terminated before it picks the next instruction.

269. Describe the working and use of the sleep() method.

The sleep() method is used to make the thread wait for a certain amount of time. In other words, it pauses the execution of the thread for a specific time.

When a thread calls the sleep method, the current thread execution is paused for a specific time and executes other threads if available. Once the waiting period is complete, it resumes the previous thread and starts running until it completes the execution.

270. What is the difference between wait() and sleep()?

wait(): This method is part of the Object class and can release the lock.

sleep(): This method is part of the Thread class and cannot release the lock.

271. Can we start a thread twice?

No, we can start a thread again if it is already started. This is because once a thread starts and executes, it goes to the dead state, Hence it will throw IllegalThreadStateException if we try to restart a thread.

272. Can we call the run() method instead of the start() method?

Yes, calling a run() method directly is valid but it will not work as a thread and will not support context switching. This is because when we call the start() method, it internally calls the run() method which creates a separate stack whereas if we call the run() method directly will not create a new stack.

273. What are daemon threads?

Daemon threads are low priority threads that support background services to the user threads. Daemon threads are terminated automatically by the JVM when all the other user threads are dead. We can check if a thread is a daemon thread or not and also set a thread as a daemon thread.

274. Can we make a user thread as a daemon thread if it is already started?

No, we can make user threads as daemon threads only before starting the thread, else it will throw IllegalThreadStateException.

275. What is a shutdown hook?

A shutdown hook is a thread that is invoked implicitly before the JVM shuts down normally or abruptly. Hence it can be used to clean up or release the resources. It is more efficient than the finalizer() method. We can add a shutdown hook by using the below code:

public void addShutDownHook(Thread hook) { }
Runtime r = Runtime.getRuntime();
r.addShutdDownHook(new MyThread());

276. When should we interrupt a thread?

We use the interrupt() method to interrupt a thread from either sleep state or wait state. This method throws InterruptedException.

277. What is synchronization?

Synchronization is the process of controlling the access of threads to a resource. This means it allows only a single thread to access the resource at the same time. Synchronization is very important to use in Java when multiple threads attempt to get the same resource. Synchronization can be achieved in the below ways:

  • Synchronized method
  • Synchronized block
  • Static synchronization

278. What is the use of a synchronized block?

A synchronized block is always marked with a synchronized keyword. The synchronized blocks contain all the shared resources. This means a single thread can only access the shared resources at the same time. The remaining threads will be in a blocked state. This block locks the object for a shared resource.

synchronized(object_identifier) {
   //shared resources
}

279. Can Java objects be locked down for exclusive use by a given thread?

Yes, we can lock a Java object for exclusive use by a given thread by specifying it within a synchronized block. In this way, only a single thread can access the object at a particular time.

280. What is static synchronization?

When we use the static keyword before a method, it is static synchronization. This means that the lock is on the class and not on the object and at a time only one thread can access the class at a given time.

281. What is the difference between the notify() and notifyAll() method?

The notify() method unblocks a single waiting thread while the notifyAll() method unblocks all the threads that are in the waiting state.

282. What do you mean by deadlock?

Deadlock is a situation in which a thread waits for a resource that is held by another waiting thread. This means none of the threads get a chance to execute and will be waiting infinitely. It is a very important concept that needs to be handled in code.

283. How to detect a deadlock and how can it be avoided?

We can detect a deadlock by running the code in the cmd and if it exists, a message will appear on the cmd.

Avoiding deadlock situation

We can avoid a deadlock situation by the below ways:

  • Avoid nested locks
  • Avoid unnecessary locks
  • Using thread join

284. What is a thread scheduler in Java?

A thread scheduler is part of the JVM which decides which thread should be executed. In other words, it is the responsibility of the thread scheduler to pick up the thread for execution. A thread scheduler used two mechanisms to select the thread: Preemptive Scheduling, Time slicing.

285. Does each thread have its stack in multithreaded programming?

Yes, each thread has its own stack in multithreaded programming thus making it independent of each other.

286. How is the safety of a thread achieved?

When a method or a class can be used by multiple threads without any issues, we call it a thread-safe. We can achieve a thread-safe program in the below ways:

  • Synchronization
  • volatile keyword
  • Using a lock-based mechanism
  • Atomic wrapper classes.

287. What is the race condition?

A race condition occurs when multiple threads try to access the same shared resource at the same time. This can be avoided using the synchronization concept.

288. What is a volatile keyword?

A volatile keyword is used to achieve a thread-safe program. A change in the volatile variable is common to all threads hence once variable can be used by one thread at a time.

289. What is a thread pool?

A thread pool is a common area where all the threads that are ready and waiting for task allocation. The service provider checks the thread pool and picks up one thread at a time for execution. Once the task is completed, the thread will again go back to the thread pool. Using the thread pool, we can enhance performance and achieve better system stability.

290. What are the main components of the Concurrency API?

The java.util.concurrent contains many components that support the development of the Concurrency API as listed below:

  • Executor
  • ExecutorService
  • ScheduledExecutorService
  • Future
  • CountDownLatch
  • CyclicBarrier
  • Semaphore
  • ThreadFactory
  • BlockingQueue
  • DelayQueue
  • Locks
  • Phaser

291. What is the Executor in Concurrency API in Java?

The Executor interface of the java.util.concurrency contains as execute() method to execute some task or given command. If the executor cannot accept the task for execution, it will throw RejectedExecutionException.

Syntax:

public void execute(Runnable command)

292. What is BlockingQueue?

BlockingQueue supports asynchronous programming. It is a subinterface of Queue that supports operations like waiting for space availability before inserting a new value or waiting for the queue to become non-empty before retrieving a value.

293. How to implement the producer-consumer problem by using BlockingQueue?

The producer-consumer pattern is the most common integration patterns in asynchronous programming. We can implement this using the BlockingQueue as seen in the below example:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

class Producer implements Runnable {
  
  private final BlockingQueue b;
  
  public Producer(BlockingQueue b) {
    this.b = b;
  }

  @Override
  public void run() {
    for(int i=0;i<5;i++) {
      try {
        System.out.println("Produced: " + i);
        b.put(i);
      }
      catch(InterruptedException e) {
        Logger.getLogger(Producer.class.getName()).log(Level.SEVERE,null,e);
      }
    }
    
  }
  
}

class Consumer implements Runnable {

  private final BlockingQueue b;
  
  public Consumer(BlockingQueue b) {
    this.b = b;
  }
  @Override
  public void run() {
    while(true) {
      try {
        System.out.println("Consumed: " + b.take());
      }
      catch(InterruptedException e) {
        Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null,e);
      }
    }
    
  }
  
}

public class BlockingQueueDemo {

  public static void main(String[] args) {
    BlockingQueue b = new LinkedBlockingQueue();
    
    Thread p = new Thread(new Producer(b));
    Thread c = new Thread(new Consumer(b));
    
    p.start();
    c.start();

  }

}
Produced: 0
Produced: 1
Produced: 2
Produced: 3
Produced: 4
Consumed: 0
Consumed: 1
Consumed: 2
Consumed: 3
Consumed: 4

 

294. What is the difference between the Java Callable interface and the Runnable interface?

Both the Java Callable and the Runnable interfaces are used by classes that want to execute multiple threads. However, there are a few differences as below:

Callable interfaceRunnable interface
The interface can return a resultThe interface cannot return a result
It can throw a checked exceptionIt cannot throw a checked exception
The Callable interface supports only after Java 5The Runnable interface can be used before Java 5 as well

295. What is atomic action in Concurrency in Java?

Atomic action is used to perform a single task that does not require any dependency or interference with other operations. The atomic operation cannot be stopped in between. This means once it starts it has to complete the task fully.

Example of atomic operations: All read and write operation for a primitive variable(except long and double) and volatile variable (including long and double).

All the atomic methods are present in the java.util.concurrent package.

296. What is a lock interface in Concurrency in Java?

Lock interface is used to block other threads from accessing a code segment that is currently used by another thread. It supports the synchronization mechanism. It is similar to a synchronized block however there are few differences.

The main difference is that a synchronized block is within a method while the Lock interface APIs like lock() and unlock() can be separate methods. Lock interface has a timeout option while the synchronized block does not have.

297. What is ExecutorService interface

ExecutorService is a subinterface of the Executor and supports asynchronous processing. It has features to manage the entire lifecycle.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrencyDemo {

  public static void main(String[] args) {
    ExecutorService e = Executors.newFixedThreadPool(10);
    e.execute(new Runnable() {
       public void run() {
         System.out.println("Executor Service");
       }
    });
    e.shutdown();
  }

}
Executor Service

298. What is the difference between synchronous and asynchronous programming in the Thread concept?

In synchronous programming, after assigning a task to a thread and starting the task, it is available for other tasks only once this is complete.

In asynchronous programming, multiple threads can complete the same job and hence promotes maximum usability.

299. What is Callable and Future in Java?

Java Callable interface was introduced from Java 5 and is part of the java.util.concurrent package. It has a run() method to support execution and can return a result and throw an exception as well.

The Java Future interface returns the result of the concurrent process. The Callable interface returns the object of java.util.concurrent.Future. The Java future interface supports implementation for various methods like cancel(), get(), isCancelled(), isDone().

300. What is the difference between ScheduledExecutorService and ExecutorService interface?

ScheduledExecutorService and ExecutorService interfaces are part of the java.util.concurrent package. The main difference is that the ScheduledExecutorService can perform tasks periodically and has additional methods to execute the Runnable and Callable tasks.

301. What is the FutureTask class in Java?

The FutureTask class provides the base implementation of the Future interface. It has methods to start and cancel computation. We can retrieve the results only if the computation is complete, else the get method will block if the computation is not complete. It is not possible to restart or cancel the computation once it is complete.

302. What is a Collection framework in Java?

A Collection framework contains a list of classes and interfaces to store and manipulate data. This framework contains classes like ArrayList, Vector, Stack, HashSet, etc, and interfaces like List, Queue, etc.

303. What is the difference between array and collection?

ArrayCollection
It is fixed size and cannot change the size in runtimeThe size can be dynamically changed and is not fixed.
It can store only same type of dataIt can store combination of data type values
It does not have built-in methods like sorting or searchingIt has built-in methods for sorting and searching
Performance is fastPerformance is slow
Memory efficiency is lessMemory efficiency is more
It is not implemented based on any data structureEvery class in Collection is implemented based on some data structure

304. What are the various interfaces used in a Collection framework?

The Collection framework contains various interfaces as listed below:

  • Collection interface:ย This is the primary interface and every other interface must implement the Collection interface. java.util.Collection
  • List interface:ย List is an ordered collection of elements that can store duplicate values and extends the COllection interface. We can access random elements from a List. java.util.List
  • Set interface: Set is an interface that cannot store duplicate values and can include only inherited methods of the Collection interface. java.util.Set
  • Queue interface:ย The queue interface stores data in the form of a First-In-First-Out basis(FIFO). java.util.Queue
  • Dequeue interface:ย It is a double-ended queue and implements the Queue interface. It supports both FIFO(First-In-First-Out)ย  operation of the queue and LIFO(Last-In-First-Out) operation of stack. Due to this, we can insert and remove elements from both ends. java.util.Dequeue
  • Map interface: A Map interface stores elements in the form of key-value pairs. It can store only unique keys but can contain duplicate values. It does not implement the Collection interface. java.util.Map

305. What is the difference between ArrayList and Vector?

ArrayListVector
ArrayList is not synchronizedVector is synchronized
It is not a legacy classIt is a legacy class
It can increase its size by 50% of the array sizeIt can increase its size by doubling
It is not thread-safeIt is thread-safe
Uses only Iterator for traversingUses both Enumeration and Iterator for traversing
ArrayList performance is fasterVector performance is comparatively slower

306. What is the difference between ArrayList and LinkedList?

ArrayListLinkedList
Uses dynamic array to store elementsUses Double LinkedList to store elements
Performance is slowerPerformance is faster
It can be used to implement only ListIt can be used to implement List and Queue
Provides random accessDoes not provide random access
Occupies less memory since it stores only objectOccupies more memory since it stores both object and reference of the object
get(int index) gives performance of O(1)get(int index) gives performance of O(n)
Removal operation performance in worst case is O(n) and best case is O(1)Removal operation gives performance of O(1)
Add method gives performance of O(n) in worst caseAdd method gives performance of O(1)

307. What is the difference between Iterator and ListIterator?

IteratorListIterator
It is a universal iteratorIt is not a universal iterator
It can be used for any type of CollectionIt can be used only for List implementation classes
Supports only read and delete operationSupports add, update, read and delete operations.
Can be used only for forward navigationCan be used for forward and reverse direction navigation
It is not a bidirectional iteratorIt is a bidirectional iterator
We use the iterator() methodWe use the listiterator() method.
We cannot specify the index for iterationWe can specify the index for iteration

310. What is the difference between Iterator and Enumeration?

EnumerationIterator
Available from JDK 1.0Available from JDK 1.2
It is not a universal iteratorIt is a universal iterator
It can be used to iterate only legacy collections like Vector, hashtableIt can be used to iterate any Collections
Supports only read operationSupports both read and delete operation
It has lengthy method names
Eg: hasMoreElements()
It has short method names
Eg: hasNext()

311. What is the difference between List and Set?

ListSet
It can store duplicate elementsIt can store only unique elements
It is an ordered collectionIt is an unordered collection
It has a single legacy class which is VectorIt does not have any legacy class
It can store any number of null valuesIt can store only a single null value

312. What is the difference between HashSet and TreeSet?

TreeSetHashSet
Maintains ascending orderDoes not maintain any order
Computation is slowerComputation is faster
Time cost is log(n)Time cost is constant

313. What is the difference between Set and Map?

SetMap
Set stores only valuesMap stores key and values
Set can contain unique valuesMap can contain unique keys and duplicate values
It can hold single null valueIt can hold single null key and multiple null values

314. What is the difference between HashSet and HashMap?

HashSetHashMap
It implements the Set interfaceIt implements the Map interface
It stores only valuesIt stores data in the form of key-value pair
It cannot have duplicate valuesIt can contain duplicate values with unique keys
It can have only a single null valueIt can hold a single null key with multiple null values

315. What is the difference between HashMap and TreeMap?

TreeMapHashMap
Maintains ascending orderDoes not maintain any order
Cannot contain null keyCan contain one null key
It is a tree structure based implementationIt is a hashtable based implementation
It does not allow null valuesIt allows multiple null values
Sorting is slowerSorting is faster
Uses red-black tree data structureIt uses a hashtable data structure

316. What is the difference between HashMap and HashTable?

HashMapHashtable
It is not synchronizedIt is synchronized
It is not thread safe and cannot be shared between threadsIt is thread safe and can be shared between threads
Allows one null key and multiple null valuesDoes not allow null key and null value
Introduced in JDK 1.2It is a legacy class
We use Iterator to traverse through HashmapWe use Iterator or Enumeration to traverse through Hashtable
Inherits AbstractMap classInherits Dictionary class
Computation is fastComputation is slow

317. What is the difference between Collection and Collections?

  • Collection is an interface while Collections is a class
  • Collection provides data structure to implement List, Set,etc while Collections class provides methods to sort and synchronize collection elements.

318. What is the difference between Comparable and Comparator?

  • Comparable has a single method compareTo() while Comparator contains a single method compare().
  • Comparable is found in the java.lang package while Comparator is found in the java.util package
  • There is only one sort sequence in Comparable while the Comparator has multiple sore sequence.

319. What is a BlockingQueue?

BlockingQueue extends the Queue interface and provides operations to support the concurrency concept. It cannot contain null elements. During the retrieval operation, the queue has to be non-empty and while storing the elements, the queue should have some available space.

320. What is the advantage of the Properties file?

The properties file is mainly used when we want to store information that changes frequently. Whenever we change the values in the property file, we do not need to recompile the java class file. Hence maintenance is easy using the Properties file and provides flexibility in terms of configuration.

321. What is a hashCode() method?

The hashCode() method is used in the hashing technique. This method returns a hashcode value which is an integer. It returns the same integer value if both the keys are equal. It checks if two keys are equal by the equal() method. If two objects do not produce an equal result using the equals() method, then the hashCode() method will return a different integer for both the objects.

322. Why should we override the equals() method?

We override the equals() methods to checks if the properties of an object are equal or not.

323. How to synchronize elements in a List, Set, and Map?

We can use the synchronized method that is present in the Collections class to synchronize the elements as below:

public static List synchronizedList(List l) {}
public static Set synchronizedSet(Set s) {}
public static SortedSet synchronizedSortedSet(SortedSet st) {}
public static Map synchronizedMap(Map m) {}
public static SortedMap synchronizedSortedMap(SortedMap sm) {}

324. What is the advantage of using a generic collection?

  • We don’t need to typecast while using a generic collection.
  • It is type-safe and checked at compile time
  • It makes the code more stable by detecting bugs during compile time

325. What is hash-collision in Hashtable and how can we handle it in Java?

When two different keys produce the same hashcode value, we call it hash-collision. In this case, it stores as two separate entries in the same bucket. There are 2 ways to avoid a collision:

  • Separate chaining
  • Open addressing

326. What is a Dictionary class?

A Dictionary class stores data in the form of key-value pairs. We can retrieve the value based on the corresponding key. It is similar to the English Dictionary word where we can get the meaning of a word by searching with the keyword.

327. What is the default size of load factor in hashing based collection?

The default size of the load factor is 0.75.

328. What is fail-fast?

Fail-fast occurs in an Iterator when we try to modify the structure during iteration. It throws ConcurrentModificationException. It does not require any extra space in memory.

329. What is the difference between Array and ArrayList?

  • An Array is of fixed-size and we cannot change it while we can change the size of ArrayList dynamically.
  • Arrays can store primitive data and objects while ArrayList can store only objects.

330. What is the difference between the length of an array and the size of an ArrayList?

To retrieve the length of an array, we can use the length property.

int[] a = {4,5,6,7}
System.out.println(a.length);

But ArrayList does not have a length property, instead, we use the size() method to get the number of elements in the ArrayList.

ArrayList<String> al = new ArrayList<String>();
al.add("AAA");
al.add("BBB");
System.out.println(al.size());

331. How to convert an ArrayList to an Array and vice-versa?

We can use the toArray() method of the ArrayList to convert an ArrayList to an Array as below:

ArrayList<String> al = new ArrayList<String>();
al.toArray(new String[al.size()]);

To convert an Array to an ArrayList, we use the asList method of the Array as below:

int[] a = {4,5,6};
Arrays.asList(a);

332. How to make the Java ArrayList read-only?

We can use the Collections.unmodifiableCollection() method to make the ArrayList as read-only. In this case, we cannot perform add, delete, or set operations on the ArrayList.

333. How to remove duplicates from an ArrayList?

We can remove the duplicates from an ArrayList in two ways:

  • Using HashSet – It does not preserve the insertion order but removes duplicates
  • Using LinkedHashSet – It maintains the order and removes duplicates

334. How to synchronize ArrayList?

We can synchronize ArrayList by using either Collections.synchronizedList() method or using CopyOnWriteArrayList<T>.

335. When to use ArrayList and LinkedList?

We can use ArrayList for search operations and LinkedList for update operations.

336. Write a Java program to reverse the elements in an ArrayList.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class ArrayListSort {

  public static void main(String[] args) {
    ArrayList<Integer> i = new ArrayList<Integer>();
    i.add(5);
    i.add(1);
    i.add(10);
    i.add(3);
    i.add(8);
    System.out.println("ArrayList Elements:");
    for(int num : i)
      System.out.println(num);
    
    Iterator it = i.listIterator();
    Collections.reverse(i);
    
    System.out.println("Elements in the reverse order:");
    while(it.hasNext())
      System.out.println(it.next());
  }

}
ArrayList Elements:
5
1
10
3
8
Elements in the reverse order:
8
3
10
1
5

337. Write a Java program to sort the elements in an ArrayList in descending order.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

public class ArrayListReverse {

  public static void main(String[] args) {
    ArrayList<Integer> al = new ArrayList<Integer>();
    al.add(30);
    al.add(10);
    al.add(50);
    al.add(40);
    al.add(20);
    
    System.out.println("Elements in the ArrayList");
    for(int i: al)
      System.out.println(i);
    
    System.out.println("Sort Elements in descending order:");
    Comparator c = Collections.reverseOrder();
    Collections.sort(al, c);
    Iterator it = al.listIterator();
    while(it.hasNext())
      System.out.println(it.next());

  }

}
Elements in the ArrayList
30
10
50
40
20
Sort Elements in descending order:
50
40
30
20
10

338. What is JDBC?

JDBC is Java Database Connectivity which is an API to connect the Java application and databases. It used JDBC drivers to connect and execute queries in a database. We can also view and modify records in a database.

339. What is JDBC Driver?

JDBC driver uses the JDBC API to connect the Java application to any database. JDBC driver implementation is based on the type of operating system and hardware platform. Below are the different types of JDBC drivers available:

  • JDBC-ODBC Bridge driver: Uses the ODBC driver to connect to the database. It converts the JDBC method calls into the ODBC method calls. This is less used now and replaced by a thin driver.
  • JDBC Native API: Converts the JDBC calls to native calls of the database API. It uses the client-side libraries of the database. Its performance is better than the JDBC-ODBC driver.
  • JDBC-Net pure Java: This is a network protocol driver that uses the middleware to convert the JDBC calls to vendor-specific database protocol.
  • Thin driver(100% pure Java): It is a pure Java driver that directly converts the JDBC calls to vendor-specific database protocols. This is the most recommended type of driver due to its faster performance.

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

Below are the steps to connect to a database in Java:

  • Import the JDBC package: To use the JDBC drivers, we need to import the specific packages in our code.
    import java.sql.*;
    
  • Load and Register the JDBC drivers: We can use the forName()method to load and register the JDBC Driver. Registration is just a one time processor for the entire Java application.
    Class.forName("oracle.jdbc.driver.OracleDriver");
  • Connect to the Database: We need to establish a connection to the database by using the getConnection() method. It creates an object instance of java.sql.Connection class. It accepts three parameters, the URL of the database server, username, and password to connect to the database(if required).
    Connection con = DriverManager.getConnection(URL, username, password);
  • Create a statement object: Next, we need to create a statement that is used to execute the queries in the database. For this, we can use access to the createStatement method using the connection object.
    Statement s = con.createStatement();
  • Execute the query: Using the Statement object, we can execute the required queries. This always returns a result of type ResultSet.
    ResultSet rs = s.executeQuery(query);
  • Process the result: After executing the query, we can process the result using the while loop.
    while(rs.next())
         System.out.println(rs.getInt(1) + " " + rs.getString(2));
  • Close the objects: Once all operations are complete, we need to close the ResultsSet, Statement, and Connection objects using the close() method.
    rs.close();
    s.close();
    con.close();

341. What are the JDBC API components?

The JDBC API components contain different interfaces and classes as below:

Interfaces

  • Connection: The connection object establishes a connection to the required database.
  • Statement: Using the connection object, we can create a Statement object to execute the query.
  • PreparedStatement: This is used to execute parameterized queries.
  • ResultSet: It returns the result of the query that is executed.
  • ResultSetMetaData: It contains information of the table like the number of columns, column name, column type, etc
  • DatabaseMetaData: It provides information about the database like database name, driver name, the total number of tables, etc.
  • CallableStatement: Useful to call stored procedures and functions

Classes

  • DriverManager: Keeps track of all the available drivers and establishes a connection to the database. This is the main class component of the JDBC API.
  • SQLException: Provides information related to errors in the database.
  • Blob: It is a Binary large object that represents a collection of binary data.
  • Clob: It is Character large object that stores character files.

342. What are JDBC statements?

JDBC Statement is used to execute the SQL queries and retrieve the data. It has methods like execute(),executeUpdate(), executeQuery(), etc to execute various SQL commands.

There are 3 types of JDBC Statements:

  • Statement: It executes a static SQL query at runtime and is a factory of the ResultSet.
  • PreparedStatement: It executes parameterized queries at runtime.
  • CallableStatement: It is used to access stored procedures or functions.

343. What is the return type of Class.forName() method?

The Class.ForName() returns an object of type java.lang.Object class.

344. What are the differences between Statment and PreparedStatement?

StatementPreparedStatement
It is used to execute SQL queriesIt is used to execute parameterized queries
When we use Statement, the query is compiled every time when we run the programWhen we use PreparedStatement, the query is compiled only once.
It does not require any parametersIt is required to pass parameters to the query

345. How to set null value in JDBC PreparedStatement?

We can use the setNull() method of the PreparedStatement interface to set an index to null value as below.

void setNull(int parameterIndex, int sqlType) throws SQLException

346. What are the benefits of PreparedStatement over the Statement interface?

  • PreparedStatement performance is faster than Statement since the query is compiled only once whereas, in Statement, the query is compiled every time when we run the program.
  • We can pass parameters to the query while using PreparedStatement while we can use only static queries in the Statement.
  • PreparedStatement reuses the cache since the query is similar always while this is not the case in Statement.

347. What is the difference between execute, executeQuery, and executeUpdate?

executeexecuteQueryexecuteUpdate
It can be used to perform any SQL statement opertions like both update and selectIt can be used to perform only select operationIt can be used to perform only operations like update, delete or insert.
Returns a Boolean valueReturns a ResultSet which contains the data retrieved by executing the queryReturns an integer value that represents the number of records affected by executing the query

348. What are the different types of ResultSet?

There are 3 types of ResultSet based on the direction in which it can navigate through the records:

  • ResultSet.TYPE_Forward_ONLY: It can navigate only in the forward direction.
  • ResultSet.TYPE_SCROLL_INSENSITIVE: It can navigate in both the forward and reverse directions. It is not sensitive to the changes made.
  • ResultSet.TYPE_SCROLL_SENSITIVE: It can navigate in both the forward and reverse directions. It is sensitive to the changes made.

349. What are the differences between ResultSet and RowSet?

ResultSetRowSet
Always maintains connection with the databaseIt can be connected and disconnected anytime
Cannot be serializedCan be serialized
Cannot pass a ResultSet object over networkCan pass RowSet object over a network
It is not a JavaBean objectIt is a JavaBean object
By default ResultSet is not scrollable and updatable.By default RowSet is scrollable and updatable.
ResultSet is returned by the executeQuery() methodRowSet is returned by the RowSetProvider.newFactory().createJdbcRowSet() method.

350. How to execute stored procedures using the CallableStatement?

Below are the steps to execute the stored procedures.

  • Create a procedure in the database
  • Establish a network connection
  • Create an object of the CallableStatement
  • Set the values and execute the query

Example:

Below is a sample procedure that we create in the database.

create or replace procedure "SAMPLE"(id IN NUMBER, name IN VARCHAR2)
is
begin
insert into employee values(id,name);
end

Below is the table structure

CREATE TABLE EMPLOYEE(ID NUMBER(10), NAME VARCHAR2(100))

Java code to execute a stored procedure using the CallableStatement.

import java.sql.*;
public class StoredProcedureDemo {

  public static void main(String[] args) throws Exception{
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");
    
    CallableStatement cs = c.prepareCall("{call sample(?,?)}");
    cs.setInt(1, 100);
    cs.setString(2, "Ravi");
    
    cs.execute();
    
    System.out.println("Success");

  }

}

351. What is the role of the JDBC DriverManager class?

The JDBC DriverManager class keeps track of all the available drivers that have registered using the registerDriver method. It acts as an interface between the user and the driver and helps to establish a connection between the driver and the database.

352. What is the function of the JDBC Connection interface?

The JDBC Connection interface helps to establish a connection to the database and maintains the session. It is also used for transaction management. It is used along with Statement, PreparedStatement, CallableStatement, and DatabaseMetaData.

353. What is a JDBC ResultSet interface?

The JDBC ResultSet interface contains the data retrieved by executing the query. Each ResultSet object represents the row in a data table. It has different types using which we navigate forward and backward in a data table.

354. What is the JDBC ResultSetMetaData interface?

The JDBC ResultSetMetaData interface contains information related to the table like the number of columns, column name, column type, etc.

355. What is the JDBC DatabaseMetaData interface?

The JDBC DatabaseMetaData interface contains information related to the database like database name, driver name, driver version, number of tables, etc. We can use the getMetaData method using the connection object to create an instance of the DatabaseMetaData.

356. Which interface is responsible for transaction management in JDBC?

The Connection interface has methods like commit(), rollback() that are responsible for transaction management in JDBC.

357. What is batch processing and how to perform batch processing in JDBC?

Batch processing is the process to execute multiple queries at once in a batch and hence results in after performance. Statement and PreparedStatement contain methods that support batch processing. Below are the steps to perform batch processing:

  • Load the driver class
  • Create a connection
  • Create a statement
  • Add queries in the batch
  • Execute the batch
  • Close the connection
import java.sql.*;
public class BatchProcessing {

  public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
    c.setAutoCommit(false);
    
    Statement s = c.createStatement();
    
    //Add queries to the batch
    s.addBatch("insert into employees value(111,'Akash')");
    s.addBatch("insert into employees value(222,'Bharat')");
    
    //Execute the batch
    s.executeBatch();
    
    c.commit();
    c.close();

  }

}

358. What are CLOB and BLOB data types in JDBC?

BLOB stands for Binary Large Object and stores binary data such as voice, image, and mixed media in the database. It can be used in databases like MySQL, Oracle, DB2. It can hold up to 3GB data in MySQL and 128GB on the Oracle database.

CLOB stands for Character Large Object and stores character-based data like files in the database. It is considered as a character string. It can hold up to 2GB on MySQL and 128GB on the Oracle database.

359. What are the different types of lockings in JDBC?

A lock is a mechanism that prevents other users from using particular resources. Below are the different types of locks in JDBC:

  • Row and key locks: It is used when we update the rows in the data table.
  • Page locks: It is used to lock the page especially when some transaction is still in process on that particular page. It locks the entire page that uses the row for updating, deleting, or insertion of data.
  • Table locks: It is used to lock the table. There are two types of table locks like shared and exclusive. A shared lock allows us to read the table but prevents updates. An exclusive lock prevents both reading and writing.
  • Database locks: It locks the database and prevents read and update operations of other transactions when the database is open.

360. How to store and retrieve images from the database?

Create a table with two columns as NAME and PHOTO.

CREATE TABLE "IMAGETABLE"("NAME" VARCHAR2(1000), "PHOTO" BLOB)

Using PreparedStatement we can store and retrieve the images from the database. Below is the code to store the image.

import java.sql.*;
import java.io.*;
public class StoreImage{

  public static void main(String[] args) {
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");
      
      PreparedStatement p = c.prepareStatement("insert into imagetable(?,?)");
      p.setString(1, "Ravi");
      
      FileInputStream f = new FileInputStream("C:\\photo.jpg");
      p.setBinaryStream(2, f, f.available());
      
      //Store the image
      int i = p.executeUpdate();
      System.out.println(i + " row is affected");
      
      c.close();
      
    }
    catch(Exception e) {
      e.printStackTrace();
    }
    

  }

}

Below is the code to retrieve the image from the database.

import java.sql.*;
import java.io.*;
public class ImageRetrieval {

  public static void main(String[] args) {
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");
      
      PreparedStatement p = c.prepareStatement("select * from imagetable");
      ResultSet r = p.executeQuery();
      
      if(r.next()) {
        Blob b = r.getBlob(2); //Retrieve 2nd column data since image is in 2nd column
        byte[] barr = b.getBytes(1, (int)b.length()); //1 denotes 1st image
        
        FileOutputStream f = new FileOutputStream("C:\\newphoto.jpg");
        f.write(barr);
        
        f.close();
      }
      System.out.println("Image retrieved");
      
      c.close();
      
    }
    catch(Exception e) {
      e.printStackTrace();
    }

  }

}

361. How to store files in the Oracle database?

We can use the CLOB datatype to store files in the database using the PreparedStatement.

Below is the code to create a table with 2 columns ID and NAME

CREATE TABLE FILETABLE("ID" NUMBER, "NAME" CLOB)

Below is the code to store the file in the database.

import java.sql.*;
import java.io.*;

public class StoreFile {

  public static void main(String[] args) {
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");
      
      PreparedStatement p = c.prepareStatement("insert into filetablevalues(?,?)");
      
      File f = new File("D:\\File1.txt");
      FileReader fr = new FileReader(f);
      
      p.setInt(1, 100);
      p.setCharacterStream(2, fr, (int)f.length());
      
      int i = p.executeUpdate();
      System.out.println(i + " row is affected");
      
      c.close();
      
    }
    catch(Exception e) {
      e.printStackTrace();
    }

  }

}

362. How to retrieve files from an Oracle database?

We can use the getClob() method of the PreparedStatement to retrieve files from the database.

Below is the table which we have created.

CREATE TABLE FILETABLE("ID" NUMBER, "NAME" CLOB)

Below is the code to retrieve the file from the database.

import java.io.*;
import java.sql.*;
public class FileRetrieval {

  public static void main(String[] args) {
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");
      
      PreparedStatement p = c.prepareStatement("select * from filetable");
      
      ResultSet r = p.executeQuery();
      r.next(); //Points to the first row
      
      Clob clob = r.getClob(2); //2 denotes the 2nd column that contains the file
      Reader reader = clob.getCharacterStream();
      
      FileWriter f = new FileWriter("D:\\File2.txt");
      int i;
      while((i=reader.read())!= -1) {
        f.write((char)i);
      }
      f.close();
      c.close();
      
      System.out.println("File Retrieved");
    }
    catch(Exception e) {
      e.printStackTrace();
    }

  }

}

363. What are the differences between stored procedures and functions?

Stored procedureFunctions
Performs business logicPerforms calculations
It is optional to have a return typeIt is mandatory to have a return type
It supports input and output parametersSupports only input parameters
It can return 0 or many valuesIt can return only 1 value
Procedures cannot be called from functionFunction can be called from a procedure
Procedure allows SELECT and DML statements(INSERT,UPDATE,DELETE)Function allows only SELECT statement

364. How to maintain the integrity of the database using JDBC?

We can maintain the integrity of the database by ensuring the ACID properties. ACID stands for Atomicity, Consistency, Isolation, and durability. We can manage the transactions by using the methods like setAutoCommit(), commit(), rollback() which is present in the Connection interface.

import java.sql.*;
public class IntegrityDemo {

  public static void main(String[] args) throws Exception{
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");
    
    c.setAutoCommit(false);
    
    Statement s = c.createStatement();
    s.executeUpdate("insert into employees values(111,'Ravi')");
    s.executeUpdate("insert into employees values(222,'Abhishek')");
    
    c.commit();
    c.close();

  }

}

365. What is JDBC RowSet?

JDBC RowSet is a wrapper of the ResultSet.It can hold tabular data like the ResultSet and is easy to use. The implementation classes of the RowSet interface are:

  • JdbcRowSet
  • CachedRowSet
  • WebRowSet
  • JoinRowSet
  • FilteredRowSet

366. What is the difference between java.util.Date and java.sql.Date?

The major difference is that java.sql.Date represents only Date information without time and java.util.Date represents both Date and time information.

367. What is JDBC setMaxRows method?

The setMaxRows() method limits the number of rows the database can return by using the query.

 

Translate ยป