Site icon TechVidvan

Top 100 Core Java Interview Questions for Freshers

Core Java Interview Questions and answers – Your entry pass into the world of top Java Developers

This is the second part in the series of Java Interview questions. In this series, we are providing 370 Java interview questions and answers in 3 parts:

After discussing Java interview questions for beginners, in this article, we are going to provide 100 core Java interview questions and answers. These interview questions cover in-depth concepts of Java, if you are a beginner, please start with the 1st part of interview questions series.

Core Java Interview Questions

Java is being used by more than 10 Million professionals to develop applications for 15 Billion devices.

In this core Java interview questions article, we have compiled some advanced interview questions of Java as well:

We will cover all these topics and their related questions that hold a maximum possibility of being asked in interviews. So let us begin.

Core Java Interview Questions for Freshers

Q.1. What is the sleep() and wait() methods in Java?

Answer. The sleep() is a method that is used to pause the process for a few seconds or the time we want to. But in case of the wait() method, the thread goes in the waiting state and it won’t come back automatically until we call notify() or notifyAll().

The major difference is that wait() releases the lock or monitor while sleep() doesn’t release the lock or monitor while waiting. wait() is used for inter-thread communication while sleep() is used to introduce pause on execution, generally.

Q.2. Tell me something about memory management and garbage collection in Java.

Answer. Java handles both memory management and garbage collection automatically using JVM. The garbage collector periodically collects variables or objects that are no longer in use and stop referencing. It is possible for programmers to schedule garbage collection using System.gc() method, but there is still no guarantee when that will happen.

Stack and heap areas are the two most important memory areas in the JVM. The stack holds method frames and local variables and is not shared between threads. Objects are always given memory from the heap area, which is shared between all threads in the JVM. The stack area is usually much smaller than the heap memory area.

Q.3. When is it appropriate to use transient keyword with a variable in Java?

Answer. It is appropriate to use transient variables when there is a need to make a variable non-serializable in a class that implements the Serializable interface. If we want that a particular variable should not become serializable even if it is present in the class that implements the Serializable interface, then we can declare it with a transient keyword to serve the same purpose.

Q.4. How can you prevent a class from being inherited in Java?

Answer. We can prevent a class from being subclasses or inherited by another class in two ways:

  1. Making the constructor of the class as private
  2. Declaring the class with the final keyword.

Q.5. What are Generics in Java?

Answer. Generics can be used in conjunction with classes and methods. They’re used to specify a single declaration for a set of related methods, or a single class declaration for a set of related types. Generics are checked at compile-time for type safety. Two examples are ArrayList<T> and three classes representing daily, monthly, and yearly charts that extend an abstract Chart and can be specified with <? extends Chart>.

Q.6. What are the default values in an array?

Answer. By default, when we create an array of something in Java all entries will have its default value. For primitive types like int, long, float the default value is zero (0 or 0.0). For reference types (anything that holds an object in it) will have null as the default value. For boolean variables, it will be false.

Q.7. How will you loop around an array using enhanced for loop in Java?

Answer. The enhanced for loop was introduced with Java 5. This loop mainly traverses a collection of elements.

The following is the syntax of enhanced for loop:

for(declaration : expression) 
{
   //Statements
}

Example:

public static void main(String args[]) {
  int[] numbers = {
    10,
    20,
    30,
    40,
    50
  };
  for (int x: numbers) {
    System.out.print(x);
    System.out.print(",");
  }
  System.out.print("\n");
  String[] names = {
    "James",
    "Larry",
    "Tom",
    "Lacy"
  };
  for (String name: names) {
    System.out.print(name);
    System.out.print(",");
  }
}

Output:
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,

Q.8. What are asserts in Java and what is their use?

Answer. Assert in Java is a keyword that defines an assert statement. An assert statement declares an expected boolean condition in a program. If the program runs with assertions enabled, then the condition is checked at runtime. If the condition becomes false, the Java runtime system throws an AssertionError.

We generally use assertions as a debugging aid. We should not use them instead of validating arguments to public methods. We can enable Java Assertions with the Java -ea or -enable assertions runtime option.

Java Thread Interview Questions

Q.9. What is the need for threads in Java?

Answer. We need to use thread in core Java for starting a program. Thread is a lightweight process that helps in running the tasks in parallel. The threads work independently and provide the maximum utilization of the CPU, thus enhancing the CPU performance.

In one word, we use Threads to make Java applications faster by doing multiple things at the same time. The thread helps us to achieve parallelism in our Java programs. Since the CPU is very fast and nowadays it even contains multiple cores, just one thread is not able to take advantage of all the cores, which means your costly hardware will remain idle for most of the time.

Q.10. How can you create a thread in Java?

Answer. There are two ways to create threads in Java. One using the Runnable interface and another by extending the Thread class.

Runnable interface
Java program to create a thread by implementing the Runnable interface.

public class DemoRunnable implements Runnable {
  public void run() {
    //Code
  }
}

//start new thread with a “new Thread(new demoRunnable()).start()” call

Q.11. What are the different states of a thread in Java?

Answer. A Java thread can be in any of the following thread states during its life cycle i.e. New, Runnable, Blocked, Waiting, Timed Waiting, or Terminated. These are also called life cycle events of a thread in Java.

Threads exist in several states:

Q.12. Can we start a thread twice?

Answer. No, we can not start a thread again after starting a thread. If we attempt to do so, then there is an IllegalThreadStateException.
Let’s understand it with an example:

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

Output:
Running
Exception in thread “main” java.lang.IllegalThreadStateException

Q.13. What is the use of notify() method in Java?

