Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

Table of Contents

Top 80+ Java Interview Questions and Answers

Dreading your upcoming Java Interview? Feeling unprepared for the barrage of technical questions that might come your way? Don't fret! Mastering Java Interview Questions is the key to landing your dream Java Developer role. But with so much ground to cover, where do you even begin?  This comprehensive blog equips you with the ultimate arsenal – over 80 of the most frequently asked Java Interview Questions and their insightful answers.  

We'll explore a diverse range of topics, from core Java fundamentals to Object-Oriented Programming concepts, collections frameworks, and multithreading. By mastering these key areas, you'll approach your interview with confidence and showcase your Java expertise. So, ditch the interview jitters and dive into this ultimate collection of Java Interview Questions – your one-stop shop for interview success!

Table of Contents

1) Java Interview Questions for Freshers Level

2) Java Interview Questions for Intermediates Level 

3) Java Interview Questions for Experts Level 

4) Conclusion 

Java Interview Questions for Freshers Level

Prepare for your Java Interview with these fundamental questions, designed to build confidence and showcase your knowledge as a beginner in software development.

1) What is java?

Java is an Object-Oriented Programming language that has gained substantial traction in the marketplace due to its ability to operate across a variety of computing platforms. It aims to be beginner-friendly (easy to learn, write and understand) whilst at the same time being capable of handling large-scale projects. It also has the benefit of “write once, run anywhere” which is bytecode, that can run on any platform there is a Java Virtual Machine (JVM)
 

Java programming
 

2) What is a functional interface in Java? 

A functional interface in Java is an interface that has only one abstract method, declaring the task to be performed by the class that uses the interface. A functional interface is usually termed an Single Abstract Method (SAM) and is a target for lambda expressions, which allow short anonymous functions to be used in place of old function methods. In other words, it is a contract for one job, and the implementing classes give the details of how to do that job.

3) What are the features of Java?

Here are some key features of Java programming language: 

a) Object-Oriented: Java promotes code reusability and modularity by treating everything as an object, encapsulating data and behaviours

b) Platform independent: Java's bytecode enables the "write once, run anywhere" philosophy, allowing code to run on any platform with a JVM

c) Secure: Strong memory management and garbage collection minimise errors like buffer overflows

d) Simple and Readable: Java's clear syntax, similar to C++, makes it easy to learn and maintain.

e) Robust: Error prevention is prioritised through compile-time and runtime checks, enhancing code reliability

f) Multithreaded: Java supports concurrent task execution using threads, efficiently handling multiple processes.

g) Rich API: A comprehensive set of libraries for networking, file handling, and graphics streamlines development.

4) Differences between Stack and Heap memory in Java?  
 

Stack

Heap

Easy to implement

Difficult to implement

Linear data structure

Hierarchical data structure

Memory allocated in a continuous block

Memory allocated in a random fashion

The cost is less for building and maintenance of stack

Cost is high to build and maintain a heap

Excellent locality of reference

Sufficient locality of reference

If all blocks fail to be occupied, memory will be lost too

It is possible to resize in heap

Disadvantage of stack is shortage in memory due to fixed size

The disadvantage of heap is fragmentation of memory


5) What is main() method in Java? 

The main() method in Java is predefined in JVM (Java Virtual Machine). It is the starting point of Java program. Without the main() method, JVM will not execute the program. 

Syntax: 

Public static void main(String args[]) 

6) What are JVM, JRE, and JDK? 

Java Virtual Machine (JVM): JVM is a specification that provides a runtime environment. JVM is also called an interpreter because it is used to execute the line-by-line Java program.  

Java Run-time Environment (JRE): JRE is an installation package that gives an environment to run the java program on your machine. JRE is only used by the end-users of the system.  

Java Development Kit (JDK): JDK provides an environment to write and execute the java program. JDK contains Development toolkit and JRE. 

7) Differences between == and equals() in Java? 
 

== 

equals() 

== is a comparison operator in Java 

It is a method in Java 

The == operator compares objects and reference values 

equals() method compares objects and reference value 

User can use == operator with objects and primitives. 

It is impossible to use equals() with primitives 

== operator cannot be overridden 

equals() method can be overridden 

The == operator cannot compare conflicting objects 

equals() can compare conflicting objects


8) Why Java is not a pure Object-Oriented language? 

Java is not a pure Object-Oriented Programming language, because it supports primitive data types. Primitive data types contain Boolean, int, char, float, double, short, byte.

9) What is the difference between the break and continue statements in Java? 
 

Break

