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.

What is Java?

faq-arrow

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

What is a functional interface in Java?

faq-arrow

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.

What are the features of Java?

faq-arrow

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.
 

Differences between Stack and Heap memory in Java?

faq-arrow

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

What is main() method in Java?

faq-arrow

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[])

What are JVM, JRE, and JDK?

faq-arrow

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. 
 

Differences between == and equals() in Java?

faq-arrow

==

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

Why Java is not a pure Object-Oriented language?

faq-arrow

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.

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

faq-arrow

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

 

What are the differences between C++ and Java?

faq-arrow

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
 

What are the Memory Allocations available in Java?

faq-arrow

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

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

faq-arrow

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

What is the default value stored in Local Variables?

faq-arrow

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.
 

What is an Association?

faq-arrow

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.

What do you mean by aggregation?

faq-arrow

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.

Define Copy Constructor in Java

faq-arrow

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

What is a Marker Interface?

faq-arrow

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

What is Object Cloning?

faq-arrow

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

Define Wrapper Classes in Java.

faq-arrow

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.

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

faq-arrow

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
 

Define package in Java.

faq-arrow

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

Differentiate between instance and local variables

faq-arrow

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.

Explain Java String Pool

faq-arrow

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.

What is an Exception?

faq-arrow

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

What is the final keyword in Java?

faq-arrow

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. The Final Keyword in Java plays a crucial role in ensuring the integrity and immutability of these elements in your code.

Why is the main method static in Java?

faq-arrow

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.

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

faq-arrow

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.
 

Can you explain the Java thread lifecycle?

faq-arrow

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.
 

Explain the term “Double Brace Initialisation” in Java?

faq-arrow

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).

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

faq-arrow

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.

Write a Java Program to print Fibonacci Series using Recursion.

faq-arrow

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);

        }

    }

}

 

Write a Java program to create and throw custom exceptions.

faq-arrow
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());
        }
    }
}
 

 

Implement Binary Search in Java using recursion.

faq-arrow

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:

What is ‘super’ keyword in Java?

faq-arrow

‘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.

Why is Java a Dynamic programming language?

faq-arrow

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.

Explain Daemon Thread in Java.

faq-arrow

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!
 

What is JDBC Driver?

faq-arrow

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,  

What is “OutofMemoryError” in Java?

faq-arrow

”OutOfMemoryError” in Java is a runtime error. It occurs when JVM 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)” 
 

Differences between HashMap and HashTable in Java?

faq-arrow

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 synchronised

Method is synchronised

High performance

Low performance

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

faq-arrow

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. 

What is a ClassLoader?

faq-arrow

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.

What is constructor in Java?

faq-arrow

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.

What is JDK? Mention the variants of JDK?

faq-arrow

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.

What is a JIT compiler?

faq-arrow

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.

Explain ‘this' keyword in Java.

faq-arrow

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!
 

Explain Method Overloading in Java.

faq-arrow

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
 

Can we overload a static method?

faq-arrow

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

Define Late Binding.

faq-arrow

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.

Define Dynamic Method Dispatch.

faq-arrow

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.

Explain in brief the life cycle of an applet.

faq-arrow

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

 

Why are generics used in Java Programming?

faq-arrow

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.

Explain the Externalisable interface.

faq-arrow

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.

Explain the term enumeration in Java.

faq-arrow

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

Explain the term enumeration in Java.

faq-arrow

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. 

What is stream pipelining in Java?

faq-arrow

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

What are JCA and JPA in java?

faq-arrow

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.  

Problem: Can you sort HashMap by keys and values?

faq-arrow

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
 

 

Problem: Can you remove duplicates in an Array List?

faq-arrow

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] 
 

 

Problem: Can you reverse a string using Java?

faq-arrow

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!

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

faq-arrow

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); 

}  

 

 

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

1) Static Data 

JSP elements

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

faq-arrow

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");

            }

        }

    }

}

 

Find the word count in a string using HashMap Collection

faq-arrow

import java.util.HashMap;

import java.util.Map;

 

public class WordCount {

    public static void main(String[] args) {

        String str = "Hello world! This is a sample sentence. Hello again.";

 

        // Remove punctuation and convert to lowercase

        str = str.replaceAll("[^a-zA-Z ]", "").toLowerCase();

 

        // Split the string into words

        String[] words = str.split("s+");

 

        // Create a HashMap to store word counts

        Map wordCountMap = new HashMap<>();

 

        // Count occurrences of each word

        for (String word : words) {

            wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);

        }

 

        // Display word counts

        System.out.println("Word count in the string:");

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

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

        }

    }

}

 

Can the main method be overloaded?

faq-arrow

Yes, the main method in Java can be overloaded. Overloading allows defining multiple methods with the same name but different parameter lists. However, only the specific signature public static void main(String[] args) serves as the entry point for the application.

When can you use the "super" keyword?

faq-arrow

The super keyword is used to access the parent class. When there exist the same fields in both parent and child classes, then a use of a super keyword is possible to access data members of a parent class.

What are shallow copy and deep copy in Java?

faq-arrow

In the case of a shallow copy, primitive data types are copied, whereas in the case of a deep copy along with primitive data types of the object references are also copied.

Using relevant properties highlight the differences between interfaces and abstract classes.

faq-arrow

An abstract class can have a combination of both abstract and non-abstract methods, whereas an interface has only abstract methods in it.

What are the different ways of thread usage?

faq-arrow

Thread usage in Java includes extending the Thread class or implementing the Runnable interface.

What is the difference between the ‘throw' and ‘throws' keyword in Java?

faq-arrow

The 'throw' keyword in Java is used to explicitly throw an exception within a method or block of code, whereas the 'throws' keyword is used in method signatures to declare the exceptions that a method may throw, delegating the responsibility of handling those exceptions to the caller.

How is an infinite loop declared in Java?

faq-arrow

An infinite loop can be declared in Java by breaking the logic in the instruction block. For example:
 

while (true) {
    // Code inside this block will run indefinitely
}
 

What is the main objective of garbage collection?

faq-arrow

The main goal of using garbage collection is to free the heap memory by eliminating unnecessary objects.

Can you have virtual functions in Java?

faq-arrow

Yes, all non-static methods in Java are implicitly virtual, allowing them to be overridden by subclasses.

What is the covariant return type?

faq-arrow

Covariant return type in Java allows overriding a superclass method in a subclass with a return type that is a subtype of the return type declared in the superclass, providing more flexibility in method overriding.

What is the final variable?

faq-arrow

A final variable in Java is a variable that cannot be changed once it is initialised.

What is the final method?

faq-arrow

A final method in Java is a method that cannot be overridden in a subclass.  

What is the final class?

faq-arrow

A final class in Java is a class that cannot be subclassed.

What is the final blank variable?

faq-arrow

The final blank variable in Java is one not initialised when declared.

Difference between the final method and the abstract method.

faq-arrow

A final method in Java cannot be overridden by subclasses, providing a fixed implementation. An abstract method is declared in an abstract class or interface without implementation, requiring subclasses to provide their own implementation.

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross
Unlock up to 40% off today!

Get Your Discount Codes Now and Enjoy Great Savings

WHO 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.