Answer. The notify() method of thread class wakes up a single thread. The notify() method gives the notification for only one thread that is waiting for a particular resource or object. If we use this method and if multiple threads are waiting for the notification then only one thread will get the notification and the remaining thread will have to wait for further notifications.

Q.14. What is the priority of a thread? How can you change the priority of a thread?

Answer. There is a priority for each thread in Java. We represent the thread Priorities by a number between 1 and 10. Mostly, the thread scheduler schedules the threads according to their priority which is called preemptive scheduling. But there is no guarantee because it depends on JVM specification which scheduling it chooses.

Thread class provides 3 constant properties for thread priority:

  1. public static int MIN_PRIORITY
  2. public static int NORM_PRIORITY
  3. public static int MAX_PRIORITY

We use the setPriority() method of thread class to change the priority of the thread.

public class Example extends Thread {
  public void run() {
    System.out.println("Priority of thread is: " + Thread.currentThread().getPriority());
  }
  public static void main(String args[]) {
    // creating thread   
    Example e1 = new Example();
    // printing the maximum priority of this thread  
    e1.setPriority(Thread.MAX_PRIORITY);
    //call the run() method  
    e1.start();
  }
}

Output:
Priority of thread is: 10

Q.15. What is the difference between the Runnable interface and the Thread class in Java?

Answer. Runnable is an interface that represents a task that we can execute by using either a Thread or Executor. Whereas, the Thread class creates a new thread. But, when we implement the Runnable interface, it does not create a new thread.

Q.16. Differentiate between wait() and sleep() methods in Java?

Answer. The sleep() method pauses the process for a few seconds or for the required time. But when we use the wait() method, the thread goes into a waiting state and it does not come back automatically until we call notify() or notifyAll() methods.

Another major difference between wait() and sleep() methods is that the wait() method releases the lock while the sleep() method does not release the lock while waiting. The wait() method is useful for inter-thread communication while the sleep() method is generally useful to introduce a pause on execution.

Q.17. How can you share data between two threads in Java?

Answer. Threads communicate with each other using Inter thread communication via objects. The threads exchange information over objects by locking and notification. A thread waits before accessing information of an object until another thread releases that object. The accessing thread notifies all the waiting threads via notify() or notifyAll() methods defined in Object class.

Java Multithreading Interview Questions

Q.18. What are the advantages of multithreading in Java?

Answer. This is a java basic questions but a favorite of interviewers. Multithreading allows multiple threads of a program to execute at the same time. The threads are lightweight processes available within the process. Therefore, multithreading enables maximum utilization of the CPU by multitasking. The benefits of multithreading in Java are:

Q.19. What is a Thread Scheduler?

Answer. Thread Scheduler is a part of JVM in Java. It decides which thread should run. It allocates the CPU time to all the available runnable threads. But there is no guarantee that the scheduler will choose which thread to run. At a time, only one thread can run.
The thread scheduler uses preemptive or time-slicing scheduling methods to schedule the threads.

Q.20. What is Time Slicing?

Answer. Time Slicing is a scheduling process that divides available CPU time among the various runnable threads. The allocation of CPU time will be dependent on the priority of the thread or for the time it is in the waiting state. Java cannot control Thread Scheduling, so it is better to control it by the application itself. In the Time slicing process, a task executes for a particular slice of time and then again enters the pool of ready tasks. The thread scheduler then decides which task should execute next, based on priority and other factors.

Core Java Basic Interview Questions

Let’s discuss more core Java interview questions and answers, these interview questions will be helpful for freshers. Interview questions are a good way to revise your fundamentals and get confidence for next interview.

Q.21. Is it possible to make an array volatile in Java?

Answer. Yes, we can make an array volatile in Java. But, we can make only the reference which is pointing to an array, not the whole array. If one thread changes the reference variable and points to another array, that will guarantee the volatility of array. But, if multiple threads are making changes in individual array elements, they can not change them before a volatile modifier provides the guarantee.

Q.22. What is the intern() method in Java?

Answer. The intern() method in Java belongs to the String class. The intern() method returns the String from the String pool if the String is present in the String pool, otherwise, it adds a new object of String in the String pool, and returns the reference of this String.

String string1 = "hello";
String string2 = "hello";
String string3 = "hello".intern();
if (string1 == string2) {
  System.out.println("string1 and string2 are the same");
}
if (string1 == string3) {
  System.out.println("string1 and string3 are the same");
}

We are assuming that the output of the above code snippet will be string1 and string3 as string3 is interned using the intern() method. But, the actual output is:
string1 and string2 are the same
string1 and string3 are the same
which makes clear that by default String constants are interned.

Q.23. When is class garbage collected?

Answer. Java uses the garbage collector to release the memory occupied by those objects that are no more referencing or pointing to other objects. An object can become eligible for Garbage Collection when no thread can access this object.

There are many ways to prevent a class or object form being eligible for Garbage Collection:

1. Objects of that class are reachable.
2. An object of the class representing the class is reachable.
3. The ClassLoader that loads the class is reachable.
4. Other classes loaded by the ClassLoader are reachable.

When all of the above cases are false, then all the classes which a classloader loads, become eligible for garbage collection.

Q. 24. What is the difference between eager loading and lazy loading?

Answer. The difference between eager and lazy loading is that Eager loading loads the data before the requirement, whereas Lazy loading loads the data only when required. Eager loading fetches the data in a single query, whereas lazy loading fetches the data by triggering the subquery.

Q.25. What is shallow cloning and deep cloning?

Answer. In Shallow cloning, the object is copied without its contained objects. That is Shallow cloning only copies the top-level structure of the object, not the lower levels. It is an exact bit copy of all the attributes of the object.