Continue

The Break is a statement that is used terminate the loop

Continue is a statement that is used skip an iteration of the loop

Break statement can be used with ‘switch’

Continue statement cannot be used with ‘switch’

Break statement ends an entire loop early

Continue statement brings the next iteration early

Break statement ends the execution of loop

Continue statement does not end the execution of loop

 

10) What are the differences between C++ and Java?

Topic 

C++

Java

Concept 

Object-Oriented Programming language with procedural features

Purely Object-Oriented Programming language

Languages Compatibility

Widely used in system programming, game development, and embedded systems

Primarily used for web development, enterprise applications, and Android app development

Interaction with the library 

Direct interaction with system libraries through pointers and memory management

Interaction with libraries through Java's built-in classes and APIs; no direct memory management

Characteristics

More complex syntax with greater control over memory and hardware resources

Simpler syntax with automatic memory management and platform independence

Semantics of the type

Strongly typed, allowing low-level memory manipulation

Strongly typed with emphasis on type safety and portability

Compiler vs. Interpreter

Typically compiled into machine code for performance

Compiled into bytecode and executed by the Java Virtual Machine with Just-In-Time (JIT) compilation for optimisation

 

11) What are the Memory Allocations available in Java?

Java has five significant types of memory allocations.

1) Class Memory

2) Heap Memory

3) Stack Memory

4) Program Counter-Memory

5) Native Method Stack Memory

12) Will the program run if we write static public void main?

Yes, because in Java there is no specific rule for the order of specifiers.

13) What is the default value stored in Local Variables?

Neither the Local Variables nor any primitives and Object references have any default value stored in them.

14) What is an Association?

In software engineering and design, an association refers to a relationship between two or more classes or objects. It describes how classes or objects are connected or interact with each other. Associations can have various characteristics such as directionality, multiplicity, and navigability.

Improve your JavaScript skills through our JavaScript for Beginners Course.

15) What do you mean by aggregation?

Aggregation is a type of association in Object-Oriented Programming where one class represents a "whole" or "container" object that contains other "part" or "component" objects. It's a form of relationship between classes that represents a "has-a" or "is-part-of" relationship. In aggregation, the contained objects can exist independently of the container object.

16) Define Copy Constructor in Java

A Copy Constructor in Java is a constructor that initialises an object through another object of the same class.

17) What is a Marker Interface?

An empty interface in Java is referred to as a Marker interface. Serialisable and Cloneable are some famous examples of Marker Interface.

18) What is Object Cloning?

Object cloning involves creating a duplicate of an existing object. It's achieved using the Cloneable interface and the clone() method.

19) Define Wrapper Classes in Java.

Wrapper classes in Java are classes that encapsulate primitive data types into objects. They provide a way to treat primitive data types as objects, enabling them to be used in scenarios where objects are required.

20) What is a singleton class in Java? And how to implement a singleton class?

A class that can possess only one object at a time is called a singleton class.

By following these methods a singleton class can be implemented:

1) Make sure that the class has only one object

2) Give global access to that object

21) Define package in Java.

Packages encompass classes, interfaces, and required libraries and JAR files. Their utilisation fosters code reusability by organising and grouping related components.

22) Can you implement pointers in a Java Program?

Java programming language does not support pointers directly. It employs references (objects with memory addresses) for a similar purpose, but it lacks pointer arithmetic and memory manipulation.

23) Differentiate between instance and local variables

Instance variables live within objects, persist throughout the object's lifetime, and can be accessed by all the object's methods. Local variables exist within methods or code blocks, only live during method execution, and are specific to that method.

24) Explain Java String Pool

The Java String Pool is a special area in memory where string literals are stored. When a string literal is created, Java checks the pool. If a string with the same value exists, the new string references the existing one, promoting memory efficiency by avoiding duplicate string storage.

25) What is an Exception?

An exception in Java is an event that disrupts the normal flow of a program's execution due to errors or unexpected conditions.

26) What is the final keyword in Java?

In Java, the ‘final’ keyword is used to restrict the further modification of classes, methods, and variables. When applied to a class, it prevents inheritance. When applied to a method, it prevents overriding. When applied to a variable, it makes its value immutable once initialised.

27) Why is the main method static in Java?

The main method in Java is declared static to serve as the entry point for the program. Being static allows it to be invoked by the JVM without creating an instance of the class, ensuring consistency and enabling program execution without object instantiation.

28) What are the differences between constructor and method of a class in Java?

Constructors initialise objects during creation, invoked implicitly. They lack return types and are used for object setup. 

