Java Interview Questions | 4 | -Interview of Geeks

Core java Interview Questions Interview Questions | 4

151-200 out of 300 Questions

There is the list of 300 core Java interview questions. If there is any core Java interview question that has been asked to you, kindly post it in the ask question section. We assure that you will get here the 90% frequently asked interview questions and answers.

The answers to the Core Java interview questions are short and to the point. The core Java interview questions are categorized in Basics of Java interview questions, OOPs interview questions, String Handling interview questions, Multithreading interview questions, collection interview questions, JDBC interview questions, etc.

  1. 151. Why are the objects immutable in java?

    Because Java uses the concept of the string literal. Suppose there are five reference variables, all refer to one object "sachin". If one reference variable changes the value of the object, it will be affected by all the reference variables. That is why string objects are immutable in java.

  2. 152. How many ways can we create the string object?
    1. String Literal

      Java String literal is created by using double quotes. For Example:

      String s="welcome";

      Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. String objects are stored in a special memory area known as the string constant pool For example:

      String s1="Welcome";
      String s2="Welcome";//It doesn't create a new instance
    2. By new keyword

      String s=new String("Welcome");//creates two objects and one reference variable

      In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the constant string pool. The variable s will refer to the object in a heap (non-pool).

  3. 153. How many objects will be created in the following code?
    String s1="Welcome";
    String s2="Welcome";
    String s3="Welcome";

    Only one object will be created using the above code because strings in Java are immutable.

  4. 154. Why java uses the concept of the string literal?

    To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).

  5. 155. How many objects will be created in the following code?
    String s = new String("Welcome");

    Two objects, one in string constant pool and other in non-pool(heap).

  6. 156. What is the output of the following Java program?
    public class Test

    public static void main (String args[])
    String a = new String("Sharma is a good player");
    String b = "Sharma is a good player";
    if(a == b)
    System.out.println("a == b");
    System.out.println("a equals b");


    a equals b
  7. 157. What is the output of the following Java program?
    public class Test
    public static void main (String args[])
    String s1 = "Sharma is a good player";
    String s2 = new String("Sharma is a good player");
    s2 = s2.intern();
    System.out.println(s1 ==s2);


  8. 158. What are the differences between String and StringBuffer?

    The differences between the String and StringBuffer is given in the table below.

    String StringBuffer
    1) The String class is immutable. The StringBuffer class is mutable.
    2) The String is slow and consumes more memory when you concat too many strings because every time it creates a new instance. The StringBuffer is fast and consumes less memory when you cancat strings.
    3) The String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. The StringBuffer class doesn't override the equals() method of Object class.

  9. 159. What are the differences between StringBuffer and StringBuilder?

    The differences between the StringBuffer and StringBuilder is given below.

    StringBuffer StringBuilder
    1) StringBuffer is synchronized, i.e., thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized,i.e., not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
    2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.

  10. 160. How can we create an immutable class in Java?

    We can create an immutable class by defining a final class having all of its members as final. Consider the following example.

    public final class Employee{
    final String pancardNumber;

    public Employee(String pancardNumber){

    public String getPancardNumber(){
    return pancardNumber;


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

    The toString() method returns the string representation of an object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object, etc. depending upon your implementation. By overriding the toString() method of the Object class, we can return the values of the object, so we don't need to write much code. Consider the following example.

    class Student{
    int rollno;
    String name;
    String city;

    Student(int rollno, String name, String city){

    public String toString(){//overriding the toString() method
    return rollno+" "+name+" "+city;
    public static void main(String args[]){
    Student s1=new Student(101,"Raj","lucknow");
    Student s2=new Student(102,"Vijay","ghaziabad");

    System.out.println(s1);//compiler writes here s1.toString()
    System.out.println(s2);//compiler writes here s2.toString()


    101 Raj lucknow
    102 Vijay ghaziabad

  12. 162. Why CharArray() is preferred over String to store the password?

    String stays in the string pool until the garbage is collected. If we store the password into a string, it stays in the memory for a longer period, and anyone having the memory-dump can extract the password as clear text. On the other hand, Using CharArray allows us to set it to blank whenever we are done with the password. It avoids the security threat with the string by enabling us to control the memory.

  13. 163. Write a Java program to count the number of words present in a string?


    public class Test
    public static void main (String args[])
    String s = "Sharma is a good player and he is so punctual";
    String words[] = s.split(" ");
    System.out.println("The Number of words present in the string are : "+words.length);


    The Number of words present in the string are : 10
  14. 164. Name some classes present in java.util.regex package.

    There are the following classes and interfaces present in java.util.regex package.

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

  15. 165. How the metacharacters are different from the ordinary characters?

    Metacharacters have the special meaning to the regular expression engine. The metacharacters are ^, $, ., *, +, etc. The regular expression engine does not consider them as the regular characters. To enable the regular expression engine treating the metacharacters as ordinary characters, we need to escape the metacharacters with the backslash.

  16. 166. Write a regular expression to validate a password. A password must start with an alphabet and followed by alphanumeric characters; Its length must be in between 8 to 20.

    The regular expression for the above criteria will be: ^[a-zA-Z][a-zA-Z0-9]{8,19} where ^ represents the start of the regex, [a-zA-Z] represents that the first character must be an alphabet, [a-zA-Z0-9] represents the alphanumeric character, {8,19} represents that the length of the password must be in between 8 and 20.

  17. 167. What is the output of the following Java program?
    import java.util.regex.*;
    class RegexExample2{
    public static void main(String args[]){
    System.out.println(Pattern.matches(".s", "as")); //line 4
    System.out.println(Pattern.matches(".s", "mk")); //line 5
    System.out.println(Pattern.matches(".s", "mst")); //line 6
    System.out.println(Pattern.matches(".s", "amms")); //line 7
    System.out.println(Pattern.matches("..s", "mas")); //line 8



  18. Core Java: Nested classes and Interfaces Interview Questions

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

    There are two types of advantages of Java inner classes.

    • Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of the outer class including private.
    • Nested classes are used to develop a more readable and maintainable code because it logically groups classes and interfaces in one place only.
    • Code Optimization: It requires less code to write.

  20. 169. What is a nested class?

    The nested class can be defined as the class which is defined inside another class or interface. We use the nested class to logically group classes and interfaces in one place so that it can be more readable and maintainable. A nested class can access all the data members of the outer class including private data members and methods. The syntax of the nested class is defined below.

    class Java_Outer_class{
    class Java_Nested_class{

  21. 170. What are the disadvantages of using inner classes?

    There are the following main disadvantages of using inner classes.

    • Inner classes increase the total number of classes used by the developer and therefore increases the workload of JVM since it has to perform some routine operations for those extra classes which result in slower performance.
    • IDEs provide less support to the inner classes as compare to the top level classes and therefore it annoys the developers while working with inner classes.

  22. 171. What are the types of inner classes (non-static nested class) used in Java?

    There are mainly three types of inner classes used in Java.

    Type Description
    1) Member Inner Class A class created within class and outside method.
    2) Anonymous Inner Class A class created for implementing an interface or extending class. Its name is decided by the java compiler.
    3) Local Inner Class A class created within the method.

  23. 172. Is there any difference between nested classes and inner classes?

    Yes, inner classes are non-static nested classes. In other words, we can say that inner classes are the part of nested classes.

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

    No, the local variable must be constant if you want to access it in the local inner class.

  25. 174. How many class files are created on compiling the OuterClass in the following program?
    public class Person {
    String name, age, address;
    class Employee{
    float salary=10000;
    class BusinessMen{
    final String gstin="£4433drt3$";
    public static void main (String args[])
    Person p = new Person();

    3 class-files will be created named as Person.class, Person$BusinessMen.class, and Person$Employee.class.

  26. 175. What are anonymous inner classes?

    Anonymous inner classes are the classes that are automatically declared and instantiated within an expression. We cannot apply different access modifiers to them. Anonymous class cannot be static, and cannot define any static fields, method, or class. In other words, we can say that it a class without the name and can have only one object that is created by its definition. Consider the following example.

    abstract class Person{
    abstract void eat();
    class TestAnonymousInner{
    public static void main(String args[]){
    Person p=new Person(){
    void eat(){System.out.println("nice fruits");}


    nice fruits

    Consider the following example for the working of the anonymous class using interface.

    interface Eatable{
    void eat();
    class TestAnnonymousInner1{
    public static void main(String args[]){
    Eatable e=new Eatable(){
    public void eat(){System.out.println("nice fruits");}


    nice fruits

  27. 176. What is the nested interface?

    An Interface that is declared inside the interface or class is known as the nested interface. It is static by default. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The external interface or class must refer to the nested interface. It can't be accessed directly. The nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class. The syntax of the nested interface is given as follows.

    interface interface_name{
    interface nested_interface_name{

  28. 177. Can a class have an interface?

    Yes, an interface can be defined within the class. It is called a nested interface.

  29. 178. Can an Interface have a class?

    Yes, they are static implicitly.

  30. Java: Exception Handling Interview Questions

  31. 179. What is Garbage Collection?

    Garbage collection is a process of reclaiming the unused runtime objects. It is performed for memory management. In other words, we can say that It is the process of removing unused objects from the memory to free up space and make this space available for Java Virtual Machine. Due to garbage collection java gives 0 as output to a variable whose value is not set, i.e., the variable has been defined but not initialized. For this purpose, we were using free() function in the C language and delete() in C++. In Java, it is performed automatically. So, java provides better memory management.

  32. 180. What is gc()?

    The gc() method is used to invoke the garbage collector for cleanup processing. This method is found in System and Runtime classes. This function explicitly makes the Java Virtual Machine free up the space occupied by the unused objects so that it can be utilized or reused. Consider the following example for the better understanding of how the gc() method invoke the garbage collector.

    public class TestGarbage1{
    public void finalize(){System.out.println("object is garbage collected");}
    public static void main(String args[]){
    TestGarbage1 s1=new TestGarbage1();
    TestGarbage1 s2=new TestGarbage1();


    object is garbage collected
    object is garbage collected

  33. 181. How is garbage collection controlled?

    Garbage collection is managed by JVM. It is performed when there is not enough space in the memory and memory is running low. We can externally call the System.gc() for the garbage collection. However, it depends upon the JVM whether to perform it or not.

  34. 182. How can an object be unreferenced?

    There are many ways:

    • By nulling the reference
    • By assigning a reference to another
    • By anonymous object etc.

    1. By nulling a reference:

      Employee e=new Employee();

    2. By assigning a reference to another:

      Employee e1=new Employee();
      Employee e2=new Employee();
      e1=e2;//now the first object referred by e1 is available for garbage collection

    3. By anonymous object:

      new Employee();

  35. 183. What is the purpose of the finalize() method?

    The finalize() method is invoked just before the object is garbage collected. It is used to perform cleanup processing. The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created an object without new, you can use the finalize method to perform cleanup processing (destroying remaining objects). The cleanup processing is the process to free up all the resources, network which was previously used and no longer needed. It is essential to remember that it is not a reserved keyword, finalize method is present in the object class hence it is available in every class as object class is the superclass of every class in java. Here, we must note that neither finalization nor garbage collection is guaranteed. Consider the following example.

    public class FinalizeTest {
    int j=12;
    void add()
    public void finalize()
    System.out.println("Object is garbage collected");
    public static void main(String[] args) {
    new FinalizeTest().add();
    new FinalizeTest().add();

  36. 184. Can an unreferenced object be referenced again?


  37. 185.What kind of thread is the Garbage collector thread?

    Daemon thread.

  38. 186. What is the difference between final, finally and finalize?
    final finally finalize
    1) Final is used to apply restrictions on class, method, and variable. The final class can't be inherited, final method can't be overridden, and final variable value can't be changed. Finally is used to place important code, it will be executed whether an exception is handled or not. Finalize is used to perform clean up processing just before an object is garbage collected.
    2) Final is a keyword. Finally is a block. Finalize is a method.

  39. 187. What is the purpose of the Runtime class?

    Java Runtime class is used to interact with a java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory, etc. There is only one instance of java.lang.Runtime class is available for one java application. The Runtime.getRuntime() method returns the singleton instance of Runtime class.

  40. 188. How will you invoke any external process in Java?

    By Runtime.getRuntime().exec(?) method. Consider the following example.

    public class Runtime1{
    public static void main(String args[])throws Exception{
    Runtime.getRuntime().exec("notepad");//will open a new notepad

  41. I/O Interview Questions

  42. 189. Give the hierarchy of InputStream and OutputStream classes.

    OutputStream Hierarchy

    Java output stream hierarchy

    InputStream Hierarchy

    Java input stream hierarchy
  43. 190. What do you understand by an IO stream?

    The stream is a sequence of data that flows from source to destination. It is composed of bytes. In Java, three streams are created for us automatically.

    • System.out: standard output stream
    • standard input stream
    • System.err: standard error stream

  44. 191. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

    The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. The ByteStream classes are used to perform input-output of 8-bit bytes whereas the CharacterStream classes are used to perform the input/output for the 16-bit Unicode system. There are many classes in the ByteStream class hierarchy, but the most frequently used classes are FileInputStream and FileOutputStream. The most frequently used classes CharacterStream class hierarchy is FileReader and FileWriter.

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

    All the stream classes can be divided into two types of classes that are ByteStream classes and CharacterStream Classes. The ByteStream classes are further divided into InputStream classes and OutputStream classes. CharacterStream classes are also divided into Reader classes and Writer classes. The SuperMost classes for all the InputStream classes is and for all the output stream classes is Similarly, for all the reader classes, the super-most class is, and for all the writer classes, it is

  46. 193. What are the FileInputStream and FileOutputStream?

    Java FileOutputStream is an output stream used for writing data to a file. If you have some primitive values to write into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through the FileOutputStream class. However, for character-oriented data, it is preferred to use FileWriter than FileOutputStream. Consider the following example of writing a byte into a file.

    public class FileOutputStreamExample {
    public static void main(String args[]){
    FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
    }catch(Exception e){System.out.println(e);}

    Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video, etc. You can also read character-stream data. However, for reading streams of characters, it is recommended to use FileReader class. Consider the following example for reading bytes from a file.

    public class DataStreamExample {
    public static void main(String args[]){
    FileInputStream fin=new FileInputStream("D:\\testout.txt");

    }catch(Exception e){System.out.println(e);}

  47. 194. What is the purpose of using BufferedInputStream and BufferedOutputStream classes?

    Java BufferedOutputStream class is used for buffering an output stream. It internally uses a buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast. Whereas, Java BufferedInputStream class is used to read information from the stream. It internally uses the buffer mechanism to make the performance fast.

  48. 195. How to set the Permissions to a file in Java?

    In Java, FilePermission class is used to alter the permissions set on a file. Java FilePermission class contains the permission related to a directory or file. All the permissions are related to the path. The path can be of two types:

    • D:\\IO\\-: It indicates that the permission is associated with all subdirectories and files recursively.
    • D:\\IO\\*: It indicates that the permission is associated with all directory and files within this directory excluding subdirectories.

    Let's see the simple example in which permission of a directory path is granted with read permission and a file of this directory is granted for write permission.

    package com.javatpoint;
    public class FilePermissionExample{
    public static void main(String[] args) throws IOException {
    String srg = "D:\\IO Package\\java.txt";
    FilePermission file1 = new FilePermission("D:\\IO Package\\-", "read");
    PermissionCollection permission = file1.newPermissionCollection();
    FilePermission file2 = new FilePermission(srg, "write");
    if(permission.implies(new FilePermission(srg, "read,write"))) {
    System.out.println("Read, Write permission is granted for the path "+srg );
    }else {
    System.out.println("No Read, Write permission is granted for the path "+srg); }


    Read, Write permission is granted for the path D:\IO Package\java.txt

  49. 196. What are FilterStreams?

    FilterStream classes are used to add additional functionalities to the other stream classes. FilterStream classes act like an interface which read the data from a stream, filters it, and pass the filtered data to the caller. The FilterStream classes provide extra functionalities like adding line numbers to the destination file, etc.

  50. 197. What is an I/O filter?

    An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. Many Filter classes that allow a user to make a chain using multiple input streams. It generates a combined effect on several filters.

  51. 198. In Java, How many ways you can take input from the console?

    In Java, there are three ways by using which, we can take input from the console.

    • Using BufferedReader class: we can take input from the console by wrapping into an InputStreamReader and passing it into the BufferedReader. It provides an efficient reading as the input gets buffered. Consider the following example.
      public class Person
      public static void main(String[] args) throws IOException
      System.out.println("Enter the name of the person");
      BufferedReader reader = new BufferedReader(new InputStreamReader(;
      String name = reader.readLine();
    • Using Scanner class: The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default. It provides many methods to read and parse various primitive values. Java Scanner class is widely used to parse text for string and primitive types using a regular expression. Java Scanner class extends Object class and implements Iterator and Closeable interfaces. Consider the following
      import java.util.*;
      public class ScannerClassExample2 {
      public static void main(String args[]){
      String str = "Hello/This is JavaTpoint/My name is Abhishek.";
      //Create scanner with the specified String Object
      Scanner scanner = new Scanner(str);
      System.out.println("Boolean Result: "+scanner.hasNextBoolean());
      //Change the delimiter of this scanner
      //Printing the tokenized Strings
      System.out.println("---Tokenizes String---");
      //Display the new delimiter
      System.out.println("Delimiter used: " +scanner.delimiter());
    • Using Console class: The Java Console class is used to get input from the console. It provides methods to read texts and passwords. If you read the password using the Console class, it will not be displayed to the user. The class is attached to the system console internally. The Console class is introduced since 1.5. Consider the following example.
      class ReadStringTest{
      public static void main(String args[]){
      Console c=System.console();
      System.out.println("Enter your name: ");
      String n=c.readLine();
      System.out.println("Welcome "+n);

  52. Serialization Interview Questions

  53. 199. What is serialization?

    Serialization in Java is a mechanism of writing the state of an object into a byte stream. It is used primarily in Hibernate, RMI, JPA, EJB and JMS technologies. It is mainly used to travel object's state on the network (which is known as marshaling). Serializable interface is used to perform serialization. It is helpful when you require to save the state of a program to storage such as the file. At a later point of time, the content of this file can be restored using deserialization. It is also required to implement RMI(Remote Method Invocation). With the help of RMI, it is possible to invoke the method of a Java object on one machine to another machine.

  54. 200. How can you make a class serializable in Java?

    A class can become serializable by implementing the Serializable interface.

Last Updated:

Trending Technologies Interview Questions

@InterviewofGeeks, Some rights reserved.