In Deep cloning, the object is copied along with the objects it refers to. That is Deep cloning copies all the levels of the object from top to the bottom levels recursively.

Q.26. What are Class loaders?

Answer. This is a good core Java interview question for freshers. The classloader in Java enables the program to load the class during its execution or runtime. It is present in the java.lang package. We can also load the customize classes using the Classloader required for the application execution. The class loaders in Java are organized in the form of a tree. When JVM starts, three class loaders are used which are:

1. Bootstrap class loader: These are the core Java libraries.

2. Extensions class loader: These classloaders load the code in the extension directories. The ExtClassLoader class implements this classloader.

3. System class loader: Its code is present on the java.class.path that maps to the classpath variables of the system. The AppClassLoader class implements this class loader. By default, All user classes are loaded by the system class loader.

Q.27. What are the disadvantages of a garbage collector?

Answer. Garbage Collector in Java executes in its own thread that affects the performance of the system. This increases the workload on JVM because it constantly keeps the track of the objects that are not being referenced.

Disadvantages of garbage collector are:

1. Time-consuming: JVM consumes a considerable amount of time to collect all the non-referenced objects by scanning the entire heap area.

2. Mark and sweep: It is difficult to implement the mark and sweep algorithm in the application.

Q.28. Does Java support global variables?

Answer. No, there is no support for the global variable in Java because of the following reasons:

1. Globally accessible: Global variables are globally accessible.
2. Referential transparency: The global variable breaks the rule of referential transparency. Also, a global variable generates a problem in the namespace.
3. Object-oriented: Java is an object-oriented language, so here each variable is declared inside the class. To use this variable, an object should be initialized.

Q.29. State the difference between the factory pattern and abstract factory pattern?

Answer. The differences between factory and abstract factory are:

  1. A factory design pattern is a single method but an abstract factory pattern is an object.
  2. The level of abstraction for the Abstract Factory pattern is one step higher than that of the factory pattern.
  3. The factory design pattern usually returns the common parent class or method but the abstract factory pattern returns one of the several factories.

Q.30. How is the Observable class used?

Answer. The observable class represents an observable object.

  1. The subclasses of the Observable class represent the objects to be observed.
  2. When there is a change in the object of Observable class, an application calling the notifyObservers() method of the Observable class causes all of its observers to be notified of the change.

Q.31. Explain the purpose of the Comparator Interface.

Answer. The Comparator interfaces control the order of certain data structures and collections of objects. This interface is present in java.util.Comparator. A Comparator interface must define a compare() method that takes two objects and returns 1, 0, or 1. We can perform sorting implicitly by using data structures by implementing sort methods explicitly.

Q.32. What is the impact of private constructor?

Answer. We cannot access the private constructors from any derived classes neither from another class. So we need to provide a public method that calls the private constructor if the object has not been initialized. Or, we have to return an object if it was initialized. This can be useful for objects that cannot be instantiated.

Java Interview Questions on Socket Programming

Q.33. What are the Advantages of Java Sockets?

Answer. Advantages of Java Sockets are:

Q.34. What are the disadvantages of Java Sockets?

Answer. Disadvantages of Java Sockets are:

Q.35. Implement bubble sort in Java.

Answer.

public int[] bubbleSort(int array[]) {
  // iterate over array backwards
  for (int i = array.length; i >= 0; i--) {
    // iterate over array forwards
    for (int j = 0; j < array.length - 1; j++) {
      // compare jth and next number
      int k = j + 1;

      // swap if necessary
      if (array[j] > array[k]) {
        int temp;
        temp = array[j];
        array[j] = array[k];
        array[k] = temp;
      }
    }
  }
  return array;
}

Q.36. What is the difference between multitasking and multithreading?

Answer. The basic difference between both of them is that Multitasking enables CPU to perform multiple programs, tasks, processes, threads at the same time whereas, Multithreading enables multiple threads of the same process to run at the same time.

Basis for comparison Multitasking Multithreading
Basic Multitasking lets the CPU execute multiple tasks simultaneously. Multithreading allows the CPU to run multiple threads of a process at the same time.
Switching In multitasking, the CPU switches between programs frequently. In multithreading, the CPU switches between the threads frequently.
Memory and Resource In multitasking, the system has to allocate separate memory and resources to each program. In multithreading, the system has to allocate memory to a process. Multiple threads of that process share the same memory and resources allocated to the process.

Q.37. How can you prove that the array is not null but empty using one line of code?

Answer. Using Print args.length. We will get 0 as output. This means that the array is empty. But if the output is NullPointerException on attempting to print args.length, then we can prove that it is null.

Q.38. Can an application with multiple classes have the main method?

Answer. Yes, it is possible for an application to have multiple classes with the main method. We mention the class name to be executed while starting the application. JVM will look only in that class for the main() method whose name we mentioned. Therefore, there will be no problem amongst the multiple classes having the main method.

Q.39. Is it possible to have multiple main methods in the same class?

Answer. No, we can not multiple main() methods in the same class. If we do so, the program fails to compile. The compiler gives the error saying that the main method is already defined in the class.

Q.40. Do we need to import the java.lang package at any time? Why?

Answer. No, we do not need to import the java.lang package in our programs. The JVM automatically loads it inside our programs. JVM by default imports the java.lang package. This package contains a number of components that are commonly used in Java programs. Java is useless without much of the functionality in the java.lang package. For the same reason, the java.lang is implicitly imported by the Java compiler for all programs.

Q.41. Can we import the same package or class twice? Will the JVM load the package twice?