Methods are regular functions invoked explicitly, performing specific tasks. They can have return types and define object behavior. Both can be overloaded, but only methods can be overridden for polymorphism.

29) Can you explain the Java thread lifecycle?

The Java thread lifecycle consists of several states through which a thread transitions during its lifetime:

a) New: Thread is created but not yet running.

b) Runnable: Thread is ready to run and waits for resources (like CPU).

c) Running: Thread is actively executing code.

d) Blocked: Thread is waiting for an event (like I/O) and cannot proceed.

e) Terminated: Thread has finished execution or encountered an error.

30) Explain the term “Double Brace Initialisation” in Java?

The outer braces of the double-brace initialisation construct an anonymous class that is descended from the provided class and gives an initialiser block for that class (the inner braces).

31) What is a Memory Leak? Discuss some common causes of it.

A memory leak occurs in a computer program when it allocates memory but fails to release it after it's no longer needed, leading to a gradual depletion of available memory. Memory leaks can cause performance degradation and eventual program failure due to insufficient memory.

32) Write a Java Program to print Fibonacci Series using Recursion.

public class FibonacciSeries {

    public static void main(String[] args) {

        int n = 10; // Change the value of n to print desired number of Fibonacci numbers

        System.out.println("Fibonacci Series:");

        for (int i = 0; i < n; i++) {

            System.out.print(fibonacci(i) + " ");

        }

    }

    public static int fibonacci(int n) {

        if (n <= 1) {

            return n;

        } else {

            return fibonacci(n - 1) + fibonacci(n - 2);

        }

    }

}

 

33) Write a Java program to create and throw custom exceptions.

class InvalidAgeException extends Exception {

    public InvalidAgeException(String message) {

        super(message);

    }

}class Voter {

    private String name;

    private int age;

    public Voter(String name, int age) throws InvalidAgeException {

        if (age < 18) {

            throw new InvalidAgeException("Invalid age. Minimum age required for voting is 18.");

        }

        this.name = name;

        this.age = age;

    }

    public void vote() {

        System.out.println(name + " is eligible to vote.");

    }

}

public class CustomExceptionExample {

    public static void main(String[] args) {

        try {

            Voter voter1 = new Voter("Alice", 25);

            voter1.vote();

            Voter voter2 = new Voter("Bob", 16); // This will throw InvalidAgeException

            voter2.vote(); // This line won't be executed because of the exception

        } catch (InvalidAgeException e) {

            System.out.println("Exception occurred: " + e.getMessage());

        }

    }

}

 

34) Implement Binary Search in Java using recursion.

public class BinarySearch {

    // Recursive binary search method

    public static int binarySearch(int[] arr, int low, int high, int key) {

        if (high >= low) {

            int mid = low + (high - low) / 2;

            // If the element is present at the middle itself

            if (arr[mid] == key)

                return mid;

            // If the element is smaller than mid, then it can only be present in the left subarray

            if (arr[mid] > key)

                return binarySearch(arr, low, mid - 1, key);

            // Else the element can only be present in the right subarray

            return binarySearch(arr, mid + 1, high, key);

        }

        // We reach here when the element is not present in the array

        return -1;

    }

    public static void main(String[] args) {

        int[] arr = { 2, 3, 4, 10, 40 };

        int key = 10;

        int n = arr.length;

        int result = binarySearch(arr, 0, n - 1, key);

        if (result == -1)

            System.out.println("Element not present");

        else

            System.out.println("Element found at index " + result);

    }

}

 

Join our Java Engineer Training today and kickstart your career in software development.

Java Interview Questions for Intermediates Level

Let us look at a few intermediate level questions for your next Java Interview:

1) What is ‘super’ keyword in Java? 

‘Super’ keyword is a method used to call and access the superclass constructor. It refers to the parent object. The main purpose of this keyword is to avoid the confusion between superclass and subclass. 

2) Why is Java a Dynamic programming language? 

Java is far from being a purely dynamic programming language. It is strictly typed, meaning the types of variables are defined at compile time. Dynamic languages, like Python, determine their types at runtime, making them truly dynamic.

3) Explain Daemon Thread in Java. 

It is a background service thread (low priority thread) which runs in the background to perform some specific tasks. It provides services to the user thread. JVM automatically ends this thread, when all the user threads die.  

Learn how to develop embedded systems and applications with our Java Engineer Training. Sign up today!

4) What is JDBC Driver? 

