![Post thumbnail](https://www.guvi.in/blog/wp-content/uploads/2023/08/feature-image-Core-Java-Interview-Questions-and-Answers.webp)
Top 100 Core Java Interview Questions and Answers 2024
Sep 05, 2024 13 Min Read 6964 Views
(Last Updated)
Java is a high-level programming language developed by James Gosling that is based on the principles of object-oriented programming and can be used to develop large-scale applications. Java is one such programming language or skill that top MNCs look for in learners. You must be very well-versed in Java and should know some of the top Java interview questions and answers to crack tech interviews.
In this blog, we’ll have curated the top 100 Java Interview Questions and Answers, especially for Java learners, to help them clear tech interviews in one go. These Java interview questions and answers are hand-picked and revolve around the basic, core, and advanced fundamentals of Java, and they will definitely be asked by interviewers. Java developers must focus on these questions and be thorough with them. Without much ado, let’s begin:
Table of contents
- Top Core Java Interview Questions and Answers
- Q1: What is Java?
- Q2: Why do we go for Java?
- Q3: What are the main features of Java?
- Q4: What is platform-independent?
- Q5: What is meant by open-source?
- Q6: What types of tools are used to execute Java?
- Q7: What are the differences between the JDK, JVM, and JRE?
- Q8: What is meant by OOPS?
- Q9: What are the coding standards used in Java?
- Q10: What do you mean by class, method, or object?
- Q11: What is meant by encapsulation?
- Q12: What are the datatypes used in Java?
- Q13: What is the byte size and range of int datatypes?
- Q14: What is mean by Wrapper class?
- Q15: What is the main use of the scanner class?
- Q16: What are the methods available in the Scanner Class?
- Q17: What is meant by inheritance?
- Q18: What are the ways to access the methods or data from another class?
- Q19: What is meant by polymorphism?
- Q20: What are the differences between method overloading and overriding?
- Q21: What are the types of inheritance?
- Q22: Why multiple inheritance is not supported in Java?
- Q23: What are the differences between Multiple and Multilevel inheritance?
- Q24: What is meant by access specifier?
- Q25: What are the differences between public and protected?
- Q26: What is meant by Abstraction?
- Q27: What are the types of Abstraction?
- Q28: Can we create an Object for the Abstract class?
- Q29: What is meant by Interface?
- Q30: What are the differences between Abstract and Interface?
- Q31: What is meant by String?
- Q32: What are the methods available in a string?
- Q33: What is meant by constructor?
- Q34: What are the types of constructors?
- Q35: Do constructors have any return type?
- Q36: Write a syntax for creating a constructor.
- Q37: What are the rules for defining a constructor?
- Q38: Why a return type is not allowed for the constructor?
- Q39: Can we declare the constructor as 'private'?
- Q40: Why a compiler-given constructor is called a default constructor?
- Q41: What is constructor chaining and how can it be achieved in Java?
- Q42: What are the differences between this() and super()?
- Q43: What is the super-class of all Java?
- Q44: What are the types of variables?
- Q45: What is meant by local variable, instance variable, class/static variable?
- Q46: What is meant by static keyword in Java?
- Q47: Can we override static methods in Java?
- Q48: Can we overload static methods in Java?
- Q49: What is meant by static variable?
- Q50: What is meant by static method?
- Q51: What is meant by the final keyword and what's happened when we declare final as in class, method, and variable?
- Q52: What is the difference between the final and finally keyword?
- Q53: Where do local, static, and class variables stored in JVM?
- Q54: What is an Exception?
- Q55: What are the types of Exceptions?
- Q56: What are the differences between checked exceptions and unchecked exceptions?
- Q57: What is the super-class for Exception and Error?
- Q58: Can we have a try block without a catch block?
- Q59: Can we write multiple catch blocks under a single try block?
- Q60: How to write user-defined exceptions or custom exceptions in Java?
- Q61: What are the different ways to print exception messages on the console?
- Q62: What are the differences between final finally and finalize in Java?
- Q63: What are the differences between throw and throws?
- Q64: Explain Java Exception Hierarchy.
- Q65: What is meant by throw and throws?
- Q66: What is meant by an array?
- Q67: What are the advantages and disadvantages of an array?
- Q68: Write a code to initialize an array.
- Q69: Can we change the memory size of an array after initialization?
- Q70: What is a collection?
- Q71: What is the difference between ArrayList and Vector?
- Q72: What is the difference between ArrayList and LinkedList?
- Q73: How to convert Array to List and List to Array?
- Q74: Describe the Collections type hierarchy What are the main interfaces?
- Q75: What is the difference between a set and a List?
- Q76: What is the difference between HashSet and TreeSet?
- Q77: How to convert List into Set?
- Q78: What is a map?
- Q79: What is the difference between Hash Map and Hash Table?
- Q80: What is the difference between a set and a Map?
- Q81: Can we iterator the list using normal for loop?
- Q82: What are the methods available in the list but not in the set?
- Q83: Explain about user-defined Map.
- Q84: How much null allows in the below maps:
- Q85: How to Iterate Map?
- Q86: What is the return type of entrySet?
- Q87: Write the methods to get the key only and value only?
- Q88: What is meant by File? In which package it is available?
- Q89: What are the methods available in a File ?
- Q90: While creating a file if we do not mention the format then under which format will it save the file?
- Q91: What are the differences between the append and updating the file?
- Q92: What is meant by Enumerator, Iterator, and List Iterator?
- Q93: Difference between Enumurator, Iterator, and List Iterator?
- Q94: What are the methods available in Enumerator, Iterator and List Iterator?
- Q95: Explain JDBC connection steps.
- Q96: What are control statements?
- Q97: What are the differences between break and continue?
- Q98: What is the difference between a while and a do-while loop?
- Q99: What is the difference between an if and an if-else loop?
- Q100: What is the difference between an Immutable and mutable string?
- Q101: What is the difference between Removeall() and Retainall()?
- Q102: What is the difference between a Literal String and a Non-literal string?
- Q103: What is the difference between Heap and stack memory?
- Q104: What is the default Package in Java?
- Q105: What is the difference between equals() & hashcode()?
- Q106: Difference between a string buffer and a string builder?
- Q107: What is a String Constant pool?
- Q108: Difference between Collection and Collections?
- Q109: Why do we need to go for collection when there is already an Array concept?
- Q110: Why do we need to go for collection when there is already an Array concept?
- Conclusion
- FAQs
- Q1. What are the core Java interview questions?
- Q2. How to prepare for core Java interview questions?
- Q3. What are the four core concepts of Java?
Top Core Java Interview Questions and Answers
Let’s go through some of the top Java interview questions and answers which can be asked by interviewers:
Q1: What is Java?
Java is a versatile, object-oriented programming language, developed by Sun Microsystems. It has automatic memory management and a robust standard library, supports multithreading, and excels at building scalable applications.
Q2: Why do we go for Java?
There are various reasons why you should go for Java. Some of them are:
- It is platform-independent and open-source.
- It runs multiple applications at once.
Q3: What are the main features of Java?
- Platform independent
- Open source
- Multithreading
- More secure
- Portable
Q4: What is platform-independent?
Java has “write once, run anywhere”, which means that during the compilation, the Java program converts into byte code. Using byte code, we can run the application on any platform, such as Windows, Mac, Linux, etc. This is known as being platform-independent.
Q5: What is meant by open-source?
A program in which source code is available to the general public for use and/or modification from its original design at no cost is called open source.
Q6: What types of tools are used to execute Java?
- Notepad
- Net bean
- Eclipse
- J Developer(oracle)
- RAD(IBM)
Q7: What are the differences between the JDK, JVM, and JRE?
JDK:
- Java Development Kit.
- If we want to run any applications in Java, we need JDK to be installed.
- JDK versions: 1.0 to 1.10.
JRE:
- Java Runtime Environment.
- It is a predefined class file (i.e.) a library file).
JVM:
- Java Virtual Machine.
- It is mainly used to allocate memory and compile.
Before proceeding further, make sure you have a strong grasp of essential concepts in Java Full Stack Development, including front-end frameworks, back-end technologies, and database management. If you’re looking for a professional future in Java Full Stack Development, consider joining GUVI’s Java Full Stack Development Career Program. With placement assistance included, you’ll master the Java stack and build real-world projects to enhance your skills.
Also, if you’re looking for a self-paced course in Java in your language, you can go for GUVI’s Java Course with Certification to help you master Java from basics to advanced level.
Q8: What is meant by OOPS?
Object-Oriented Programming Structure (OOPS) is a method of implementation in which programs are organized as a collection of objects, classes, and methods.
Q9: What are the coding standards used in Java?
- Pascal notation: Each and every word of the first letter should be in capital letters. Example: GuviGeek
- Camel notation: The first word should be small, and every word of the first letter should be capitalized. Example: guviGeek
Q10: What do you mean by class, method, or object?
Class: A class is nothing but a collection of methods or objects.
Method: A method is nothing but a set of actions to be performed.
Object: Object is the run-time memory allocation.
Using objects, we call any methods.
Q11: What is meant by encapsulation?
Encapsulation is one of the fundamental principles of object-oriented programming (OOP) that refers to the bundling of data (attributes or fields) and methods (functions or procedures) that operate on that data into a single unit called a class.
Q12: What are the datatypes used in Java?
- byte
- short
- int
- long
- float
- double
- boolean
- char
- String
Q13: What is the byte size and range of int datatypes?
- The size of a byte is 1 byte (8-bit)
- Range formula =[-2^(n-1)] to [(2^(n-1))-1] for int n=32.
Q14: What is mean by Wrapper class?
Classes of data types are called wrapper classes and are used to convert any data type into an object. All classes and wrapper classes’ default value is Null.
Q15: What is the main use of the scanner class?
The main use of the scanner class is to get input from the user at runtime.
Q16: What are the methods available in the Scanner Class?
- nextByte();
- nextShort();
- nextInt();
- nextLong();
- nextFloat();
- nextDouble();
- next().charAt(0);
- next();
- nextLine();
- nextBoolean();
Q17: What is meant by inheritance?
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class (subclass or derived class) to inherit properties and behaviors (data fields and methods) from an existing class (superclass or base class). Inheritance creates a hierarchical relationship between classes, facilitating code reuse and the creation of more specialized classes based on existing ones.
Q18: What are the ways to access the methods or data from another class?
We can access the other class methods either by creating an object or using extends keyword.
Q19: What is meant by polymorphism?
Poly means many and morphism means forms. Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass.
Q20: What are the differences between method overloading and overriding?
Method overloading(static binding/compile time polymorphism):
- Class-same
- Method-same
- Argument-differ based on datatype, order, number
Method overriding(dynamic binding/run time polymorphism):
- Class name-differ(using extends)
- Method-same
- Argument-same
Q21: What are the types of inheritance?
- Single Inheritance
- Multilevel Inheritance
- Multiple Inheritances
- Hybrid Inheritance
- Hierarchical Inheritance
Q22: Why multiple inheritance is not supported in Java?
- Priority problem
- Compilation error/syntax error
(i.e) if both parent classes have the same method name it will get a priority problem so it doesn’t work in Java.
Q23: What are the differences between Multiple and Multilevel inheritance?
Multiple inheritance:
- A combination of more than one parent class directly supported one child class.
- It won’t work in Java due to a priority problem.
Multilevel inheritance:
- A combination of more than one parent class and child class using a tee-level structure.
- It works in Java.
Q24: What is meant by access specifier?
In Java, access specifiers are keywords that determine the visibility or accessibility of classes, fields (variables), methods, and constructors in different parts of your code. There are 4 main access specifiers:
Public
Private
Protected
Default
Q25: What are the differences between public and protected?
Public: It is global-level access( same package + different package). Members (classes, methods, fields) marked as public
are accessible from anywhere in the code, both within the same class and from other classes.
Protected: Inside package + outside Package (Extends). Members are marked as protected
accessible within the same class, subclasses (even if they are in different packages), and other classes in the same package. They are not accessible from classes in different packages that are not subclasses.
Q26: What is meant by Abstraction?
Abstraction is a core concept in object-oriented programming (OOP) that focuses on simplifying complex reality by modeling classes based on their essential attributes and behaviors. It involves hiding the complex implementation details of an object while exposing a simplified and well-defined interface for interaction.
Q27: What are the types of Abstraction?
- Partially abstraction(abstract class).
- Fully abstraction(interface).
Q28: Can we create an Object for the Abstract class?
No, we can’t create objects for abstract classes.
Q29: What is meant by Interface?
In Java, an interface is a reference type that serves as a contract for classes that implement it. It defines a set of method signatures (without implementations) that must be provided by any class that claims to implement the interface.
Q30: What are the differences between Abstract and Interface?
Abstract class:
- It is partially abstract.
- It supports both abstract methods and non-abstract methods.
- It uses the “extends” keyword.
- Here “public abstract” have to mention.
- We can use whatever access specifier we want.
Interface:
- It is fully abstract.
- It supports only abstract methods.
- It uses the “implement” keyword.
- “public Abstract” is default no need to mention it.
- Here we use only public( access specifier).
Q31: What is meant by String?
Collections of characters or words enclosed with double quotes are called String.
Example: “guvigeek”.
Q32: What are the methods available in a string?
- Equals();
- Equalsignorecase();
- contains();
- split();
- toUpperCase();
- toLowerCase();
- subString();
- isEmpty();
- identifyHashCode();
- startsWith();
- endsWith();
- CompareTo();
- charAt();
- indexOf();
- lastIndexOf();
- replace();
Q33: What is meant by constructor?
In Java, a constructor is a special type of method that is automatically called when an object of a class is instantiated (created). It is used to initialize the newly created object and set its initial state.
Q34: What are the types of constructors?
- Parameterized constructor
- Non parameterized constructor
Q35: Do constructors have any return type?
No, the constructor can’t have any return type.
Q36: Write a syntax for creating a constructor.
Access_specifier classname(){
}
Q37: What are the rules for defining a constructor?
- The class name and constructor name must be the same.
- It doesn’t have any return type.
Q38: Why a return type is not allowed for the constructor?
A constructor is not directly called by your code, it’s called by memory allocation and object initialization in the run time. Its return value is opaque to the user so we can’t mention it.
Q39: Can we declare the constructor as ‘private’?
Yes, we can declare the constructor as private.
Q40: Why a compiler-given constructor is called a default constructor?
If we won’t pass the constructor explicitly it will take the default constructor.
Q41: What is constructor chaining and how can it be achieved in Java?
- The process of calling one constructor from another constructor with respect to the current object is called constructor chaining.
- By using this() we can achieve constructor chaining.
Q42: What are the differences between this() and super()?
- this() is used to call the class-level constructor.
- super() is used to call the constructor in the parent class.
Q43: What is the super-class of all Java?
An object is the super-class of all Java.
Q44: What are the types of variables?
- Local level variable.
- Class level variable.
- Super level variable.
Q45: What is meant by local variable, instance variable, class/static variable?
- Static Variable – It is used to share the same variable or method of a given class.
- Local Variable – It will declare below the main method.
- Class variable- – It will access only within the class.
Q46: What is meant by static keyword in Java?
The static keyword is mainly used for memory management and is used to share the same variable or method of a given class.
Q47: Can we override static methods in Java?
No, we can’t override the static method because it is part of a class rather than an object.
Q48: Can we overload static methods in Java?
Yes, we can overload the static method in Java.
Q49: What is meant by static variable?
When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. Static variables are essentially, global variables. All the instances of the class share the same static variable.
Q50: What is meant by static method?
Static methods in Java belong to the class(not to an object). They use no instance variables and will usually take the input from the parameters and perform an action on it, then return some result.
Q51: What is meant by the final keyword and what’s happened when we declare final as in class, method, and variable?
- Final is a non-access modifier applicable only to a variable, a method, or a class.
- When a variable is declared with the final keyword, its value cant be modified essentially a constant.
- When a method is declared as final we can prevent method overriding.
- When a class is declared as final we can prevent inheritance.
Q52: What is the difference between the final and finally keyword?
Final:
- Final variable can’t be modified.
- Final method can’t be overridden.
- Final class can’t be inherited.
Finally:
Finally part will execute the important code whether the exception is handled or not.
Q53: Where do local, static, and class variables stored in JVM?
- Static variables are stored in the permGen section of heap memory.
- Local variables are stored in the stack.
- Class variables are stored in heap memory.
Q54: What is an Exception?
In Java, an exception is an event that occurs during the execution of a program and disrupts the normal flow of instructions. It is an instance of a class that is derived from the Throwable
class (or its subclasses).
Q55: What are the types of Exceptions?
- Unchecked exception(Run time exception)
- Checked exception(Compile time exception)
Q56: What are the differences between checked exceptions and unchecked exceptions?
Unchecked exception: It will occur at the Run time exception.
Checked exception: Checked exception will occur at the Compile time exception.
Q57: What is the super-class for Exception and Error?
Throwable Exception.
Q58: Can we have a try block without a catch block?
No, we haven’t a try block without catch block.
Q59: Can we write multiple catch blocks under a single try block?
Yes, we write multiple catch blocks under the single try block.
Q60: How to write user-defined exceptions or custom exceptions in Java?
Access_specifier method_name throws customException { throw new customException();
}
Q61: What are the different ways to print exception messages on the console?
ref.printStackTrace() method is used to print the exception message from the console.
Q62: What are the differences between final finally and finalize in Java?
Final:
- A final class variable whose value cannot be changed.
- A final is declared as class level, they cannot be inherited.
- If the final is declared as method level, they cannot be overridden.
Finally:
- It’s a block of statements that definitely executes after the try-catch block.
- If the try block fails means, the final block will execute once.
Finalize:
It will clean up processing memory space.
Q63: What are the differences between throw and throws?
Throw:
- Throw is a keyword, we can through any exception inside the method.
- At a time we can throw only one exception.
Throws:
- Throws is a keyword, it is used to declare the exception (at the method level).
- At a time we can declare more than one exception.
Q64: Explain Java Exception Hierarchy.
Exception
- Unchecked exception(Run time exception)
- ArithmaticException
- NullPointException
- InputMismatchException
- ArrayIndexOutOfBoundExcepion
- StringIndexOutOfBoundExcepion
- IndexOutOfBoundExcepion
- NumberFormatException
- Checked exception(Compile time exception)
- IOException
- SQLException
- FileNotFoundException
- ClassNotFoundException
Q65: What is meant by throw and throws?
Throw | Throws |
Checked Exceptions can not be propagated using Throw only | Checked Exceptions can be propagated using throws |
The throw is followed by an instance | Throws is followed by a class |
A throw is used within the method | The throws keyword is used to declare an exception |
A throw keyword is used to declare an exception | Multiple exceptions can be declared using throws: Public void method()throws IO exception, SQL Exception |
We can only throw one exception | Multiple exceptions can be declared using throws Ex: Public void method()throws IO exception, SQL Exception |
Q66: What is meant by an array?
An array is a data structure in programming that stores a fixed-size collection of elements of the same data type. Each element in an array is accessed by its index, which is a numeric value that represents its position in the array.
Q67: What are the advantages and disadvantages of an array?
Advantage:
In a single variable, we can store multiple values.
Disadvantages:
- It supports only similar data types.
- It is a fixed-size one.
- Memory wastage is high.
Q68: Write a code to initialize an array.
- Initializing without assigning any values:
Datatype refName[]= new Datatype[size];
class HelloWorld
{
public static void main(String[] args)
{
// Initializing an array of integers with specific values
int[] array= new int[5];
array for(int i = 0; i <5; i++)
{
System.out.println(array[i]);
}
}
}
Q69: Can we change the memory size of an array after initialization?
No, we can’t change the memory size of an array after initialization.
Q70: What is a collection?
Collection Framework is a combination of classes and interfaces, which is used to store and manipulate the data in the form of objects. It provides various classes such as ArrayList, Vector, Stack, and HashSet, etc., and interfaces such as List, Queue, Set, etc. for this purpose.
- It will support dissimilar data types.
- It is dynamic memory allocation.
- No memory wastage like an array.
Q71: What is the difference between ArrayList and Vector?
ArrayList | Vector |
ArrayList is not synchronized i.e.executed parallel | Vector is Synchronous ( executed one byone) |
Not Thread safe | Vector is Synchronous ( executed one by one) |
ArrayList increases its size by 50% of the array size | Vector is a legacy class |
Vector increases its size by doubling theArray size | Vector is thread-safe |
Q72: What is the difference between ArrayList and LinkedList?
LinkedList:
- Insertion and deletion is the best one.
- Searching/retrieving is the worst.
- It makes performance issue.
ArrayList:
- In Arraylist retrieve/searching is the best one
- In ArrayList deletion and insertion is the worst one because if we delete/insert one index value after all the index move to forward/backward.
- It makes performance issue.
Q73: How to convert Array to List and List to Array?
- Native Method
- Using Arrays.asList() Method
- Using Collections.addAll() Method
- Using Java 8 Stream API
- Using Guava Lists.newArrayList() Method
Q74: Describe the Collections type hierarchy What are the main interfaces?
Main Interface:
- List
- Set
- Map
The hierarchy is as follows:
List:
- ArrayList
- LinkedList
- Vector
Set:
- HashSet
- LinkedHashSet
- TreeSet
Map:
- HashMap
- LinkedHashMap
- Hashtable
- TreeMap
- ConcurrentHahMap
Q75: What is the difference between a set and a List?
Set:
- It is a value-based one.
- It prints in random order.
- It won’t allow duplicates.
List:
- It is an Index based one.
- It prints in insertion order.
- It allows duplicates.
Q76: What is the difference between HashSet and TreeSet?
Hash set is implemented using HashTable | The tree set is implemented using a tree structure. |
HashSet allows a null object | The tree set does not allow the null object. It throws the null pointer exception. |
Hash set use equals method to compare two objects | The tree set allows a heterogeneous object |
Hash set doesn’t now allow a heterogeneous object | Hash set use the equals method to compare two objects |
HashSet does not maintain any order | TreeSet maintains an object in sorted order |
Q77: How to convert List into Set?
By addAll() we can convert List into set.
Q78: What is a map?
- A map is an interface that is present in java.util package.
- It is used to represent the mapping between key and value.
- It is a key and value pair.
- Here key+value is one entry.
- Key ignore the duplicate value and value allow the duplicate.
Q79: What is the difference between Hash Map and Hash Table?
HashMap | Hashtable |
5) We can make the HashMap synchronized by calling this code Map m = Collections.synchronizedMap(hashMap); | Hashtable is synchronized. It is thread-safe and can be shared with many threads. |
2) HashMap allows one null key and multiple null values. | Hashtable doesn’t allow any null key or value. |
3) HashMap is a new class introduced in JDK 1.2. | Hashtable is a legacy class. |
4) HashMap is fast. | Hashtable is slow. |
The enumerator in Hashtable is not fail-fast. | Hashtable is internally synchronized and can’t be unsynchronized. |
6) HashMap is traversed by Iterator. | Hashtable is traversed by Enumerator and Iterator. |
7) Iterator in HashMap is fail-fast. | Enumerator in Hashtable is not fail-fast. |
8) HashMap inherits AbstractMap class. | Hashtable inherits Dictionary class. |
Q80: What is the difference between a set and a Map?
Set:
- It is a value-based one.
- It prints in random order.
- It won’t allow duplicates.
Map:
- It is a key and value pair.
- Here key+value is one entry.
- Key ignore the duplicate value and value allow the duplicate.
Q81: Can we iterator the list using normal for loop?
Yes, we can iterator the list using both normal and by using enhanced for loop.
Q82: What are the methods available in the list but not in the set?
- indexOf();
- get();
- lastIndexOf();
Q83: Explain about user-defined Map.
- It is a key and value pair. Here key+value is one entry.
- Key ignore the duplicate value and value allow the duplicates
- Syntax: Map<String,String> map=new HashMap<String,String>();
Q84: How much null allows in the below maps:
HashMap :k?,v?
LinkedHashMap:k?,v?
TreeMap :k?,v?
HashTable :k?,v?
- HashMap :k-1 null,v- n null
- LinkedHashMap:k-1 null,v- n null
- TreeMap :k-ignore null,v- ignore null
- HashTable :k-ignore null,v- ignore null
Q85: How to Iterate Map?
- Iterating over entries using For-Each loop.
- Iterating over keys or values using the keySet() and values() method using for-each loop.
- Iterating using stream() in JAVA 8.
- Using entrySet()
- Using Iterator through a Maps.
Q86: What is the return type of entrySet?
Set<Entry<key,value>>
Q87: Write the methods to get the key only and value only?
- For key only the keySet() method is used.
- For value, only values() method is used.
Q88: What is meant by File? In which package it is available?
The File is a class and it is used to perform the file operation. It is available in java.io package.
Q89: What are the methods available in a File ?
- mkdir();
- mkdirs();
- list();
- createNewFile();
- isDirectory();
- isFile();
- isHidden();
Q90: While creating a file if we do not mention the format then under which format will it save the file?
If we do not mention the file format it will automatically take the format as a file.
Q91: What are the differences between the append and updating the file?
For updating the file: It will replace the old content of a file.
For appending the file: It will add the content at the end of a file.
Q92: What is meant by Enumerator, Iterator, and List Iterator?
Enumeration: It is a legacy interface and it is used before jdk version 1.4(old version).
Iterator: It is an Interface used to iterate the class ArrayList, LinkedList.
List Iterator: It is an interface used for iterating the list only and has backward direction special features(go back to the previous element).
Q93: Difference between Enumurator, Iterator, and List Iterator?
Property | Enumeration | Iterator | ListIterator |
1. Where we can apply? | It can be applied only to the legacy classes. | It can be applied to any collection interface. | It can be applied to the only list interface. |
2. Is it a legacy? | Yes (introduced in 1.0 V). | No (introduced in1.2 V). | No (introduced in 1.2 V). |
3. Allowed Movement | Single direction, i.e we can traverse elements present in the collection only in the forward direction. | Single direction, i.e we can traverse elements present in the collection only in the forward direction. | Bidirectional, i.e we can traverse elements present in the collection both in forward and backward directions. |
4.Allowed Operation | We can only perform the read operation. | We can perform read and remove operation. | We can perform read, remove, add, and replace operations. |
5. How can we get it? | By calling elements() method present in the vector class. | By calling iterator() method present in any collection interface. | By calling listIterator() method present in the list interface. |
Q94: What are the methods available in Enumerator, Iterator and List Iterator?
Enumerator Methods:
- hasMoreElements();
- nextElement();
Iterator Methods:
- hasNext();
- next();
- remove();
ListIterator Methods:
- hasNext();
- next();
- remove();
- hasPrevious();
- previous();
Q95: Explain JDBC connection steps.
- Import JDBC packages.
- Load and register the JDBC driver.
- Open a connection to the database.
- Create a statement object to perform a query.
- Execute the statement object and return a query resultset.
- Process the resultset.
- Close the resultset and statement objects.
- Close the connection.
Q96: What are control statements?
Statements which has control over the loop or program are called control statements. Example: if, if-else.
Q97: What are the differences between break and continue?
Break:
- It will terminate where the condition becomes true.
- It will not be used inside the loop other than the switch case.
Continue:
- It will skip the condition become true and keep executing the loop.
- It will not be used inside the loop
Q98: What is the difference between a while and a do-while loop?
While is an entry-controlled loop whereas do-while is an exit-controlled loop.
Q99: What is the difference between an if and an if-else loop?
if loop: execute only when the condition becomes true.
if-else: execute the else part when the condition becomes false and execute the if part when the condition becomes true.
Q100: What is the difference between an Immutable and mutable string?
Immutable string:
- We can store more duplicate values in the same memory
- We can’t change the value in memory
- In concordnation, we have to create a new memory
Mutable string:
- We can’t store duplicate values in the same memory
- We can change the value in memory
- In concordnation, it takes the same memory
Q101: What is the difference between Removeall() and Retainall()?
removeAll(): removeAll() is a method, it is used to compare both the list and remove all the list1 values in list 2
retainAll(): retainAll() is a method, it is used to compare both the list and print the common values.
Q102: What is the difference between a Literal String and a Non-literal string?
Literal String:
- It is stored inside the heap memory(string pool or string constant)
- It shares the memory if the same value (duplicate value)
Non-Literal String:
- It is stored in the heap memory
- It creates a new memory every time even if it’s a duplicate value(same value)
Q103: What is the difference between Heap and stack memory?
Heap memory:
- Heap for dynamic memory allocation.
- Memory access is slow.
Static memory:
- Stack is used for static memory allocation.
- Variables allocated on the stack are stored directly into the memory and access to this memory is very fast.
Q104: What is the default Package in Java?
java.lang
Q105: What is the difference between equals() & hashcode()?
Equals: Used to compare the two strings.
Hashcode: Used to return the address where it is stored.
Q106: Difference between a string buffer and a string builder?
String Buffer | String Builder |
It is synchronized i.e. only one thread can enter an object at any point of time. | It is asynchronized i.e., multiple threads can enter the object at any point of time. |
It is Thread safe. Multiple threads can’t enter the object simultaneously. OneThread has to wait until another thread has finished with them. | It is not Thread safe i.e. multiple threads can enter the object parallel. Threads don’t have to wait until one thread is finished. |
Because of the above reason String Bufferis slower | String builder is faster as a result of this. |
Q107: What is a String Constant pool?
String Constant Pool is the memory space in heap memory specially allocated to store the string objects created using string literals. In String Constant Pool, there will be no two string objects having the same content/value.
Whenever you create a string object using string literal, JVM first checks the content of the object to be created. If an object in the string constant pool has the same content, then it returns the same reference of that object. It doesn’t create a new object. If the content is different from the existing objects then only it creates a new object.
Q108: Difference between Collection and Collections?
Collection | Collections |
A collection is an interface in java.utilpackage | Collections is a utility class in java.utilpackage |
It is used to represent a group of individual objects as a single unit | It defines several utility methods that are used to operate on collection. |
It contains abstract and default methods. It has static methods from Java 8 onwards | It has only static methods |
Add(), remove(), clear(), contains() andsize() are the important methods in collection | Collections class sorts and synchronize the collection elements |
Q109: Why do we need to go for collection when there is already an Array concept?
In an array, we can store only similar types of objects. Array size is fixed and cannot provide readymade methods for user requirements such as searching, sorting, etc. Therefore we use collection where heterogenous or dissimilar objects can be stored. In a collection, the size can be changed dynamically as per the need and it also contains readymade methods.
Q110: Why do we need to go for collection when there is already an Array concept?
We can use collections.SynchronisedList(refName of array)method to synchronize arraylist in Java:
public class synchronizeArrayList{ public static void main(string[]args){
//Non-synchronized array list
List<String> language= new arrayList<String>(); language.add(“Java”);
language.add(“python”); language.add(“SQL”);
//synchronizing arraylist in Java
language=collections.synchronizedList(language);
//use synchronize block to avoid non-deterministic behaviour synchronized(language){
Iterator<String>itr= language.iterator(); While(itr.hasNext()){ System.out.println(itr.hasNext());
}
}
}
}
If you’re a beginner and want to dive deep into it, here’s how you can get started and learn How to Become a Java Developer in 2024?
Conclusion
Now that you know about some of the most frequently asked and top Java interview questions and answers, it’s time to get thorough with each of these questions. Start your preparation for getting a job in Java development.
You should now focus on preparation tips for clearing tech interviews. These questions will definitely help you answer some of the tricky tech questions asked by interviewers.
Kickstart your tech Java career now and get placed with a handsome salary package with GUVI’s Java Full Stack Development Career Program, providing placement assistance. Master essential technologies including Java, Maven, Eclipse, HTML, CSS, MongoDB, and more while working on practical real-world projects to enhance your expertise.
You can also accelerate your career with an awesome course on JAVA offered by GUVI, which has 11 hours of recorded sessions and is subdivided into modules for better understanding. You must go and register now for this course and explore Java.
FAQs
Q1. What are the core Java interview questions?
Ans. Some of the core Java interview questions are:
1: What is Java?
2: What are the features of Java?
3: How does Java enable high performance?
4: Name the Java IDEs.
5: What do you mean by constructor?
6: What is meant by the Local variable and the Instance variable?
7: What is a Class?
Q2. How to prepare for core Java interview questions?
Ans. To prepare for core Java interview questions and answers, you must read blogs related to Java, watch YouTube videos of interviews being conducted, and ask questions of mentors and already-placed working professionals.
Q3. What are the four core concepts of Java?
Ans. The four core concepts of Java are:
Abstraction, encapsulation, polymorphism, and inheritance are the four main theoretical principles of object-oriented programming.
Did you enjoy this article?