Answer. Yes, it is possible to import the same package or a class multiple times in our program. Neither compiler nor JVM complains about it. The JVM will internally load the class or package only once no matter how many times we import it.

Java Developer Interview Questions

As Java is an evergreen programming language, careen in Java development is one of the best career options. Following Java interview questions will help you in cracking your next interview and make you a Java developer.

Q.42. How will you differentiate HashMap from HashTable?

Answer.

Q.43. Explain Map and their types in Java.

Answer. A Java Map is one of the Collection classes in java whose object maps keys to values. It does not contain duplicate keys and each key maps to only one value. The Map class uses the equals() method to determine whether two keys are the same or distinct.

There are four types of Maps in Java:

  1. HashMap: HashMap is an unordered and unsorted map and is a good choice to use when there is no focus on the order of values. A HashMap in Java allows one null key and multiple null values. It does not maintain any insertion order.
  2. HashTable: HashTable does not allow null values. It has methods that are synchronized. Its performance is slow as it allows for thread safety.
  3. LinkedHashMap: LinkedHashMap is slower than a HashMap but maintains insertion order. It has a faster iteration.
  4. TreeMap: TreeMap is a sorted Map that provides support for constructing a sort order using a constructor.

Q.44. What is a Priority Queue in Java?

Answer. A Priority queue is similar to a regular queue. It is an abstract data type that has a priority associated with each of its elements. In the priority queue, the element with the high priority is served before the element with low priority. The order of elements in a priority queue is either naturally or according to the comparator.

Q.45. What is a Set in Java? Explain its types in a Java Collections.

Answer. Collection is one of the important topics during the Java interview. A Set in Java is a collection of unique objects. It uses the equals() method to determine whether two objects are the same or not.
There are three types of Set in Java Collections which are:

  1. HashSet: HashSet is an unordered, and unsorted set. It uses the hash code of the object for adding the values into it. We use it when the order of the collection is important.
  2. LinkedHashSet: A LinkedHashSet is an ordered version of the HashSet. It maintains a doubly-linked list of all the elements. We can use it when the iteration order is mandatory. The insertion order is the same as that of the Set.
  3. TreeSet: TreeSet is one of the two sorted Collections in Java. It uses the Read-Black tree structure and ensures that the elements are present in the ascending order.

Q.46. What is ordered and sorted in terms of Collections?

Answer.

1. Ordered
Ordered means the values are stored in a collection in a particular order, but the order is not dependent on the value. For example, List is an ordered collection in Java.

2. Sorted
It means the collection has the values stored in an order which is dependent on the value of an element. For example, SortedSet is a sorted Collection in Java.

Q.47. Explain the various types of garbage collectors in Java.

Answer. In Java there are four types of garbage collectors:

1. Serial Garbage Collector: This garbage collector uses only a single thread for garbage collection. The serial garbage collector works by holding all the application threads. It is designed basically to work in single-threaded environments. This garbage collector is the most suitable for command-line programs because it freezes all the application threads while performing garbage collection. For using the serial garbage collector, we need to turn on the -XX:+UseSerialGC JVM argument.

2. Parallel Garbage Collector: Parallel Garbage Collector or the throughput collector is the default garbage collector of the JVM. This garbage collector uses multiple threads for garbage collection. It freezes all application threads during garbage collection, just like the serial garbage collector.

3. CMS Garbage Collector: CMS Garbage Collector stands for Concurrent Mark Sweep. The CMS garbage collector uses multiple threads for scanning the heap memory for marking instances.

4. G1 Garbage Collector: G1 Garbage Collector is used where there are large heap memory areas. It works by separating the heap memory into multiple regions and then executes them parallelly. The G1 garbage collector compacts the free heap area right after reclaiming the memory. It also prioritizes the region with the most garbage. We need to turn on the –XX:+UseG1GC JVM argument for using the G1 garbage collector.

Q.48. What do you mean by Synchronization in Java? What is its most significant disadvantage?

Answer. Synchronization in Java is used to prevent the situation when several threads try to access the same block of code. Simply, the synchronization process allows only a single thread to access a block of code at a time. There is a lock for each Java object and every lock has only one key. A thread can access a synchronized method only if it can get the key to the lock of the object.

The main disadvantage of the synchronized keyword is that it increases the waiting time of thread and adversely affects the performance of the system. Therefore, if there is no specific requirement, we should not use the synchronized keyword.

Java Basic Programs for Interview

Q.49. Write a program for string reversal without using inbuilt function.

Answer.

public int[] bubbleSort(int array[]) {
  // iterate over array backwards
  for (int i = array.length; i >= 0; i--) {
    // iterate over array forwards
    for (int j = 0; j < array.length - 1; j++) {
      // compare jth and next number
      int k = j + 1;

      // swap if necessary
      if (array[j] > array[k]) {
        int temp;
        temp = array[j];
        array[j] = array[k];
        array[k] = temp;
      }
    }
  }
  return array;
}

Q.50. Write a program to reverse a number.

Answer.

import java.util.Scanner;
public class NumberReversal {
  public static void main(String args[]) {
    System.out.println("Please enter the number to be reversed");
    Scanner sc = new Scanner(System. in );
    int number = sc.nextInt();
    int reverse = reverse(number);
    System.out.println("Reverse of number: " + number + " is " + reverse(number));
  }
  public static int reverse(int number) {
    int reverse = 0;
    int remainder = 0;
    do {
      remainder = number % 10;
      reverse = reverse * 10 + remainder;
      number = number / 10;
    } while ( number > 0 );
    return reverse;
  }
}

Q.51. Write a program for binary search in Java.