Java Data Base Connectivity (JDBC) is an Application Programming Interface (API) for Java. It allows Java applications to connect with databases. It is used to send queries and update statements to the database,  

5) What is “OutofMemoryError” in Java? 

”OutOfMemoryError” in Java is a runtime error. It occurs when JVM (Java Virtual Machine) is unable to allot an object due to poor space in Java heap. Also, when the Garbage Collector is unable to free up the space, the “OutofMemoryError” issue can occur. It occurs when memory is insufficient.  

“Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at OutOfMemoryErrorExample.main(OutOfMemoryErrorExample.java:8)” 

6) Differences between HashMap and HashTable in Java? 
 

HashMap

HashTable

HashMap is non-legacy

HashTable is legacy

HashMap introduced in the Java’s 1.2 version of Java

HashTable introduced in Java’s 1.0 version

Null is permitted for both key and value

Null is not permitted for both key and value

Object is not thread safe in HashMap

Object is thread safe in HashTable

Method is not synchronized

Method is synchronized

High performance

Low performance


7) Is Java “Pass-by-Value“ or “Pass-by-Reference”? 

Java is “Pass-by-Value".

“Pass-by-Value": It means, a function (method) is called by passing a value. It makes a copy in memory of the parameter’s value.  

8) What is a ClassLoader? 

ClassLoader is an abstract class in Java. It is a sub system of JVM (Java Virtual Machine). It is used to load class files when a program is executing. ClassLoader performs the first process in loading the executable file. It belongs to java.lang package. ClassLoader works based on three principles: Delegation, Visibility, and Uniqueness. 

There are three types of ClassLoader: 

A) Bootstrap ClassLoader 

B) Extensions Class Loader 

C) System Class Loader 

9) What is constructor in Java? 

Constructor is a block of code same as like methods. A constructor used to start an object. It is automatically invoked when a new object is created.

10) What is JDK? Mention the variants of JDK?

JDK stands for Java Development Kit. It provides the tools and libraries needed to develop Java applications. There's no official variant of the JDK, but Oracle offers a commercially supported version and OpenJDK is the open-source alternative.

11) What is a JIT compiler?

A Just-In-Time (JIT) compiler is a performance enhancer in Java. It translates bytecode (intermediate code of the Java program) to machine code at runtime, specifically for the most frequently executed segments of the program. The compiled machine code executes faster than the repeated interpretation of bytecode.

12) Explain ‘this' keyword in Java.

In Java, the ‘this’ keyword is used to denote the current object instance. It is used to differentiate between instance variables and parameters, call the current instance methods and variables, and pass the current object as a parameter.

Improve Web Development skills through our Web Development Using Java Training. Join now!

13) Explain Method Overloading in Java.

The process of creating multiple method signatures using one method name is called Method Overloading in Java. Two ways to achieve method overloading are:

1) Varying the number of arguments

2) Changing the return type of the Method

14) Can we overload a static method?

Yes, there are static methods that can be overloaded in Java as well. Method overloading is a technique where multiple methods can share the same name but different parameter lists in a class

15) Define Late Binding.

Late binding, or dynamic binding, is a programming concept where method invocation is determined at runtime based on the object's actual type. It enables polymorphic behavior, allowing different objects to respond differently to the same method call.

16) Define Dynamic Method Dispatch.

Dynamic method dispatch is a feature in Object-Oriented Programming where method calls are resolved at runtime based on the actual type of the object. It enables polymorphic behavior by allowing subclass methods to override superclass methods, providing flexibility and runtime flexibility.

17) Explain in brief the life cycle of an applet.

An applet's life cycle in Java follows these key stages:

1) Initialisation: The applet is initialised, memory is allocated, and initial setup occurs when the applet is first loaded

2) Start: The applet starts, initiating animations or processes when the user enters the webpage

3) Run: The applet runs, interacting with the user and performing its core functions

4) Stop: The applet stops, pausing animations or processes when the user leaves the webpage

5) Destroy: The applet is destroyed, releasing resources and freeing memory when the user leaves the webpage or closes the browser

18) Why are generics used in Java Programming?

Generics in Java takes care of the type safety issue at the compile time, preventing the use of mismatching types at runtime. They allow one or more methods/classes to be specified indicating with which arguments these methods/classes are available. This also improves readability of code and reusability, thus making castings less likely while preventing runtime errors.

19) Explain the Externalisable interface.

The Externalisable interface in Java is used for custom serialisation and deserialisation of objects. Classes that implement this interface must define methods for writing and reading their state to and from an external source, such as a file or network stream.

