Java Interview Questions | 5 | -Interview of Geeks

Core java Interview Questions Interview Questions | 5

201-250 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. 201. How can you avoid serialization in child class if the base class is implementing the Serializable interface?

    It is very tricky to prevent serialization of child class if the base class is intended to implement the Serializable interface. However, we cannot do it directly, but the serialization can be avoided by implementing the writeObject() or readObject() methods in the subclass and throw NotSerializableException from these methods. Consider the following example.

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.NotSerializableException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    class Person implements Serializable
    {
    String name = " ";
    public Person(String name)
    {
    this.name = name;
    }
    }
    class Employee extends Person
    {
    float salary;
    public Employee(String name, float salary)
    {
    super(name);
    this.salary = salary;
    }
    private void writeObject(ObjectOutputStream out) throws IOException
    {
    throw new NotSerializableException();
    }
    private void readObject(ObjectInputStream in) throws IOException
    {
    throw new NotSerializableException();
    }
    }
    public class Test
    {
    public static void main(String[] args)
    throws Exception
    {
    Employee emp = new Employee("Sharma", 10000);

    System.out.println("name = " + emp.name);
    System.out.println("salary = " + emp.salary);
    FileOutputStream fos = new FileOutputStream("abc.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeObject(emp);

    oos.close();
    fos.close();
    System.out.println("Object has been serialized");

    FileInputStream f = new FileInputStream("ab.txt");
    ObjectInputStream o = new ObjectInputStream(f);

    Employee emp1 = (Employee)o.readObject();

    o.close();
    f.close();

    System.out.println("Object has been deserialized");

    System.out.println("name = " + emp1.name);
    System.out.println("salary = " + emp1.salary);
    }
    }

  2. 202. Can a Serialized object be transferred via network?

    Yes, we can transfer a serialized object via network because the serialized object is stored in the memory in the form of bytes and can be transmitted over the network. We can also write the serialized object to the disk or the database.


  3. 203. What is Deserialization?

    Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

    import java.io.*;
    class Depersist{
    public static void main(String args[])throws Exception{

    ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
    Student s=(Student)in.readObject();
    System.out.println(s.id+" "+s.name);

    in.close();
    }
    }

    Output

    211 ravi
  4. 204. What is the transient keyword?

    If you define any data member as transient, it will not be serialized. By determining transient keyword, the value of variable need not persist when it is restored.


  5. 205. What is Externalizable?

    The Externalizable interface is used to write the state of an object into a byte stream in a compressed format. It is not a marker interface.


  6. 206. What is the difference between Serializable and Externalizable interface?
    Serializable Externalizable
    1) The Serializable interface does not have any method, i.e., it is a marker interface. The Externalizable interface contains is not a marker interface, It contains two methods, i.e., writeExternal() and readExternal().
    2) It is used to "mark" Java classes so that objects of these classes may get the certain capability. The Externalizable interface provides control of the serialization logic to the programmer.
    3) It is easy to implement but has the higher performance cost. It is used to perform the serialization and often result in better performance.
    4) No class constructor is called in serialization. We must call a public default constructor while using this interface.

  7. Networking Interview Questions

  8. 207. Give a brief description of Java socket programming?

    Java Socket programming is used for communication between the applications running on different JRE. Java Socket programming can be connection-oriented or connectionless. Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket, and DatagramPacket classes are used for connectionless socket programming. The client in socket programming must know two information:

    • IP address of the server
    • port number

  9. 208. What is Socket?

    A socket is simply an endpoint for communications between the machines. It provides the connection mechanism to connect the two computers using TCP. The Socket class can be used to create a socket.


  10. 209. What are the steps that are followed when two computers connect through TCP?

    There are the following steps that are performed when two computers connect through TCP.

    • The ServerSocket object is instantiated by the server which denotes the port number to which, the connection will be made.
    • After instantiating the ServerSocket object, the server invokes accept() method of ServerSocket class which makes server wait until the client attempts to connect to the server on the given port.
    • Meanwhile, the server is waiting, a socket is created by the client by instantiating Socket class. The socket class constructor accepts the server port number and server name.
    • The Socket class constructor attempts to connect with the server on the specified name. If the connection is established, the client will have a socket object that can communicate with the server.
    • The accept() method invoked by the server returns a reference to the new socket on the server that is connected with the server.

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

    Consider the following program where the connection between the client and server is established.

    File: MyServer.java

    import java.io.*;
    import java.net.*;
    public class MyServer {
    public static void main(String[] args){
    try{
    ServerSocket ss=new ServerSocket(6666);
    Socket s=ss.accept();//establishes connection
    DataInputStream dis=new DataInputStream(s.getInputStream());
    String str=(String)dis.readUTF();
    System.out.println("message= "+str);
    ss.close();
    }catch(Exception e){System.out.println(e);}
    }
    }

    File: Myclient.java

    import java.io.*;
    import java.net.*;
    public class MyClient {
    public static void main(String[] args) {
    try{
    Socket s=new Socket("localhost",6666);
    DataOutputStream dout=new DataOutputStream(s.getOutputStream());
    dout.writeUTF("Hello Server");
    dout.flush();
    dout.close();
    s.close();
    }catch(Exception e){System.out.println(e);}
    }
    }

  12. 211. How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?

    By InetAddress.getByName("192.18.97.39").getHostName() where 192.18.97.39 is the IP address. Consider the following example

    import java.io.*;
    import java.net.*;
    public class InetDemo{
    public static void main(String[] args){
    try{
    InetAddress ip=InetAddress.getByName("195.201.10.8");

    System.out.println("Host Name: "+ip.getHostName());
    }catch(Exception e){System.out.println(e);}
    }
    }

  13. Reflection Interview Questions

  14. 212. What is the reflection?

    Reflection is the process of examining or modifying the runtime behavior of a class at runtime. The java.lang.Class class provides various methods that can be used to get metadata, examine and change the runtime behavior of a class. The java.lang and java.lang.reflect packages provide classes for java reflection. It is used in:

    • IDE (Integrated Development Environment), e.g., Eclipse, MyEclipse, NetBeans.
    • Debugger
    • Test Tools, etc.

  15. 213. What is the purpose of using java.lang.Class class?

    The java.lang.Class class performs mainly two tasks:

    • Provides methods to get the metadata of a class at runtime.
    • Provides methods to examine and change the runtime behavior of a class.

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

    There are three ways to instantiate the Class class.

    • forName() method of Class class: The forName() method is used to load the class dynamically. It returns the instance of Class class. It should be used if you know the fully qualified name of the class. This cannot be used for primitive types.
    • getClass() method of Object class: It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives.
    • the .class syntax: aIf a type is available, but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type. It can be used for primitive data type also.

  17. 215. What is the output of the following Java program?
    class Simple{
    public Simple()
    {
    System.out.println("Constructor of Simple class is invoked");
    }
    void message(){System.out.println("Hello Java");}
    }

    class Test1{
    public static void main(String args[]){
    try{
    Class c=Class.forName("Simple");
    Simple s=(Simple)c.newInstance();
    s.message();
    }catch(Exception e){System.out.println(e);}
    }
    }

    Output

    Constructor of Simple class is invoked
    Hello Java

  18. 216. What is the purpose of using javap?

    The javap command disassembles a class file. The javap command displays information about the fields, constructors and methods present in a class file.


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

    Yes, by changing the runtime behavior of a class if the class is not secured.


  20. Miscellaneous Interview Questions

  21. 218. What are wrapper classes?

    Wrapper classes are classes that allow primitive types to be accessed as objects. In other words, we can say that wrapper classes are built-in java classes which allow the conversion of objects to primitives and primitives to objects. The process of converting primitives to objects is called autoboxing, and the process of converting objects to primitives is called unboxing. There are eight wrapper classes present in java.lang package is given below.

    Primitive Type Wrapper class
    boolean Boolean
    char Character
    byte Byte
    short Short
    int Integer
    long Long
    float Float
    double Double

  22. 219. What are autoboxing and unboxing? When does it occur?

    The autoboxing is the process of converting primitive data type to the corresponding wrapper class object, eg., int to Integer. The unboxing is the process of converting wrapper class object to primitive data type. For eg., integer to int. Unboxing and autoboxing occur automatically in Java. However, we can externally convert one into another by using the methods like valueOf() or xxxValue().

    It can occur whenever a wrapper class object is expected, and primitive data type is provided or vice versa.

    • Adding primitive types into Collection like ArrayList in Java.
    • Creating an instance of parameterized classes ,e.g., ThreadLocal which expect Type.
    • Java automatically converts primitive to object whenever one is required and another is provided in the method calling.
    • When a primitive type is assigned to an object type.

  23. 220. What is the output of the below Java program?
    public class Test1
    {
    public static void main(String[] args) {
    Integer i = new Integer(201);
    Integer j = new Integer(201);
    if(i == j)
    {
    System.out.println("hello");
    }
    else
    {
    System.out.println("bye");
    }
    }
    }

    Output

    bye
  24. 221. What is object cloning?

    The object cloning is a way to create an exact copy of an object. The clone() method of the Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException. The clone() method is defined in the Object class. The syntax of the clone() method is as follows:

    protected Object clone() throws CloneNotSupportedException


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

    Advantage of Object Cloning

    • You don't need to write lengthy and repetitive codes. Just use an abstract class with a 4- or 5-line long clone() method.
    • It is the easiest and most efficient way of copying objects, especially if we are applying it to an already developed or an old project. Just define a parent class, implement Cloneable in it, provide the definition of the clone() method and the task will be done.
    • Clone() is the fastest way to copy the array.

    Disadvantage of Object Cloning

    • To use the Object.clone() method, we have to change many syntaxes to our code, like implementing a Cloneable interface, defining the clone() method and handling CloneNotSupportedException, and finally, calling Object.clone(), etc.
    • We have to implement the Cloneable interface while it does not have any methods in it. We have to use it to tell the JVM that we can perform a clone() on our object.
    • Object.clone() is protected, so we have to provide our own clone() and indirectly call Object.clone() from it.
    • Object.clone() does not invoke any constructor, so we do not have any control over object construction.
    • If you want to write a clone method in a child class, then all of its superclasses should define the clone() method in them or inherit it from another parent class. Otherwise, the super.clone() chain will fail.
    • Object.clone() supports only shallow copying, but we will need to override it if we need deep cloning.

  26. 223. What is a native method?

    A native method is a method that is implemented in a language other than Java. Natives methods are sometimes also referred to as foreign methods.


  27. 224. What is the purpose of the strictfp keyword?

    Java strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. The precision may differ from platform to platform that is why java programming language has provided the strictfp keyword so that you get the same result on every platform. So, now you have better control over the floating-point arithmetic.


  28. 225. What is the purpose of the System class?

    The purpose of the System class is to provide access to system resources such as standard input and output. It cannot be instantiated. Facilities provided by System class are given below.

    • Standard input
    • Error output streams
    • Standard output
    • utility method to copy the portion of an array
    • utilities to load files and libraries

    There are the three fields of Java System class, i.e., static printstream err, static inputstream in, and standard output stream.


  29. 226. What comes to mind when someone mentions a shallow copy in Java?

    Object cloning.


  30. 227. What is a singleton class?

    Singleton class is the class which can not be instantiated more than once. To make a class singleton, we either make its constructor private or use the static getInstance method. Consider the following example.

    class Singleton{
    private static Singleton single_instance = null;
    int i;
    private Singleton ()
    {
    i=90;
    }
    public static Singleton getInstance()
    {
    if(single_instance == null)
    {
    single_instance = new Singleton();
    }
    return single_instance;
    }
    }
    public class Main
    {
    public static void main (String args[])
    {
    Singleton first = Singleton.getInstance();
    System.out.println("First instance integer value:"+first.i);
    first.i=first.i+90;
    Singleton second = Singleton.getInstance();
    System.out.println("Second instance integer value:"+second.i);
    }
    }

  31. 228. Write a Java program that prints all the values given at command-line.

    Program

    class A{
    public static void main(String args[]){

    for(int i=0;i<args.length;i++)
    System.out.println(args[i]);

    }
    }

    Compile:

    compile by > javac A.java
    run by > java A Stephan 1 3 abc

    Output

    Stephan
    1
    3
    abc

  32. 229. Which containers use a border layout as their default layout?

    The Window, Frame and Dialog classes use a border layout as their default layout.


  33. 230. Which containers use a FlowLayout as their default layout?

    The Panel and Applet classes use the FlowLayout as their default layout.


  34. 231. What are peerless components?

    The lightweight component of Swing is called peerless components. Spring has its libraries, so it does not use resources from the Operating System, and hence it has lightweight components.


  35. 232. is there is any difference between a Scrollbar and a ScrollPane?

    The Scrollbar is a Component whereas the ScrollPane is a Container. A ScrollPane handles its events and performs its scrolling.


  36. 233. What is a lightweight component?

    Lightweight components are the one which does not go with the native call to obtain the graphical units. They share their parent component graphical units to render them. For example, Swing components, and JavaFX Components.


  37. 234. What is a heavyweight component?

    The portable elements provided by the operating system are called heavyweight components. AWT is limited to the graphical classes provided by the operating system and therefore, It implements only the minimal subset of screen elements supported by all platforms. The Operating system dependent UI discovery tools are called heavyweight components.


  38. 235.What is an applet?

    An applet is a small java program that runs inside the browser and generates dynamic content. It is embedded in the webpage and runs on the client side. It is secured and takes less response time. It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os, etc. However, the plugins are required at the client browser to execute the applet. The following image shows the architecture of Applet

    Applet hierarchy

    When an applet is created, the following methods are invoked in order.

    • init()
    • start()
    • paint()

    When an applet is destroyed, the following functions are invoked in order.

    • stop()
    • destroy()

  39. 236. Can you write a Java class that could be used both as an applet as well as an application?

    Yes. Add a main() method to the applet.


  40. Internationalization Interview Questions

  41. 237. What is Locale?

    A Locale object represents a specific geographical, political, or cultural region. This object can be used to get the locale-specific information such as country name, language, variant, etc.

    import java.util.*;
    public class LocaleExample {
    public static void main(String[] args) {
    Locale locale=Locale.getDefault();
    //Locale locale=new Locale("fr","fr");//for the specific locale

    System.out.println(locale.getDisplayCountry());
    System.out.println(locale.getDisplayLanguage());
    System.out.println(locale.getDisplayName());
    System.out.println(locale.getISO3Country());
    System.out.println(locale.getISO3Language());
    System.out.println(locale.getLanguage());
    System.out.println(locale.getCountry());

    }
    }

    Output

    United States
    English
    English (United States)
    USA
    eng
    en
    US

  42. 238. How will you load a specific locale?

    By ResourceBundle.getBundle(?) method.


  43. Java Bean Interview Questions

  44. 239. What is a JavaBean?

    JavaBean is a reusable software component written in the Java programming language, designed to be manipulated visually by a software development environment, like JBuilder or VisualAge for Java. t. A JavaBean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides the easy maintenance. Consider the following example to create a JavaBean class.

    //Employee.java
    package mypack;
    public class Employee implements java.io.Serializable{
    private int id;
    private String name;
    public Employee(){}
    public void setId(int id){this.id=id;}
    public int getId(){return id;}
    public void setName(String name){this.name=name;}
    public String getName(){return name;}
    }

  45. 240. What is the purpose of using the Java bean?

    According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides the easy maintenance.


  46. 241. What do you understand by the bean persistent property?

    The persistence property of Java bean comes into the act when the properties, fields, and state information are saved to or retrieve from the storage.


  47. RMI Interview Questions

  48. 242. What is RMI?

    The RMI (Remote Method Invocation) is an API that provides a mechanism to create the distributed application in java. The RMI allows an object to invoke methods on an object running in another JVM. The RMI provides remote communication between the applications using two objects stub and skeleton.


  49. 243. What is the purpose of stub and skeleton?

    Stub

    The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it. It resides at the client side and represents the remote object. When the caller invokes the method on the stub object, it does the following tasks:

    • It initiates a connection with remote Virtual Machine (JVM).
    • It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM).
    • It waits for the result.
    • It reads (unmarshals) the return value or exception.
    • It finally, returns the value to the caller.

    Skeleton

    The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are routed through it. When the skeleton receives the incoming request, it does the following tasks:

    • It reads the parameter for the remote method.
    • It invokes the method on the actual remote object.
    • It writes and transmits (marshals) the result to the caller.

  50. 244. What are the steps involved to write RMI based programs?

    There are 6 steps which are performed to write RMI based programs.

    • Create the remote interface.
    • Provide the implementation of the remote interface.
    • Compile the implementation class and create the stub and skeleton objects using the rmic tool.
    • Start the registry service by the rmiregistry tool.
    • Create and start the remote application.
    • Create and start the client application.

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

    HTTP tunneling can be defined as the method which doesn't need any setup to work within the firewall environment. It handles the HTTP connections through the proxy servers. However, it does not allow outbound TCP connections.


  52. 246. What is JRMP?

    JRMP (Java Remote Method Protocol) can be defined as the Java-specific, stream-based protocol which looks up and refers to the remote objects. It requires both client and server to use Java objects. It is wire level protocol which runs under RMI and over TCP/IP.


  53. 247. Can RMI and CORBA based applications interact?

    Yes, they can. RMI is available with IIOP as the transport protocol instead of JRMP.


  54. Core Java: Data Structure interview questions

  55. 248. How to perform Bubble Sort in Java?

    Consider the following program to perform Bubble sort in Java.

    public class BubbleSort {
    public static void main(String[] args) {
    int[] a = {10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
    for(int i=0;i < 10;i++)
    {
    for (int j=0;j < 10;j++)
    {
    if(a[i]<a[j])
    {
    int temp = a[i];
    a[i]=a[j];
    a[j] = temp;
    }
    }
    }
    System.out.println("Printing Sorted List ...");
    for(int i=0;i < 10;i++)
    {
    System.out.println(a[i]);
    }
    }
    }

    Output

    Printing Sorted List . . .
    7
    9
    10
    12
    23
    34
    34
    44
    78
    101

  56. 249. How to perform Binary Search in Java?

    Consider the following program to perform the binary search in Java.

    import java.util.*;
    public class BinarySearch {
    public static void main(String[] args) {
    int[] arr = {16, 19, 20, 23, 45, 56, 78, 90, 96, 100};
    int item, location = -1;
    System.out.println("Enter the item which you want to search");
    Scanner sc = new Scanner(System.in);
    item = sc.nextInt();
    location = binarySearch(arr,0,9,item);
    if(location != -1)
    System.out.println("the location of the item is "+location);
    else
    System.out.println("Item not found");
    }
    public static int binarySearch(int[] a, int beg, int end, int item)
    {
    int mid;
    if(end >= beg)
    {
    mid = (beg + end)/2;
    if(a[mid] == item)
    {
    return mid+1;
    }
    else if(a[mid] < item)
    {
    return binarySearch(a,mid+1,end,item);
    }
    else
    {
    return binarySearch(a,beg,mid-1,item);
    }
    }
    return -1;
    }
    }

    Output

    Enter the item which you want to search
    45
    the location of the item is 5

  57. 250. How to perform Selection Sort in Java?

    Consider the following program to perform selection sort in Java.

    public class SelectionSort {
    public static void main(String[] args) {
    int[] a = {10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
    int i,j,k,pos,temp;
    for(i=0;i < 10;i++)
    { pos = smallest(a,10,i);
    temp = a[i];
    a[i]=a[pos];
    a[pos] = temp;
    }
    System.out.println("\nprinting sorted elements...\n");
    for(i=0;i<10;i++)
    {
    System.out.println(a[i]);
    }
    }
    public static int smallest(int a[], int n, int i)
    {
    int small,pos,j;
    small = a[i];
    pos = i;
    for(j=i+1;j<10;j++)
    {
    if(a[j]<small)
    {
    small = a[j];
    pos=j;
    }
    }
    return pos;
    }
    }

    Output

    printing sorted elements...
    7
    9
    10
    12
    23
    23
    34
    44
    78
    101


Last Updated:


Trending Technologies Interview Questions


@InterviewofGeeks, Some rights reserved.