Answer.

This is a popular Java coding interview question

import java.util. * ;
public class BinarySearch {
  public static void main(String[] args) {
    System.out.println("Enter total number of elements : ");
    Scanner sc = new Scanner(System. in );
    int length = sc.nextInt();
    int[] input = new int[length];
    System.out.printf("Enter %d integers", length);
    for (int i = 0; i < length; i++) {
      input[i] = sc.nextInt();
    }
    Arrays.sort(input);
    System.out.print("the sorted array is: ");
    for (int i = 0; i <= length - 1; i++) {
      System.out.println(input[i] + " ,");
    }
    System.out.println("Enter number to be searched in sorted array");
    int key = sc.nextInt();
    int index = BSearch(input, key);
    if (index == -1) {
      System.out.printf("Sorry, %d is not found in array %n", key);
    }
    else {
      System.out.printf("%d is found in array at index %d %n", key, index);
    }
  }
  public static int BSearch(int[] input, int number) {
    int low = 0;
    int high = input.length - 1;
    while (high >= low) {
      int middle = (low + high) / 2;
      if (input[middle] == number) {
        return middle;
      }
      else if (input[middle] < number) {
        low = middle + 1;
      }
      else if (input[middle] > number) {
        high = middle - 1;
      }
    }
    return - 1;
  }
}

Q.52. Write a program to check if a number is a prime number.

Answer.

import java.util.Scanner;
public class Prime {
  public static void main(String args[]) {
    System.out.println("Enter the number to check: ");
    Scanner sc = new Scanner(System. in );
    int num = sc.nextInt();
    boolean isPrime = false;
    if (num != 0) {
      isPrime = checkPrime(num);
    }
    else {
      System.out.println("Enter valid number");
    }
    if (isPrime == false) {
      System.out.println(" NOT PRIME!!");
    }
    else {
      System.out.println("PRIME!!");
    }
  }
  public static boolean checkPrime(int number) {
    int sqrt = (int) Math.sqrt(number) + 1;
    for (int i = 2; i < sqrt; i++) {
      if (number % i == 0) {
        return false;
      }
    }
    return true;
  }
}

Q.53. Write a program to print the Fibonacci Series.

Answer.

import java.util.Scanner;
public class Fibo {
  public static void main(String args[]) {
    System.out.println("Enter the number upto which Fibonacci series should be printed ");
    Scanner sc = new Scanner(System. in );
    int num = sc.nextInt();
    System.out.println("Fibonacci Series upto %d is" + num);
    for (int i = 1; i <= num; i++) {
      System.out.print(fib(i) + " ");
    }
  }
  public static int fib(int n) {
    if (n == 1 || n == 2) {
      return 1;
    }
    return fib(n - 1) + fib(n - 2);
  }
}

Q.54. Write a program to check if the given string is a palindrome.

Answer.

During the core Java interview, String is a hot topic. Interviewers ask tons of questions about Strings, also about the String related Java programs

import java.util.Scanner;
public class PalinDrome {
  public static void main(String args[]) {
    System.out.println("Enter the string to check");
    Scanner sc = new Scanner(System. in );
    String str = sc.nextLine();
    boolean isPalindrome;
    isPalindrome = checkPalindrome(str);
    if (str.equals(" ")) {
      System.out.println("Enter valid string");
    }
    else {
      if (isPalindrome) {
        System.out.println("PALINDROME!!");
      }
      else {
        System.out.println("NOT A PALINDROME!!");
      }
    }
  }
  public static boolean checkPalindrome(String input) {
    int str_length = input.length();
    int i = 0,
    j = str_length - 1;
    while (i < j) {
      if (input.charAt(i) != input.charAt(j)) return false;
      i++;
      j--;
    }
    return true;
  }
}

Java Programming Interview Questions

Q.55. Write a program to print the following pattern.

Answer.

public class Pattern {
  public static void main(String args[]) {
    for (int i = 5; i >= 0; i--) {
      System.out.println();
      for (int j = i; j < 5; j++) {
        System.out.print(" * ");
      }
    }
    System.out.println();
  }
}

Q.56. Write a program to swap two numbers.

Answer.

import java.util.Scanner;
public class Swap {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System. in );
    System.out.println("Enter a number: ");
    int num1 = sc.nextInt();
    System.out.println("Enter second number: ");
    int num2 = sc.nextInt();
    System.out.println("Values of num1 and num2 before swapping: " + "num1 = " + num1 + " num2= " + num2);
    swap(num1, num2);
  }
  public static void swap(int num1, int num2) {
    int swap_variable;
    swap_variable = num1;
    num1 = num2
    num2 = swap_variable;
    System.out.println("Value of num1 and num2 after swapping: " + "num1 = " + num1 + " num2 = " + num2);
  }
}

Q.57. Write a program to check if the given number is an Armstrong number.

Answer.

This is a popular Java programming question

import java.util.Scanner;
public class Armstrong {
  public static void main(String args[]) {
    Scanner s = new Scanner(System. in );
    System.out.println("Enter a number: ");
    int number = s.nextInt();
    int a = number,
    sum = 0,
    num = 0;
    while (a % 10 != 0) {
      num = a % 10;
      sum = sum + (num * num * num);
      a = a / 10;
    }
    if (sum == number) {
      System.out.println("Armstrong Number!");
    }
    else {
      System.out.println("Not an Armstrong Number!");
    }
  }
}

JDBC Interview Questions

Q.58. What is JDBC?

Answer. JDBC stands for Java DataBase Connectivity. It is a Java API that connects and executes the query to the database. JDBC API(Application Programming Interface) uses JDBC drivers to connect to the database of the system. We can use JDBC API to access tabular data stored in any relational database.