20) Explain the term enumeration in Java.

In Java, an enumeration, or enum, is a special data type used to define a set of named constants. Enums are declared using the enum keyword and are typically used to represent a fixed number of possible values for a variable, providing type safety and clarity in code.

Join our Web Development Using Java Training today and master the skills to build dynamic web applications!

Java Interview Questions for Experts Level

1) What is Servlet Session Management in Java? 

Servlet Session Management is used to store session data in a Web container. In this mechanism, user’s data is managed by the session tracking method. Some other methods used to manage sessions in Java, are Cookies, HTTP Session API, URL writing, Hidden Fields, etc.  

2) What is stream pipelining in Java? 

A stream is a series of objects that support different methods that can be pipelined to produce the desired result. Stream pipelining is the concept of changing operations together. It is an API used to process the set of objects.

1) Stream and data structure are not same, but the process of stream is same as data structure. Stream takes data from collections, Array and input and output channels 

2) Stream provides the result based on the pipelined methods 

3) Every intermediate operation is slowly executed and returns a stream as a result

3) What are JCA and JPA in java? 

JCA: Java EE Connector Architecture and J2EE Connector Architecture. It is used to connect application servers by connecting an enterprise’s data system.  

JPA: Java Persistence API. It is the standard API for persistence and object/relational mapping for the Java EE platform. It is crucial to Java developers for data binding purposes.  

4) Problem: Can you sort HashMap by keys and values? 

import java.text.ParseException;  

import java.util.ArrayList;  

import java.util.Collections;  

import java.util.Comparator;  

import java.util.HashMap;  

import java.util.LinkedHashMap;  

import java.util.List;  

import java.util.Map.Entry;  

import java.util.Set;  

import java.util.TreeMap; 

public class HashMapSorting {  

         public static void main(String args[]) throws ParseException {

                   HashMap codenames = new HashMap(); 

                   codenames.put("JDK 1.1.4", "Sparkler"); 

                   codenames.put("J2SE 1.2", "Playground"); 

                   codenames.put("J2SE 1.3", "Kestrel"); 

                   codenames.put("J2SE 1.4", "Merlin"); 

                   codenames.put("J2SE 5.0", "Tiger"); 

                   codenames.put("Java SE 6", "Mustang"); 

                   codenames.put("Java SE 7", "Dolphin"); 

                    System.out.println("HashMap before sorting, random order ");  

                   Set> entries = codenames.entrySet();      

                             for(Entry entry : entries){  

                     System.out.println(entry.getKey() + " ==> " + entry.getValue());  

                     TreeMap sorted = new TreeMap<>(codenames); 

                   Set> mappings = sorted.entrySet(); 

         System.out.println("HashMap after sorting by keys in ascending order ");  

         for(Entry mapping : mappings){  

                System.out.println(mapping.getKey() + " ==> " + mapping.getValue()); 

      Comparator> valueComparator  

                 = new Comparator>() {  

             @Override  

            public int compare(Entry e1, Entry e2) {  

                  String v1 = e1.getValue();  

                  String v2 = e2.getValue();  

                  return v1.compareTo(v2); 

   } 

        }; 

  List> listOfEntries  

           = new ArrayList>(entries); 

     Collections.sort(listOfEntries, valueComparator);  

     LinkedHashMap sortedByValue 

                           = new LinkedHashMap(listOfEntries.size()); 

     for(Entry entry : listOfEntries){  

           sortedByValue.put(entry.getKey(), entry.getValue());  

     System.out.println("HashMap after sorting entries by values ");  

     Set> entrySetSortedByValue = sortedByValue.entrySet();  

     for(Entry mapping : entrySetSortedByValue){  

            System.out.println(mapping.getKey() + " ==> " + mapping.getValue());  

            }  

       }  


Output:  

HashMap before sorting, random order  

Java SE 7 ==> Dolphin  

J2SE 1.2 ==> Playground  

Java SE 6 ==> Mustang  

J2SE 5.0 ==> Tiger  

J2SE 1.3 ==> Kestrel  

J2SE 1.4 ==> Merlin  

JDK 1.1.4 ==> Sparkler  

HashMap after sorting by keys in ascending order  

J2SE 1.2 ==> Playground  

J2SE 1.3 ==> Kestrel  

J2SE 1.4 ==> Merlin  

J2SE 5.0 ==> Tiger  

JDK 1.1.4 ==> Sparkler  

Java SE 6 ==> Mustang  

Java SE 7 ==> Dolphin  

HashMap after sorting entries by values  

Java SE 7 ==> Dolphin  

J2SE 1.3 ==> Kestrel  

J2SE 1.4 ==> Merlin  

Java SE 6 ==> Mustang  

J2SE 1.2 ==> Playground 

 JDK 1.1.4 ==> Sparkler  

J2SE 5.0 ==> Tiger 
                                               
5) Problem: Can you remove duplicates in an Array List? 

Removing duplicates in an Array List using LinkedHashSet 

ArrayListExample.java 

import java.util.ArrayList; 

import java.util.Arrays; 

import java.util.LinkedHashSet; 

  public class ArrayListExample  

    public static void main(String[] args)  

    { 

        // ArrayList with duplicate elements 

        ArrayList numbersList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8)); 

                  System.out.println(numbersList); 

          LinkedHashSet hashSet = new LinkedHashSet<>(numbersList); 

              ArrayList listWithoutDuplicates = new ArrayList<>(hashSet); 

                System.out.println(listWithoutDuplicates); 

    } 

}