Q.59. What is a JDBC Driver? Explain their types.

Answer. A JDBC Driver is a software component installed on the client machines that enables Java applications to interact with the database. They convert requests from Java programs to a protocol that DBMS can understand. There are four types of JDBC drivers:

1. JDBC-ODBC bridge driver: The JDBC-ODBC bridge driver makes the use of ODBC(Open Database Connectivity) driver to connect to the database. This driver converts JDBC method calls into ODBC function calls. This is now not in much use because of the thin drivers. It is easy to use and connect to any database.

2. Native-API driver (partial Java driver): The Native API driver makes the use of the client-side libraries of the database. The Native-API driver converts JDBC method calls into native calls of the database API. This driver is not written entirely in Java. The performance of the Native-API driver is better than the JDBC-ODBC bridge driver.

3. Network Protocol driver (full Java driver): The Network Protocol driver uses middleware (application server). This server converts JDBC calls directly or indirectly into the vendor-specific database protocol. This driver is entirely written in Java. It is not compulsory to have a client-side library for using this driver because of the application server that can perform any task like load balancing, auditing, and logging, etc.

4. Thin driver (fully Java driver): The thin driver is used to convert JDBC calls directly into the vendor-specific database protocol. For the same reason, it is also known as the thin driver. This driver is entirely written in Java language. The performance of this driver is better than all other drivers. However, these drivers are dependent upon the database.

Q.60. What are the differences between the Statement and PreparedStatement interface?

Statement  PreparedStatement
In Statement, the query compiles each time we execute the program. In PreparedStatement, the query compiles only once.
We mainly use the Statement in the case when we need to run the static query at runtime. We use PreparedStatement when we need to provide input parameters to the query at runtime.
The statement executes normal SQL queries. PreparedStatement executes parameterized or dynamic SQL queries.
It is preferable when a particular SQL query is to be executed only once. It is preferable when a particular query is to be executed multiple times.
We cannot pass the parameters to the SQL query using the Statement interface. We can pass the parameters to SQL query at run time using the PreparedStatement interface.
The statement is mainly used for DDL statements like CREATE, ALTER, DROP, etc. PreparedStatement is used for any SQL queries which are to be executed multiple times.
The performance of the Statement interface is very slow. The performance of the PreparedStatement interface is better than the Statement interface.

Q.61. What are the benefits of PreparedStatement over a Statement?

Answer. The benefits of PreparedStatement over Statement interface are:

Q.62. What are the differences between execute, executeQuery, and executeUpdate?

execute executeQuery executeUpdate
The execute() method is used for any SQL statements, i.e., select and update both. The executeQuery() method can only be used with the select statement. The executeUpdate() method can be used with insert, update, or delete operations in the database.
The execute() method returns the value of the boolean type. The true value indicates that the ResultSet can later be extracted and the false value indicates that the void or integer value is returned. The executeQuery() returns the object of  ResultSet which contains the data retrieved by the select statement. The executeUpdate() returns an integer value that represents the number of records affected. 0 indicates that the query returns nothing.

Q.63. What is the role of the JDBC DriverManager class?

Answer. The JDBC DriverManager class acts as an interface between users and JDBC drivers. The DriverManager class keeps track of the drivers that are available. It handles the establishment of a connection between a database with the appropriate driver. This class maintains a list of Driver classes that are registered by calling the DriverManager.registerDriver() method.

Q.64. What is the role of the JDBC Connection interface?

Answer. The Connection interface of JDBC is used to maintain a session with the database. We can use this interface for transaction management. The Connection interface provides factory methods. These factory methods return the object of Statement, PreparedStatement, CallableStatement, and DatabaseMetaData.

Q.65. What is the JDBC ResultSet interface?

Answer. The instance of the ResultSet interface represents a row of a table in the database. We can use this interface to change the cursor pointer and get the information from the database. By default, the ResultSet object can move only in the forward direction and we cannot update it. But, we can make the object of ResultSet to move in forward and backward direction by passing either TYPE_SCROLL_SENSITIVE or TYPE_SCROLL_INSENSITIVE in createStatement(int, int) method.

Q.66. How can you maintain the integrity of a database using JDBC?

Answer. We need to ensure the ACID properties to maintain the integrity of a database. ACID properties stand for Atomicity, Consistency, Isolation, and Durability. In JDBC, We can use the Connection interface that provides methods like commit(), setAutoCommit(), and rollback(). These methods are useful to manage transactions. Let’s see an example of transaction management in JDBC.

import java.sql. * ;
public class FetchRecords {
  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 stmt = c.createStatement();
    stmt.executeUpdate("insert into user420 values(101,'Raj',10000)");
    stmt.executeUpdate("insert into user420 values(191,'Neha',40000)");

    c.commit();
    c.close();
  }
}

Q.67. What are setFetchSize() and setMaxRows() methods in Statement?

Answer. We can use the setMaxRows(int i) method to limit the number of rows that the database returns from the query. We can also use the SQL query to achieve the same thing. For example, we can use the LIMIT clause in MySQL to set the maximum rows that should be returned by the query.

Suppose we have a query that returns 100 rows. We have set fetch size to 10. Thus, in every database trip, the JDBC driver will fetch only 10 rows. Hence, there will be 10 trips/rounds to fetch all the rows. It is helpful to set an optimal fetch there is a need for a lot of processing time for each row and the number of rows in the result is large. We can set fetchSize using the object of the Statement but we can also do the same thing through the ResultSet object setFetchSize() method.