Output: 

Console 

[1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8] 

[1, 2, 3, 4, 5, 6, 7, 8] 

6) Problem: Can you reverse a string using Java? 

Reversing a string using a loop in Java

public class ReverseStringByFavTutor 
 

 
   public static void main(String[] args) { 
  
       String stringExample  =  "FavTutor"; 
 
       System.out.println("Original string: "+stringExample); 
 
        StringBuilder reverseString = new StringBuilder(stringExample); 
 
        reverseString.reverse();   
   
       String result = reverseString.toString(); 
 
        System.out.println("Reversed string: "+result); 
  
   } 
 

Output:

Original string: FavTutor 
 
Reversed string: rotuTvaF 

Enhance Java skills through our Introduction to Java EE Training. Sign up now!

7) Problem: Can you find if a string is present in a text file? 

import java.io.BufferedReader; 

import java.io.FileNotFoundException; 

import java.io.FileReader; 

import java.io.IOException; 

public class StringFinder { 

public static void main(String[] args) 

    double count = 0,countBuffer=0,countLine=0; 

    String lineNumber = ""; 

    String filePath = "C:UsersvikiDesktopTestText.txt"; 

    BufferedReader br; 

    String inputSearch = "are"; 

    String line = ""; 

    try { 

        br = new BufferedReader(new FileReader(filePath)); 

        try { 

            while((line = br.readLine()) != null) 

            { 

                countLine++; 

                //System.out.println(line); 

                String[] words = line.split(" "); 

 

                for (String word : words) { 

                  if (word.equals(inputSearch)) { 

                    count++; 

                    countBuffer++; 

                  } 

                } 

                if(countBuffer > 0) 

                { 

                    countBuffer = 0; 

                    lineNumber += countLine + ","; 

                } 

            } 

            br.close(); 

        } catch (IOException e) { 

            // TODO Auto-generated catch block 

            e.printStackTrace(); 

        } 

    } catch (FileNotFoundException e) { 

        // TODO Auto-generated catch block 

        e.printStackTrace(); 

    } 

    System.out.println("Times found at--"+count); 

    System.out.println("Word found at--"+lineNumber); 

}  

8) What is a JSP page?

JSP is an abbreviation for Java Servlet Page. The JSP page consists of two types of text.

1) Static Data 

JSP elements

9) Write a program that detects the duplicate characters in a string.

import java.util.HashMap;

import java.util.Map;

public class DuplicateCharacters {

    public static void main(String[] args) {

        String str = "programming";

        Map charCountMap = new HashMap<>();

        // Count occurrences of each character

        for (char c : str.toCharArray()) {

            charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);

        }

        // Display duplicate characters

        System.out.println("Duplicate characters in the string '" + str + "':");

        for (Map.Entry entry : charCountMap.entrySet()) {

            if (entry.getValue() > 1) {

                System.out.println(entry.getKey() + ": " + entry.getValue() + " occurrences");

            }

        }

    }

}


Conclusion

Mastering Top 80 Java Interview Questions is crucial for aspiring developers to showcase their expertise and secure rewarding career opportunities. By diligently studying and understanding the topics covered in this blog, candidates can confidently navigate Java Interviews, demonstrating their proficiency and readiness for professional challenges in the field. 

Learn and master the important concept of GUI Programming with Java Swing Development Training .

Frequently Asked Questions

Upcoming Programming & DevOps Resources Batches & Dates

Date

building Java Programming

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross

BIGGEST
Cyber Monday SALE!

red-starWHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.