Q.68. What are some common JDBC Exceptions?

Answer. Some of the common JDBC Exceptions are:

  1. java.sql.SQLException: This exception is the base exception class for all the JDBC exceptions.
  2. java.sql.BatchUpdateException: This exception is thrown when any batch operation fails. However, it depends on the JDBC driver, whether it throws this exception or the base SQLException.
  3. java.sql.SQLWarning: This exception is thrown for giving warning messages in SQL operations.
  4. java.sql.DataTruncation: When a data value is unexpectedly truncated for reasons other than exceeded MaxFieldSize.

Q.69. When should each of the JDBC driver types be used?

Answer.

Q.70. What are the basic steps to create a JDBC application?

Answer. Following are the basic steps to create a JDBC application:

Q.71. How do you represent a URL in the Java programming language?

Answer. There is a URL class in the Java API that we can use to represent the URL address. We can create the URL object if we have the URL address string. The URL class provides getter methods that help to get the components of the URL such as path, hostname, port, query parameters, etc.

Example:

String urlString = 'http://www.techvidvan.com';
URL url = new URL(urlString);

Q.72. How can you connect to a URL resource in Java programming language?

Answer. There is a ‘URLConnection’ class provided by the Java API. The URLConnection class helps to create a connection to a URL. If we have a URL object, we can get the URLConnection object by calling the openConnection() method on the URL object. Once we have the URLConnection object we can connect to the URL resource by calling the connect() method on the URLConnection object. We can use the URLRequest object to set up parameters and properties that we need for making the URL connection.

Example:

String urlString = 'http://www.techvidvan.com';
URL myUrl = new URL(urlString);
URLConnection myUrlConnection = myUrl.openConnection();
myUrlConnection.connect();

Q.73. What are the key steps in reading from a URL connection?

Answer.
1. Create the URL object.
2. Create a URLConnection object.
3. Open connection to URL.
4. Get an input stream from the connection.
5. Read from the input stream.
6. Close input stream.

Q.74. What are the key steps in writing to a URL connection?

Answer.
1. Create the URL object.
2. Create a URLConnection object.
3. Open connection to URL.
4. Get the output stream from the connection.
5. Write to the output stream.
6. Close output stream.

Q.75. What is a proxy server?

Answer.

Q.76. Tell about the two important TCP Socket classes in Java?

Answer.

Core Java Interview questions on Swing

Q.77. State the differences between Swing and AWT?

Answer. There are many differences between swing and AWT:

Q.78. Why are Swing components called lightweight components?

Answer. The components of the Swing class are less dependent on the target platform and do not much use the native GUI resource. Hence the Swing components do not rely on native GUI and are referred to as lightweight components. While AWT components are heavyweight components because they are associated with native screen resources.

Q.79. What is a layout manager? What are the different types of layout managers available in Java Swing?

Answer. A layout manager is an object that organizes the components in a container. Different types of layout managers are:

1. FlowLayout: The FlowLayout elements are organized in a top to bottom, left to right fashion.
2. Border Layout: The BorderLayout elements are organized at the borders, i.e., North, South East, and West, and the center of a container.
3. Card Layout: The elements of a CardLayout are arranged on the top of the other, like a stack or a deck of cards.
4. Grid Layout: The elements of a GridLayout are of equal size and organized using the square of a grid.
5. Grid Bag Layout: The elements of a GridBagLayout are organized in the form of a grid. The elements of the Grid bag Layout may be different sizes and may occupy more than one row or column of the grid. Their rows and columns also may have different sizes.

Q.80. Is Swing thread-safe?

Answer.

Q.81. Which package in Java has a lightweight component?

Answer.

Q.82. What is the purpose of using the enableEvents() method?

Answer.

Core Java Interview Questions for Experienced

Are you a core Java professional preparing for an interview? If yes, this section is for you. Although, in this section as well we will start with basics. If you are looking for advanced Java interview questions, please refer: Java interview questions and answers for experienced professionals.

Q.83. Explain the JTable and TableDateModel interface in Swing?

Answer.

Q.84. How different is Swing from AWT?

Answer. The differences between Swing and AWT are:

AWT Swing
AWT stands for Abstract windows toolkit. JFCs (Java Foundation Classes) is another name for Swing.
AWT components are known as the Heavyweight components. Swing components are called lightweight components because swing components work on the top of AWT components.
AWT components are present in the java.awt package. Swing components are present in the javax.swing package.
AWT components are platform dependent. Swing components are purely built in java and they are platform-independent.
The Look and Feel feature is not supported in AWT. There are different look and feel features in Swing.
No such features are present in AWT. Swing has many advanced features like Jtabbed pane, JTable, etc.
With AWT, we have 21 “peers”. A “peer” is a widget of an operating system, such as a button object or an entry field object. We can have only one peer with Swing, i.e., the operating system’s window object. 
AWT is like a thin layer of code on top of the Operating System. Swing is much larger than AWT. Swing also has richer functionality.
We need to implement a lot of things using AWT. Swing has them built-in.

Q.85. How do you classify Swing Components?

Answer. Swing components are classified under the following categories:

1. Top-level containers: The top-level containers are present at the top of any swing component hierarchy. They are:

2. General-purpose containers: The general-purpose containers are:

3. Special purpose containers: Special purpose containers are intermediate containers that play specific roles in the use interface. They are:

4. Basic controls: These are the atomic components that exist primarily to get input from the user. They are:

5. Uneditable information displays: The atomic components which give information to the user are:

6. Interactive displays of highly formatted information: The atomic components that display formatted information and can be modified by the users. They are:

Q.86. What is the main difference between Dialog and Frame?

Answer.

  1. In AWT, a Frame is a top-level window, which is itself not contained in another window. On the other hand, a Dialog is a window that appears over an existing window (mostly Frame) and forces the user to respond.
  2. A Frame can exist on its own, but a DIALOG cannot exist on its own. In simple words, a FRAME is a primary window, whereas the DIALOG box is a secondary window.
  3. A Frame has maximized and minimized buttons at the top right corner of the window, but there are no such buttons in Dialog.
  4. We can set Dialog modally. Modal means that we can not use or activate another window while the corresponding JDialog is being displayed.

Java Interview questions on File Handling

Q.87. What is Java I/O?

Answer. Java I/O (Input and Output) processes the input and produces the output. Java makes use of the stream concepts to make Input/Output operation faster. Java I/O is an API that targets reading and writing data (input and output). The java.io package of Java contains all the classes required for input and output operations.

A stream is a sequence of data. There are two kinds of Streams in Java:

  1. InputStream: The InputStream reads data from a source. For example, reading data from a file or over the network.
  2. OutputStream: The OutputStream writes data to a destination. For example, writing to a file or writing a response back over the network.

Q.88. State the difference between Scanner and BufferedReader?

Answer.

Q.89. Could you draw the Java Exception Hierarchy?

Q.90. What are Java Annotations?

Answer. Java Annotations provide information about the Java program. Annotations have no direct effect on the code they annotate. Java introduced Annotations Java 5. Annotation is defined as the metadata, i.e., the data about the program embedded in the program itself.

We can parse it by the annotation parsing tool or by the compiler. We can also specify annotation availability either at the compile-time only or till the execution of the program. Some built-in annotations of Java are @Override, @Deprecated, and @SuppressWarnings, etc.

Java Technical Interview Questions

Q.91. What is the Java Reflection API? Why is it so important to have?

Answer. Reflection API in Java gives the ability to change or inspect the runtime behavior of Java applications. We can inspect a Java class, interface or, enum, and get the details of their methods and fields. Reflection API is an advanced topic of Java and we should not use it in normal programming. The use of Reflection API can break rules of the design pattern such as Singleton pattern, by invoking the private constructor and violating the rules of access modifiers.

Though we do not use Reflection API in normal programming, it is a very important concept. It is impossible to have any frameworks such as JSF, Spring, Hibernate, etc or servers such as Tomcat, JBoss without Reflection API. These frameworks or servers invoke the appropriate methods and instantiate classes through reflection API and use it a lot for other processing.

Q.92. Is it possible for an interface to implement or extend another interface?

Answer. No, it is not possible for an interface to implement another interface, but one interface can extend or inherit other interfaces/s. As interfaces do not have method implementations, there is no issue of diamond problem. Therefore, Java supports multiple inheritances in interfaces. That is, an interface can extend multiple interfaces.

Q.93. What is a Marker interface in Java?

Answer. A Marker interface is an empty interface that does not have any method or a field but we use it to force some functionality in implementing classes. A marker interface conveys to the JVM that the class implementing an interface of this category will have some special behavior. Hence, an empty interface in Java is a Marker interface. Some of the well-known marker interfaces of Java are Serializable, Remote, and Cloneable interfaces.

Q.94. What is try-with-resources in Java?

Answer. Try-with resources statement is one of the features of Java 7. It is used for automatic resource management. There was no auto resource management before Java 7, and the users had to explicitly close the resource. Usually, they did it in the finally block of a try-catch statement. This approach causes memory leaks when users forgot to close the resource. From Java 7 onwards, try-with-resources allows us to create resources inside the try block and use it.

Q.95. What is Enum in Java?

Answer. Enum was introduced in Java 5. Enum is a new type whose fields consist of a fixed set of constants. For example, in Java, we can create the Direction as an enum which has the fixed fields as EAST, WEST, NORTH, SOUTH. ‘enum’ keyword used to create an enum type. The declaration of Enum is similar to the class in Java. Enum constants are implicitly declared as static and final.

Example:

enum Direction
{
   EAST, WEST, NORTH, SOUTH;
}

Q.96. What is the difference between Heap and Stack Memory?

Answer. This is another important topic for core Java interview questions

The major differences between Heap and Stack memory are:

Q.97. Java Compiler is stored in JDK, JRE or JVM?

Answer. The task of the Java compiler is to convert the Java program into bytecode, we have a javac executable for the same. So it must be located in JDK, we do not need it in JRE and JVM is just the specs.

Java Collections Interview Questions

Q.98. What are all the Classes and Interfaces that are available in the collections?

Answer. Given below are the Classes and Interfaces that are available in Collections:

Interfaces:

Classes:

Sets:

Maps:

Queue:

Q.99. Explain the different lists available in the collection.

Answer. Values added to the list are based on the index position and it is ordered by index position. Duplicates are allowed.

Types of Lists are:

a) Array List:

b) Vector:

c) Linked List:

Q.100. How can you remove duplicates from a List in Java?

Answer. We can remove duplicate elements in an ArrayList using LinkedHashSet. LinkedHashSet is considered to be the best approach to remove the duplicate elements from an ArrayList.
LinkedHashSet does the following two things internally:

We can also use the Stream API in Java to remove the duplicates from the ArrayList. We can use the distinct() method of the Stream API. This method returns a stream consisting of the distinct elements compared by the equals() method of the Object class.

Conclusion

We have covered 100 core Java interview questions and answers. These interview questions are the most frequently asked questions. You can start your career in Java by practicing these questions, they will really be helpful in cracking your interviews on Java.

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

Exit mobile version