Java Interview Questions Core Java

Java Interview Questions Core Java: Java is one of the most popular programming languages today, with a wide range of applications in web development, mobile app development, and enterprise software development. As a result, many companies seek skilled Java developers to join their teams, and job seekers must be prepared to answer various technical questions during the interview process.

Java is a versatile language used for over two decades, and its popularity has only grown over time. One of the key reasons for this is Java’s platform independence, which means that code written in Java can be executed on any platform, from desktop computers to mobile devices to web servers. This makes Java a favorite among developers, who appreciate the ease of use and versatility that the language provides.

However, with the growing demand for skilled Java developers, job interviews have become increasingly competitive, and employers are looking for candidates who deeply understand the language and its related technologies. To succeed in a Java interview, candidates must have a solid grasp of the fundamentals and the ability to apply these concepts to real-world scenarios.

In addition to technical skills, successful candidates must also be able to communicate effectively and demonstrate a passion for programming. Employers are looking for candidates who are motivated to learn and improve and enthusiastic about working in a team environment.

To help candidates prepare for Java interviews, this article will explore some common Java interview questions and tips and strategies for answering them effectively. By reviewing these questions and practicing your responses, you can gain the confidence you need to excel in your next Java interview and land your dream job in this exciting and rewarding field.

Java Interview Questions

  • List Any Five Features Of Java.
  • Why Is Java Considered Dynamic?
  • Define Class.
  • Define JVM, JDK And JRE?
  • Define The Javaโ€™s Wora Nature.
  • What Is Abstraction?
  • What Is Encapsulation?
  • Can We Override A Static Method Or a Main Method?
  • What Is The Method Of Hiding?
  • What Is the Difference between Comparable And Comparator?
  • What Is Treeset?
  • What Is Dictionary In Java?
  • Why Is Java Known As The Platform Independent Programming Language?
  • Name The Data Types That Java supports.
  • Throw Some Light On The Main Features Of Java.
  • Define Autoboxing And Unboxing.
  • What Are Overloading And Overriding In Java?
  • What Is Constructor Chaining In Java?
  • Explain Java Heap Space And Garbage Collection.
  • What Is The Difference Between Final, Finalize, And Finally?
  • What Is Wrapper Class?
  • What Is An Immutable Class?
  • What Is Array?
  • What Is String? What is the difference Between StringBuilder And Strinngbuffer?
  • What Is Function?
  • What Is Class?
  • What Is Object?
  • What Is Polymorphism?
  • What Is Function Overloading?
  • What Is Function Overriding?
  • Why Use Super And This Keyword In Java?
  • What Is Inheritance?
  • Describe The Types Of Inheritance.
  • What Is Scope? Describe The Types Of Scope.
  • Types Of Access Specifiers?
  • What Is Encapsulation?
  • What Is Abstraction?
  • Is There Any Difference Between A = A + B And A += B Expressions?
  • What Does The Expression 1.0 / 0.0 Return? Will There Be Any Compilation Errors?
  • Can We Use Multiple Main Methods In Multiple Classes?
  • Does Java Allow You To Override A Private Or Static Method?
  • What Happens When You Put A Key Object In A Hashmap That Is Already Present?
  • How Can You Determine If Jvm Is 32-bit Or 64-bit From Java Program?
  • What Is The Right Data Type To Represent Money (Like Dollar/pound) In Java?
  • How Can You Do Multiple Inheritances In Java?
  • How Can You Access A Non-static Variable From The Static Context?
  • Let’s say there is a method in the superclass That Throws a Nullpointerexception. Can We Override It With A Method That Throws a Runtime Exception?
  • How Can You Mark An Array Volatile In Java?
  • What Is The Difference Between Sleep() And Wait() Methods In Java?
  • Can You Create An Immutable Object That Contains A Mutable Object?
  • How Can You Convert An Array Of Bytes To a String?
  • What Is the Difference Between Cyclic Barrier And Countdownlatch Class?
  • What Is The Difference Between StringBuffer And StringBuilder?
  • Which Class Contains Clone Method? Cloneable Or Object Class?
  • Can You Cast An Int Variable Into A Byte Variable? What Happens If The Value Of Int Is Larger Than Byte?
  • In Java, Can We Store A Double Value In A Long Variable Without Explicit Casting?
  • What Will This Return 5*0.1 == 0.5? True Or False?
  • Out Of An Int And Integer, Which One Takes More Memory?
  • Can We Use String In The Switch Case Statement In Java?
  • Can We Use Multiple Main Methods In the Same Class?
  • When Creating An Abstract Class, Is It A Good Idea To Call Abstract Methods Inside Its Constructor?
  • How Can You Do Constructor Chaining In Java?
  • How Can We Find The Memory Usage Of Jvm From Java Code?
  • What Is The Difference Between X == Y And X.equals(Y) Expressions In Java?
  • How Can You Guarantee That The Garbage Collection Takes Place?
  • What is the Relationship Between the X.hashcode() Method And the X.equals(Y) Method Of the Object Class?
  • What Is A Compile-Time Constant In Java?
  • Explain The Difference Between Fail-Fast and Fail-Safe Iterators.
  • You Have A Character Array And A String. Which One Is More Secure To Store Sensitive Data (Like Password, Date Of Birth, Etc.)?
  • Why Do You Use Volatile Keyword In Java?
  • What Is The Difference Between the Poll() And Remove() Methods Of Queue In Java?
  • Describe the newly added features in Java 8.
  • In which programming paradigm does Java 8 fall?
  • What are the significant advantages of Java 8?
  • What is MetaSpace? How does it differ from PermGen?
  • What are functional or SAM interfaces?
  • Can a functional interface extend/inherit another interface?
  • What is the default method, and why is it required?
  • What are static methods in Interfaces?
  • What are some standard Java pre-defined functional interfaces?
  • What are the various categories of pre-defined function interfaces?
  • What is the lambda expression in Java and How does a lambda expression relate to a functional interface?
  • What is the basic structure/syntax of a lambda expression?
  • What are the features of a lambda expression?
  • What is a type interface?
  • What are the types and common ways to use lambda expressions?
  • In Java 8, what is Method Reference?
  • What does the String::ValueOf expression mean?
  • What is an Optional class?
  • What are the advantages of using the Optional class?
  • What are Java 8 streams?
  • What are the main components of a Stream?
  • What are the sources of data objects a Stream can process?
  • What are Intermediate and Terminal operations?
  • What are the most commonly used Intermediate operations?
  • What is the stateful intermediate operation? Give some examples of stateful intermediate operations.
  • What is the most common type of Terminal operation?
  • What is the difference between findFirst() and findAny()?
  • How are Collections different from Stream?
  • What is the feature of the new Date and Time API in Java 8?
  • What are the important packages for the new Data and Time API?
  • Explain, for example, LocalDate, LocalTime, and LocalDateTime APIs.
  • Define Nashorn in Java 8
  • What is the use of JJS in Java 8
  • Why is Java a platform-independent language?
  • Why is Java not a pure object-oriented language?
  • Can Java be said to be the complete object-oriented programming language?
  • How is Java different from C++?
  • Pointers are used in C/ C++. Why does Java not make use of pointers?
  • What do you understand by an instance variable and a local variable?
  • What are the default values assigned to variables and instances in Java?
  • What do you mean by data encapsulation?
  • Can you tell the difference between the equals() method and the equality operator (==) in Java?
  • How is an infinite loop declared in Java?
  • Can the main method be Overloaded?
  • Do final, finally and finalize keywords have the same function?
  • Is it possible that the โ€˜finallyโ€™ block will not be executed? If yes, then list the case.
  • When can you use the super keyword?
  • Can the static methods be overloaded?
  • Why is the main method static in Java?
  • Can the static methods be overridden?
  • What is the main objective of garbage collection?
  • What is a ClassLoader?
  • What part of memory Stack or Heap is cleaned in the garbage collection process?
  • What are shallow copy and deep copy in Java?
  • Apart from the security aspect, what are the reasons behind making strings immutable in Java?
  • What is a singleton class in Java? And How to implement a singleton class?
  • Which of the below generates a compile-time error? State the reason.
  • How would you differentiate between a String, StringBuffer, and a StringBuilder?
  • Is this program giving a compile-time error? If yes, then state the reason and the number of errors it will give. If not, then state the reason.
  • What is a Comparator in Java?
  • What makes a HashSet different from a TreeSet?
  • Why is the character array preferred over string for storing confidential information?
  • What do we get in the JDK file?
  • What are the differences between JVM, JRE, and JDK in Java?
  • What are the differences between HashMap and HashTable in Java?
  • What is the importance of reflection in Java?
  • What are the different ways of thread usage?
  • What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?
  • What is the difference between the program and the process?
  • What is the difference between the โ€˜throwโ€™ and โ€˜throwsโ€™ keywords in Java?
  • What are the differences between the constructor and method of a class in Java?
  • Java works as a โ€œpass by valueโ€ or โ€œpass by referenceโ€ phenomenon.
  • What is the โ€˜IS-A โ€˜ relationship in OOPs Java?
  • Which among String or String Buffer should be preferred when there are a lot of updates required to be done in the data?
  • How to not allow serialization of attributes of a class in Java?
  • What happens if the static modifier is not included in the main method signature in Java?
  • Can we make the main() thread a daemon thread?
  • What happens if there are multiple main methods inside one class in Java?
  • What do you understand by Object Cloning and how do you achieve it in Java?
  • How does an exception propagate in the code?
  • How do exceptions affect the program if it doesn’t handle them?
  • Is it mandatory for a catch block to be followed after a try block?
  • Will the finallly block get executed when the return statement is written at the end of the try block and catch block as shown below?
  • Can you call a constructor of a class inside another constructor?
  • Why does the java array index start with 0?
  • Why is the remove method faster in the linked list than in an array?
  • How many overloaded add() and addAll() methods are available in the List interface? Describe the need and uses.
  • How does the size of ArrayList grow dynamically? And also state how it is implemented internally.
  • What is the difference between โ€˜>>โ€™ and โ€˜>>>โ€™ operators in java?
  • What are Composition and Aggregation? State the difference.
  • How is the creation of a String using new() different from that of a literal?
  • How is the โ€˜newโ€™ operator different from the โ€˜newInstance()โ€™ operator in java?
  • Is exceeding the memory limit possible in a program despite having a garbage collector?
  • Why is synchronization necessary? Explain with the help of a relevant example.
  • In the given code below, what is the significance of โ€ฆ ?
  • What will be the output of the below java program and define the steps of Execution of the java program with the help of the below code?
  • Can you explain the Java thread lifecycle?
  • What could be the tradeoff between the usage of an unordered array versus the usage of an ordered array?
  • Is it possible to import the same class or package twice in Java, and what happens to it during runtime?
  • In case a package has sub-packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?
  • Will the finally block be executed if the code System.exit(0) is written at the end of the try block?
  • What do you understand by marker interfaces in Java?
  • Explain the term โ€œDouble Brace Initialisationโ€ in Java?
  • Why is it said that the length() method of the String class doesn’t return accurate results?
  • What is the output of the below code and why?
  • What are the possible ways of making objects eligible for garbage collection (GC) in Java?
  • In the below Java Program, how many objects are eligible for garbage collection?
  • What is the best way to inject dependency? Also, state the reason.
  • How we can set the spring bean scope. And what supported scopes does it have?
  • What are the different categories of Java Design patterns?
  • What is a Memory Leak? Discuss some common causes of it.
  • Assume a thread has a lock on it, calling the sleep() method on that thread will release the lock

Java Interview Questions Basic

  • What Is The Difference Between Jdk, Jre, And Jvm?
  • What Is The Difference Between An Inner Class And A Sub-class?
  • What Is the Final Keyword In Java? Give An Example.
  • Whatโ€™s The Base Class In Java From Which All Classes Are Derived?
  • What Is A Platform?
  • What Is Classloader?
  • What Is The Static Method?
  • Can A Class Have Multiple Constructors?
  • What Is An Interface And Why Interface?
  • What Is An Abstract Class?
  • What Is The Difference Between Abstract Class And Interface And Concrete Class(Normal Class)
  • Why Abstract Class?
  • What Is Polymorphism?
  • What Are Overloading And Overriding?
  • Explain Static And Nonstatic Members.
  • What Is the Difference Between Final, Finalize, And Finally?
  • What Is The Difference Between Equals And == Operator
  • What Is The Case When You Override Hashcode() And Equals()? What Problem Can Occur If We Donโ€™t Override Hashcode() Method?
  • What Are Immutable Classes?
  • Mention The Access Specifiers Used In Java.
  • What Is Singleton In Java?
  • What Is Jdk?
  • Which Is The Latest Version Of Java?
  • What Is The Advantage Of Java?
  • Javac And Java Commands Are Available In Which Folder?
  • What Is The Signature Of The Main Method?
  • What Is A Keyword? List Some Keywords.
  • What Is An Identifier?
  • What Are Literals?
  • Java Is Platform Independent. Explain
  • What Is Jre?
  • What Is A Variable?
  • Mention All The Primitive Data Types In Java
  • What Are The Primitive Variables?
  • What Are Reference Variables?
  • What Is String In Java?
  • What Is The Method?
  • General Syntax For A Method?
  • What Is Method Overloading?
  • Why Method Overloading?
  • What Are The Members?
  • What Are Static Members?
  • What Are Nonstatic Members?
  • List Out The Differences Between Static And Non-static Members.
  • What Is An Object?
  • What Is A Class?
  • What Are Global Variables?
  • How Can You Access A Static Global Variable Of A Class?
  • How Can You Access Non-static Global Variables Of A Class
  • What Will Be The Default Value For Global Variables?
  • What Will Be The Default Value For Reference Variables?
  • What Is The Default Value For The Boolean Variable?
  • What Are The Differences Between Local And Global Variables?

Java Interview Questions Coding

  • Write a program to Reverse the Number
  • Write a program to count a duplicate character in a String
  • Write a program to count the number of words in a String
  • Write a program to reverse the word of the Character
  • Write a program INPUT-I work in exilant, and the output-I krow ni tnalixe;
  • Write a program to String. Is it palindrome or not?
  • Write a program to reverse a number with and without the third variable.
  • Write a program to remove the duplicate element in Array.
  • Write a program to remove duplicate Characters in String.
  • Write a program to Bubble Sort.
  • Write a program to Insertion Sort.
  • Write a program to selection sort.
  • Write a program to Count vowels in a String.
  • Write a program to determine whether it is binary or not.
  • Write a program to no is factorial.
  • Write a program to Find the largest no in the Array
  • Write a program reverse number.
  • Write a program to find the second no of ArrayList
  • Write a program to Sort Array?
  • Write a program to find the number of vowels present and their count from the given input String.

Java Interview Questions On Oops

  • What Is The Oops Concept Or Opps Principle?
  • Java Is Fully Oops Language Or Not?
  • What Is Oops
  • List Out The Oops Concepts
  • All Oops Concepts In A Single Program. Explain Oops
  • What Is The Oop Principle, Where You Used Polymorphism In Your Project?
  • What Is The Benefit Of Volatile Variable
  • Provide Byte Datatype Default Value In Java
  • Explain Applet
  • Define Use Cases In Java
  • Jvm Is A Dependent Or Independent Platform
  • Difference Between Hashmap And Hash Set, Set And Linkedlist, ArrayList And Vector List, Linkedhash Set, And HashSet
  • Abstract And Interface
  • Throw And Throws
  • How To Split
  • Checked And Unchecked Exception
  • How To Work With Ajax Application
  • Why String Is Immutable
  • What Is The Return Type Of Getwindowhandles();
  • What Are The Types Of Assertion, And What Is An Assertion In Java
  • Difference Between Interface And Abstract Classes
  • What Is A Static Variable
  • What Is Volatile
  • What Is Transient
  • What Is The Difference Between Final, Finalize, And Finally
  • What Is The Difference Between Public, Private, And Protected
  • What Is Static?
  • What Is An Interface?
  • What Is An Abstract Class?
  • What Is The Difference Between An Interface And An Abstract Class?
  • What is the difference Between Hashmap And Hashtable?
  • How Can You Declare Constant Variables In Java?
  • Can We Declare A Final Global Variable And Use It Without Initializing It?
  • What Is Sib (Static Initialization Block)?
  • When Do SIBs Get Execute?
  • How Many Times Will SIBs Be Executed In One Execution Cycle?
  • What Is An Iib?
  • When Will the Instance Initialization Block (IIB) be Executed?
  • How Many Times Will IIBs Be Executed In One Execution Cycle?
  • What Does A Methodโ€™s Return Type Signify?
  • What Is Call By Value And Call By Reference?
  • What Is A Constructor?
  • What Are The Two Types Of Constructors?
  • What Is A Default Constructor?
  • What Is This() Calling Statement?
  • What Is Recursion?
  • Recursion While Constructor Overloading Will Result In Compile-time Or Runtime Error
  • What Is โ€œthisโ€ Keyword?
  • What Is The Instance Variable Hiding?
  • What Is The Use Of This Keyword?
  • What Is Inheritance?
  • What Are The Different Types Of Inheritance?
  • What Is Extends Keyword?
  • Does Java Support Multiple Inheritances?
  • What Is The Diamond Problem?
  • Why Doesnโ€™t Java Support Multiple Inheritances?
  • What Is A Super() Calling Statement?
  • What Is A โ€œsuperโ€ Keyword?
  • What Is The Difference Between Super() Calling And This() Calling Statement?
  • What Is The Difference Between โ€œsuperโ€ And โ€œthisโ€ Keyword?
  • What Is Method Overriding?
  • Can We Override Static Methods?
  • What Is An Abstract Method?
  • What Is An Abstract Class?
  • Can We Instantiate An Abstract Class?
  • What Is The Rule To Be Followed By The Subclass Of An Abstract Class
  • Can An Abstract Class Inherit Another Abstract Class
  • Is Abstract Class 100% Abstract? Explain
  • What Is An Interface?
  • What Is The Difference Between An Abstract Class And An Interface?
  • Does The Abstract Class Have Constructors? If Yes, Why?
  • Do Interfaces Have Constructors?
  • Can We Instantiate An Interface?
  • What Is The Implements Keyword?
  • Can An Interface Inherit From Another Interface?
  • What Is Casting?
  • What Is Primitive Casting?
  • What Is Auto Widening And Explicit Narrowing?
  • What Is Derived Or Object Casting?
  • What Are Auto Upcasting And Explicit Downcasting?
  • Can We Achieve Object Casting Without Inheritance?
  • Can We Achieve Downcasting Without Upcasting?
  • What Is Polymorphism?
  • Explain Different Types Of Polymorphism.
  • What Is Abstraction?
  • What Are The Packages?
  • Why Packages?
  • What Are The New Features Released In Java 8?
  • What Are The Main Benefits Of New Features Introduced In Java 8?
  • What Is A Lambda Expression In Java 8?
  • What Are The Three Main Parts Of A Lambda Expression In Java?
  • What Is The Data Type Of A Lambda Expression?
  • What Is The Meaning Of Following Lambda Expression?
  • Why Did Oracle Release A New Version Of Java Like Java 8?
  • What Are The Advantages Of A Lambda Expression?
  • What Is A Functional Interface In Java 8?
  • What Is A Single Abstract Method (Sam) Interface In Java 8?
  • How Can We Define A Functional Interface In Java 8?
  • Why Do We Need Functional Interface In Java?
  • Is It Mandatory To Use @functionalinterface Annotation To Define A Functional Interface In Java 8?
  • What Are The Differences Between Collection And Stream Api In Java 8?
  • What Are The Main Uses Of Stream Api In Java 8?
  • What Are The Differences Between Intermediate And Terminal Operations In Java 8 Streams?
  • What Is A Spliterator In Java 8?
  • What Are The Differences Between Iterator And Spliterator In Java 8?
  • What Is Type Inference In Java 8?
  • Does Java 7 Support Type Inference?
  • How Does Internal Iteration Work In Java 8?
  • What Are The Main Differences Between Internal And External Iterators?
  • What Are The Main Advantages Of Internal Iterator Over External Iterator In Java 8?
  • What Are The Applications In Which We Should Use Internal Iteration?
  • What Is The Main Disadvantage Of Internal Iteration Over External Iteration?
  • Can We Provide the Implementation Of A Method In A Java Interface?
  • What Is A Default Method In An Interface?
  • Why Do We Need Default Method In A Java 8 Interface?
  • What Is The Purpose Of A Static Method In An Interface In Java 8?
  • What Are The Core Ideas Behind The Date/time Api Of Java 8?
  • What Are The Advantages Of New Date And Time Api In Java 8 Over Old Date Api?
  • What Are The Main Differences Between the Legacy Date/time API in Java and the Date/time API of Java 8?
  • How Can We Get Duration Between Two Dates Or Time In Java 8?
  • What Is The New Method Family Introduced In Java 8 For Processing Of Arrays On Multi-Core Machines?
  • How Does Java 8 Solve the Diamond Problem Of Multiple Inheritance?
  • What Are The Differences Between Predicate, Supplier, And Consumer In Java 8?
  • Is It Possible To Have a Default Method Definition In An Interface Without Marking It With a Default Keyword?
  • Can We Create A Class That Implements Two Interfaces With Default Methods Of the Same Name And Signature?
  • How Java 8 Supports Multiple Inheritance?
  • If We Create A Class That Extends A Base Class And Implements An Interface, and both the Base Class And Interface Have A Default Method With the same name and arguments, Which Definition Will Be Picked By Jvm?
  • If We Create the same method and define it in a class, In Its Parent Class, And An Interface Implemented By The Class, then the Definition Will Be Invoked If We Access It Using The Reference Of the Interface And The Object Of the Class.
  • Can We Access A Static Method Of An Interface By Using Reference Of The Interface?
  • How Can You Get The Name Of a Parameter In Java By Using Reflection?
  • What Is Optional In Java 8?
  • What Are The Uses Of Optional?
  • Which Method In Optional Provides The Fallback Mechanism In Case Of Null Value?
  • How Can We Get Current Time By Using Date/time Api Of Java 8?
  • Is It Possible To Define A Static Method In An Interface?
  • How Can We Analyze The Dependencies In Java Classes And Packages?
  • What Are The New JVM Arguments Introduced By Java 8?
  • What Are The Popular Annotations Introduced In Java 8?
  • What Is A String Joiner in Java 8?
  • What Is The Type Of A Lambda Expression In Java 8?
  • What Is The Target Type Of A Lambda Expression?
  • What Are The Main Differences Between An Interface With a Default Method And An Abstract Class In Java 8?

Java Interview Questions On Strings

  • What Is The Difference Between StringBuffer & StringBuilder?
  • What Is Difference B/w String S=new String(),string S=โ€โ€;
  • Is String A Data Type In Java?
  • Why Is StringBuffer Called Mutable?
  • What Are The Different Access Levels In Java? Explain
  • What Is Singleton Class?
  • What Is Encapsulation?
  • Which Is The Uppermost Class For All The Classes In Java?
  • Explain โ€œtoString()โ€ Of Object Class
  • Explain โ€œhashcode()โ€ Of Object Class
  • Explain โ€œequals()โ€ Of Object Class
  • Can A Subclass Override All These Above Methods?
  • What Is The Final Method In Java?
  • What Is The Final Class In Java?
  • What Is The Use Of Finalize() Method In Java?
  • What Is The Use Of The Clone() Method?
  • What Is A Marker Interface? Explain And Mention At Least Two Available Marker Interface
  • Strings Are Immutable In Java. Justify
  • Can We Have Inherited The String Class? Justify
  • Explain The Behavior Of Tostring(),hashcode() And Equals() Method Of String Class
  • What Is A String Constant Pool And Non-constant Pool?
  • What Are Arrays?
  • What Is A Primitive Array?
  • What Is A Derived Array?
  • What Are Boxing And Unboxing?
  • What Are The Wrapper Classes?
  • What Is A Collection Api/framework?
  • Explain the List Type Of Collection.
  • Explain the Set Type Of Collection.
  • Explain The Queue Type Of Collection.
  • List Out The Differences Between List, Set, And Queue Types Of Collections.
  • What Are The Exceptions?
  • How To Handle An Exception?
  • What Has Checked Exceptions?
  • What Are Unchecked Exceptions?
  • Different Ways Of Handling Checked Exceptions?
  • What Is The Difference Between Final, Finalize(), And Finally In Java
  • How To Write The Data Into A Text File?
  • How To Read Data From A Text File?
  • What Is The Use Of The Scanner Class In Java?
  • How To Read The String From The Console?

Java Interview Questions Collections

  • What Is Collection?
  • What Is List?
  • What Is The Difference Between ArrayList And LinkedList?
  • What Is The Difference Between List, Set, Map
  • What Is the Difference Between Vector And Arraylist?
  • What Is The Difference Between Hashmap And Hashtable
  • What Is The Difference Between Collection And Array?
  • What Is the Difference between HashSet And Linkedhashset
  • What Is Iterator In Java?
  • What Is the Difference between Listiterator And Iterator
  • What Is The Default Capacity Of Arraylist And Hashtable?
  • What Is The Difference Between Constructor And Method
  • What Is The Difference Between This And Super In Java?
  • How To Sort Employee Class Using Comparator?
  • What Is Super Most Class In Java, And Explain All Methods Of The Superclass?
  • How Do You Differentiate A HashSet Class And A Treeset Class?
  • What Is A List? What Is The Difference Between An ArrayList And A LinkedList?
  • What Is a Collection And A Collections Framework?
  • What Is The Difference Between ArrayList And Vector?
  • Whatโ€™s The Difference Between Stack And Queue?
  • What Is An Array
  • What is the difference Between an Array And an Arraylist?
  • How To Sort The Collections?
  • What Is Treeset?
  • In Which Scenarios ArrayList And Linkedlist Will Be Used?
  • What Happens If You Add the Same Key In The Hashmap?
  • Can We Add a Null Key To The Hashmap?
  • Hashmap Put() Operations Uses Which Datastrcture When The Hashcode Is Same?

Java Interview Questions On Exception Handling

  • How to handle Exception in Java?
  • What are try, catch, and finally?
  • What is throw and throws?
  • Will all the Try blocks in Java end with Catch Blocks?
  • What is the Final Keyword in Java?
  • Which types of exceptions are caught at compile time?
  • What is an Exception?
  • When is the throw keyword used?
  • Which types of exceptions are caught at compile time?
  • What is an Exception? Types of Exception?
  • Explain Exception Handling methods.
  • What are the types of exceptions in Java?
  • Mention the different methods to handle exceptions
  • Provide the benefits of exception handling
  • Provide the exception handling keywords available in Java
  • What is Locale in Java?
  • How will you use a specific Locale in Java?
  • What is serialization?
  • What is the purpose of serialization?
  • What is Deserialization?
  • What are Serialization and Deserialization conceptually?
  • Why do we mark a data member transient?
  • Is it allowed to mark a method as transient?
  • How does marking a field as transient make it possible to serialize an object?
  • What is an Externalizable interface in Java?
  • What is the difference between a Serializable and an Externalizable interface?
  • What is Reflection in Java?
  • What are the uses of Reflection in Java?
  • How can we access the private method of a class from outside the class?
  • How can we create an Object dynamically at Runtime in Java?
  • What is Garbage Collection in Java?
  • Why does Java provide a Garbage Collector?
  • What is the purpose of gc() in Java?
  • How does Garbage Collection work in Java?
  • When does an object become eligible for Garbage Collection in Java?
  • Why do we use the finalize() method in Java?
  • What are the different types of References in Java?
  • How can we reference an unreferenced object again?
  • What is the purpose of the Runtime class?
  • How can we invoke an external process in Java?
  • What are the uses of the Runtime class?
  • What is a Nested class?
  • How many types of Nested classes are in Java?
  • Why do we use Nested Classes?
  • What is the difference between Nested and Inner classes in Java?
  • What is a Nested interface?
  • How can we access the non-final local variable inside a Local Inner class?
  • Can an Interface be defined in a Class?
  • Do we have to mark a Nested Interface as public static explicitly?
  • Why do we use the Static Nested interface in Java?
  • What are Wrapper classes in Java?
  • What is the purpose of the native method in Java?
  • What is a System class?
  • What is System, out, and println in System.out.println method calls?
  • What is the other name of Shallow Copy in Java?
  • What is the difference between Shallow Copy and Deep Copy in Java?
  • What is a Singleton class?
  • What is the difference between the Singleton class and the Static class?

Java Interview Questions On Multithreading

  • Explain multi-threading and the ways of implementing multi-threading in Java.
  • What do you mean by BlockingQueue in Java Collections Framework?
  • Name the different states of a thread.
  • What are the two ways of implementing multi-threading in Java?
  • What will you call the wait() method? Would you use if block or loop, and why?
  • How do you take thread dump in Java?
  • What is the difference between sleep and wait in Java?
  • Is ++ operator thread-safe in Java?
  • What is the difference between poll() and remove() methods?
  • What is Multitasking? How to achieve multitasking?
  • What is Thread?
  • What is Multithreading?
  • What is the difference between Multithreading and Multiprocessing?
  • Which thread will execute first?
  • How to get the current thread?
  • What is thread
  • What is synchronisation
  • Which methods are there in the thread class?
  • Can we have two start() methods in thread execution?
  • Which will manage the lifecycle of the thread?
  • What is the default priority of the thread?
  • Describe Thread in Java
  • Describe wait() method
  • Explain notify () and notify all () methods
  • Provide the list of thread methods to stop a thread in Java
  • Describe the thread life cycle of Java
  • Define Serialization
  • What is a thread?
  • Pre-increment/decrement and post-increment/decrement
  • What is threading?
  • How does multithreading achieve?
  • How to initiate a thread in Java?
  • What do you mean by thread-safe?
  • What are Threads?
  • What is the use of the sleep() method in Threads?
  • Explain the wait(), notify(), and notifyAll() methods of the Object class.
  • Can we Override wait(), notify(), and notifyAll() methods of the Object class in the sub-classes?
  • What kind of process is the Garbage collector thread?
  • How can you ensure that N threads can access N resources without deadlock?
  • How can we share an object between multiple threads?
  • What is the difference between a process and a thread in Java?
  • Can you catch an exception thrown by another thread in Java?
  • How can you determine if your program has a deadlock?
  • Is ++ operation thread-safe in Java?
  • What is a thread-local variable in Java?
  • How will you take thread dump in Java?
  • How to achieve lock?

Java Interview Questions On Inheritance

  • Does Java support multiple inheritances?
  • Can we develop final methods in an interface?
  • Can we develop a final abstract class?
  • Can we develop a static method in an abstract class?
  • Can we declare a variable in the interface without initializing it?
  • What is the difference between JDK and JRE?
  • What is Java Virtual Machine (JVM)?
  • What are the different types of memory areas allocated by JVM?
  • What is a JIT compiler?
  • How is the Java platform different from other platforms?
  • Why did people say Java is a ‘write once and run anywhereโ€™ language?
  • How does ClassLoader work in Java?
  • Do you think โ€˜mainโ€™ used for the main method is a keyword in Java?
  • Can we write the main method as public void static instead of the public static void?
  • In Java, if we do not specify a value for local variables, what will be their default value?
  • Let’s say we run a Java class without passing any arguments. What will be the value of the String array of arguments in the Main method?
  • What is the difference between byte and char data types in Java?
  • In Java, why do we use a static variable?
  • Why is it not a good practice to create static variables in Java?
  • What is the purpose of the static method in Java?
  • Why do we mark the main method as static in Java?
  • In what scenario do we use a static block?
  • Is it possible to execute a program without defining a main() method?
  • What happens when the static modifier is not mentioned in the signature of the main method?
  • What is the difference between static and instance methods in Java?
  • How can you change the value of a final variable in Java?
  • Can a class be marked final in Java?
  • How can we create a final method in Java?
  • How can we prohibit inheritance in Java?
  • Why is the Integer class in the final in Java?
  • What is a blank final variable in Java?
  • How can we initialize a blank final variable?
  • Is it allowed to declare the main method as final?
  • What is the purpose of the package in Java?
  • What is java.lang package?
  • Which is the most important class in Java?
  • Is it mandatory to import java.lang package every time?
  • Can you import the same package or class twice in your class?
  • What is a static import in Java?
  • What is the difference between import static com.test.Fooclass and import com.test.Fooclass?

Java Interview Questions Advanced

  • Whatโ€™s the exception?
  • Are the exceptions defined in JavaScript packages? Or are there any definitions for all classes?
  • What are the types of exceptions?
  • What is the difference between an error and an exception?
  • What is the keyword in exceptional handling?
  • What is the keyword?
  • Throwing in Java
  • Can the standard block be lifted?
  • What is banned?
  • NoClassDefFoundError versus ClassNotFoundException?
  • Can we try or not try to stop it?
  • Can you handle a catch in an exception to an exception?
  • What is Java Bean?
  • Define JAVA
  • Why do we say Java is dynamic?
  • List out the different access specifiers available for Java classes
  • Define Loops in Java. Provide the different types of loops in Java
  • List out the constructors in Java
  • What is the difference between a List and a Set?
  • Can we create an object for the abstract class? If not, why?
  • Whether we can declare a class as static?
  • Polymorphism w.r.t variables and methods? Or overriding and overloading?
  • In what way we can sort the elements(default and custom sort) present in the array and any of the collection objects?
  • How to generate random numbers in Java? And also generate random numbers of format โ€˜A23BCโ€™?
  • Is it possible to call protected data members of one package in another? Similarly, all other access modifiers and their data members scope from other packages.

Java Interview Questions For Freshers

  • Explain Method Overriding
  • Define Interface in Java
  • List out the advantages of Java packages
  • Do you know whether the constructor returns any value in Java?
  • Is it possible to make a constructor final?
  • Is it possible to overload the constructors?
  • Explain static block
  • Explain the keyword โ€œthisโ€ in Java.
  • Mention the class, which is the superclass for the entire class.
  • Define Aggregation
  • Explain the keyword โ€œSuperโ€ in Java
  • List out the vital advantages of the keyword โ€œSuper.โ€
  • Is it possible to use both โ€œthis()โ€ and โ€œsuper()โ€ in a constructor?
  • Will you be able to overload the main() method?
  • Explain final variable
  • Is it possible for you to declare a constructor as final?
  • Mention the difference between the abstract and the final method
  • Explain the purpose of encapsulation
  • Explain Polymorphism
  • Define Java Collections
  • What are the operations of collections?
  • List out the interfaces available in Java collections
  • List out the Classes available in Java collections
  • List out the maps available in Java collections
  • Can you give an example of pointers?
  • Provide the features of the Hashtable method
  • Explain HashSet
  • Explain TreeSet
  • How do you decide which type of Inner Class โ€“ Static or Non-Static to use in Java?
  • What are the different types of Classloaders in Java?
  • What are the situations in which you choose HashSet or TreeSet?
  • What is the use of method references in Java?
  • Do you think Java Enums are more powerful than integer constants?
  • Why do we use static initializers in Java?
  • Your client is complaining that your code is throwing NoClassDefFoundError or NoSuchMethodError, even though you can compile your code without error and the method exists in your code. What could be the reason behind this?
  • Using a regular expression, how can you check if a String is a number?
  • What is the difference between the expressions String s = โ€œTemporaryโ€ and String s = new String(โ€œTemporary โ€œ)? Which one is better and more efficient?
  • In Java, can two equal objects have different hash codes?
  • How can we print an Array in Java?
  • Is it ok to use random numbers to implement the hashcode() method in Java?
  • Which is better between the two types of dependency injections, constructor and setter dependency injections?
  • What is the difference between DOM and SAX parser in Java?
  • Between Enumeration and Iterator, which one has better performance in Java?
  • What is the difference between pass-by-reference and pass-by-value?
  • What are the different ways to sort a collection in Java?
  • Why doesnโ€™t the Collection interface extend Cloneable and Serializable interfaces?

Java Interview Questions For Experienced

  • Is it possible to declare a class as Abstract without using any abstract method?
  • Any five differences between an Abstract Class and an Interface in Java?
  • Define Serialization. When should we make use of serialization?
  • Is it true that a Java program never goes out of memory because of the garbage collection feature?
  • How can you define Object Cloning in Java?
  • Can the throw and throws keywords be used interchangeably? If not, what is the difference between the two?
  • Are you connecting to a database in Java?
  • Functions of JVM and JRE?
  • What is the default size of the loaded factor in hacking based on the collection?
  • What is a collection?
  • What Exception Classes are the Basic Classes?
  • Two differences in the state between a class and one square
  • How are they destroyed in Java?
  • Define JSON.
  • Name the most important aspect of Java
  • What is an anonymous class?
  • What is a JVM?
  • Can a Dead End Start Again?
  • Sort of ancient data types?
  • What researchers are in Java?
  • Explain garbage in Java.
  • Whatโ€™s the difference between the stack and the queue?
  • What is a standard method?
  • Explain the keyword of Java.
  • The use of Javaโ€™s last words?
  • What is the subject class?
  • What are the packages in Java?
  • Whatโ€™s the difference between importing java.util.Date and java.util? *?
  • What is the standard import?
  • Garbage collection in Java?
  • Decision-Making in Java
  • How often do you call the trash cushion for the last time () method for an object?
  • How can garbage collection be enforced?
  • What is a class?
  • What is the difference between heap and stack?
  • What is the difference between an instance variable and a local variable?
  • What is a Constructor? Types of Constructors?
  • What is the difference between Break and Continue?
  • To exit the system from the current execution, what command is used in Java?
  • Addition features in Java 8?
  • What is the difference between for and for each loop in Java and its use of it?
  • Can we have multiple public classes within a class?
  • What is inheritance? Types of inheritance? Are multiple inheritances allowed in Java? If not, why?
  • What is polymorphism? How can we achieve it?
  • What is the difference between method overloading and method overriding?
  • Can we achieve method overloading when two methods have only differences in return type?
  • Method overloading and overriding examples in the Selenium project?
  • What is encapsulation?
  • What are IS-A and HAS-A relations in Java with examples?
  • What is the final and super keyword? What difference between them?
  • Explain runtime polymorphism and compile-time with examples.
  • Can the final/Static method be overloaded?
  • Can final/Static methods be overridden?
  • Can we overload the main method?
  • Can we execute a class without a main method?
  • What is a Package?
  • What is an Abstract Class? Write an example code.
  • What is an Interface? What is the difference from the Abstract class?
  • Can we use private and protected access modified inside an Interface?
  • Can multiple inheritances support the Interface?
  • Examples of Abstract and Interface used in the selenium project?
  • What is an Exception, and what is its base class of it?
  • What is Final, Finally, Finalize?
  • What is done in finally block?
  • What is garbage collection in Java? How is it done?
  • What is the difference between Throws and throws?
  • What is Java Reflection, Singleton?

Java Tricky Interview Questions

  • Define Constructor and Constructor Overloading in Java.
  • What are the differences between Enumeration and Iterator?
  • Why is a break used in the Switch Statement in each case?
  • How can we execute any code even before the main method?
  • Whatโ€™s the benefit of using inheritance as a key?
  • Define Expressions.
  • What will be the result of relational operators?
  • Which operators are used to mask the data in the encryption and decryption process?
  • Which is maintained to manage the life cycle of local variables?
  • In how many ways can the object be created?
  • The object which has no reference is called?
  • In Heap memory which variables are created?
  • In Java, how are arrays created?
  • Which operator is not used in Java?
  • Define Runtime Polymorphism.
  • When does a null pointer exception occur?
  • When Does an out-of-memory error occur?
  • Can exceptions occur in the catch block?
  • What will happen if we use the throws keyword in the body?
  • Which exceptions are used to represent the business/environmental failure?
  • In Java, Why multiple inheritances are not supported?
  • Which feature allows the JVM to run more than one thread in Java?
  • What is Java?
  • What is Interface?
  • What is the difference between Interface and Abstraction?
  • What is Serialization?
  • What is DeSerialization?
  • When does an Out of a stack error occur?
  • Where are all string literals managed?
  • Which condition will result in an Illegal state exception?
  • What is the default priority of gc()?
  • Which interface will result in sorted order?
  • What is Comparator?
  • What is a workspace?
  • Which will interact with the hard disk?
  • What are Access specifiers?
  • Why can we not apply access specifiers to packages, initializers, and local variables?
  • When can we use the final class?
  • An abstract class cannot be instantiated. Why?
  • An abstract method cannot have a body; why?
  • Define class in Java.
  • What is the difference between fixed and dynamic loads?
  • What is Multiple Mitigation?
  • When was Java created?
  • What stand is for JDK, JRR and JVM?
  • Need Java Use Pointers?
  • What is a singleton class?
  • Explain List
  • Explain Set
  • Explain Map
  • Why are strings immutable?
  • What is an exception? And its types?
  • What is a checked and unchecked exception?
  • What is a comparable and comparator?
  • Can we break a singleton object with the clone method? How to avoid that?
  • Can we break singleton objects with serialization? How to avoid that?
  • Can we break a singleton object with a reflection API on how to avoid that?
  • Can we break a singleton object with multiple classloaders? On how to avoid that?
  • What is the best way to create a singleton object in Java?
  • What is double-checking lock-in Singleton in Java?
  • Difference between static and Singleton objects in Java
  • Whenever going to an interview, please learn Singleton’s object above cases.

Java Interview Questions For Selenium

  • Why Collection, and where did you use the Collection of Selenium?
  • What are keywords, data type, constant and variable
  • What are the fundamental data types in c
  • What is the conditional statement?
  • What is the unconditional statement?
  • What is if-else statement
  • What are switch case statements?
  • What is a conditional operator?
  • What is the iterative statement?
  • What is sorting
  • What is searching
  • What is function
  • Explain the type of user-defined function
  • What is a recursive function?
  • What is structure
  • What is the difference between structure and union?
  • What is a pre-processor directive?
  • What is micro in c
  • What is file
  • What is a file pointer
  • What is a data structure?
  • What is stack
  • What is queue
  • What is a link list
  • What is a binary tree?
  • What is spanning tree
  • What is polymorphism
  • What is abstraction
  • What is inheritance
  • What is a static keyword
  • What is a pure virtual function?
  • What is Java
  • What final in Java
  • What is a super keyword in Java?
  • What is the difference between abstract and interface?
  • What is an applet program?
  • What is swing
  • What are the benefits of using an unordered array over an ordered array?
  • Between HashSet and TreeSet collections in Java, which one is better?
  • When does JVM call the finalize() method?
  • When would you use the Serial garbage collector or Throughput Garbage collector in Java?
  • In Java, if you set an object reference to null, will the Garbage Collector immediately free the memory held by that object?
  • How can you make an Object eligible for Garbage collection in Java?
  • When do you use Exceptions or Errors in Java? What is the difference between these two?
  • What is the advantage of PreparedStatement over Statement class in Java?
  • In Java, what is the difference between throw and throws keywords?
  • What happens to the Exception object after the exception handling is done?
  • How do you find which client machine is sending requests to your servlet in Java?
  • What is the difference between a Cookie and a Session object in Java?
  • Which protocol do Browser and Servlet use to communicate with each other?
  • What is HTTP Tunneling?
  • Why do we use JSP instead of Servlet in Java?
  • Is an empty โ€˜.javaโ€™ file name a valid source file name in Java?
  • How do you implement Servlet Chaining in Java?
  • Can you instantiate this class?
  • Why does Java not support operator overloading?
  • Why String class is Immutable or Final in Java?
  • What is the difference between the sendRedirect and forward methods?
  • How do you fix your Serializable class if it contains an un-serializable member?
  • What is the use of run time polymorphism in Java?
  • What are the rules of method overloading and method overriding in Java?
  • What is the difference between a class and an object in Java?
  • Can we create an abstract class that extends another abstract class?
  • Why do you use Upcasting or Downcasting in Java?
  • What is the reason for organizing classes and interfaces in a package in Java?
  • What is information hiding in Java?
  • Why does Java provide a default constructor?
  • What is the difference between super and this keyword in Java?
  • What is the advantage of using Unicode characters in Java?
  • Can you override an overloaded method in Java?
  • How can we change the heap size of a JVM?
  • Why should you define a default constructor in Java?
  • How will you make an Object Immutable in Java?
  • How can you prevent SQL Injection in Java Code?
  • Which two methods should always be implemented by the HashMap key Object?
  • Why should an Object used as a Key in HashMap be Immutable?

Java Interview Questions For Testers

  • What kind of variables can a class consist of?
  • What is Singleton’s class?
  • List the three steps for creating an Object for a class.
  • When is a byte datatype used?
  • What do you mean by Access Modifier?
  • When can the parseInt() method be used?
  • When is a super keyword used?
  • Why is Runnable Interface used in Java?
  • Whatโ€™s the purpose of using Break in each case of Switch Statement?
  • How can we execute any code even before the main method?
  • Can we have two methods in a class with the same name?
  • How can we make a copy of a Java object?
  • Can we use a class’s default constructor even if an explicit constructor is defined?
  • Can we override a method by using the same method name and arguments but different return types?
  • What is an applet?
  • What is a Comparable Interface?
  • Why IS the Java application platform independent?
  • What are the actions present in the JVM?
  • What is the current version of JDK?
  • Which data structure set is used?
  • Is wrapper classes override hashcode and equals method?
  • Does Java 8 support functional programming?
  • What is the default method in the Java 8 interface?
  • What is the difference between StringBuffer and StringBuilder?
  • What exceptional handling
  • What is JDBC
  • What is the JDBC driver
  • What are the steps involved in database connectivity
  • What is servlet
  • What is the life cycle of a servlet
  • Write a servlet program
  • What is Jsp
  • What is the difference between while and do-while
  • From which method the execution of Java programs begins?
  • Which name will be checked by the compiler for the execution of the program?
  • Which name will be checked by the JVM after compiling the program?
  • Can we have the filename and class name as same?
  • Why are we injecting interface references in the spring framework? Why not direct implementation?
  • Tell me about Hash Map implementation
  • Difference between Linked List and Array List
  • How to make a map a synchronized map
  • What is the difference between Collections.synchronizedMap(m) and concurrent hash map
  • Difference between forEach and iterator
  • Can we instantiate the interface? If not, then why?
  • What is the difference between classNotFoundException and NoClassDefError, and in which situation will we face this?
  • What is serializable? If my business object does not implement serializable, is there any problem?

Conclusion:

Preparing for these questions lets you demonstrate your proficiency and problem-solving skills to potential employers. By familiarizing yourself with an extensive array of topics, ranging from fundamentals to advanced Java concepts, you can confidently navigate the interview process. It is important to remember that practice and hands-on experience are the keys to success. So keep refining your Java programming skills and stay updated with the language’s latest developments to ace your Java interview.

We greatly appreciate and encourage feedback on the comments on Java interview questions, as it fosters a collaborative learning environment. By sharing your thoughts, experiences, and knowledge, you contribute to the ongoing improvement and expansion of the content available on this platform. Your feedback not only supports fellow developers in their quest to master Java development but also helps us refine and optimize the resources we provide. So, don’t hesitate to leave a comment or suggestionโ€”your input is valuable in creating a comprehensive and engaging learning experience for all.

Core Java Interview Questions: Java is one of the most popular programming languages developers and testers use worldwide. Core Java interview questions are crucial in evaluating the skills and proficiency of candidates in Java programming.

Whether you are a fresher or an experienced developer, it is essential to have a thorough understanding of Core Java, including its concepts, syntax, and applications. Core Java Interview Questions for Freshers & Experienced are designed to assess a candidate’s knowledge of Core Java concepts, such as OOPs, methods, classes, languages, control statements, inheritance, and exception handling, among others.

In this context, this article provides an extensive list of common Core Java Interview Questions for Freshers and Experienced candidates, which can help them prepare for job interviews and improve their overall knowledge of Java programming.

Core Java Interview Questions For Freshers

How many methods are there in the object class?
Ans: 11 methods, below is the list

  • protected Object clone() throws CloneNotSupportedException – Creates and returns a copy of this object.
  • Public boolean equals(Object obj) – Indicates whether some other object is “equal to” this one.
  • Protected void finalize() throws Throwable – Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
  • public final Class getClass() – Returns the runtime class of an object.
  • public int hashCode() – Returns a hash code value for the object.
  • Public final void notify() – Wakes up a single thread that is waiting on this object’s monitor.
  • Public final void notifyAll() – Wakes up all threads that are waiting on this object’s monitor.
  • Public String toString() – Returns a string representation of the object.
  • Public final void wait() – This causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
  • public final void wait(long timeout)
  • public final void wait(long timeout, int Nanos)

Hashcode method return type?
Ans: integer

what is the finalize method, and when it uses?
Ans: Garbage collection is executed before the garbage collector runs.

What is equals methods?
Ans: it is used in 2 places, one is a string class, and another is an object class. In the string class, it is overridden. In object class, it checks the addresses, and in string class, it checks the contents.

What is the difference between equal and hashcode?
Ans: hashcode can be the same; it is used internally to find out the uniqueness of an object.
Kiran — 89
Naikr — 89
suppose k=23,i=4
Then both Kiran and Naikr have the same hashcode, but both are not the same. But if equals return the same, then there must be the same hashcode.

is it compulsory to write body in a method?
Ans: no, ex-abstract class, interface

why do we need to learn encapsulation?
Ans: binding data variables and methods in a single unit is called encapsulation. We are using encapsulation to protect our class from others so that others can not extract our class. Her variables should be private, and the method is sometimes public so that our requirement is solved properly.

What is the difference between encapsulation and abstraction?
Ans: in abstraction, we expose only the required things. But in encapsulation, we are binding the data properly.

What is polymorphism?
Ans: behaving differently at different times by the same entity. It can be achieved in 2 ways: overloading and overriding. In overloading, this happens, and in overriding, this happens.

Why are you using overriding?
Ans: To change the implementation of the parent class.

Why do we use an interface?
Ans: if we want 100% abstraction, then we should go with an interface. To maintain standards.

Core Java Interview Questions Experienced

Do you need to implement all methods of interface?
Ans: If you don’t want to implement all methods, you have to make that class abstract.

What is the use of an abstract class?
Ans: if you want to implement or expose some methods and don’t want to implement some methods, then go for the abstract class

List l=new ArrayList(); and ArrayList al=new ArrayList(); which is good and why?
Ans: List l=new ArrayList() is good.

what is the difference between final and static?
Ans: In final, the value can not be changed, but in static, you can change it.

What is the difference between JDK,JRE, and JVM?
Ans:
JVM: JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which Java bytecode can be executed. It is a specification. JVMs are available for many hardware and software platforms (so JVM is platform-dependent).
JRE: JRE stands for Java Runtime Environment. It is the implementation of JVM.
JDK: JDK is an acronym for Java Development Kit. It physically exists and contains JRE and development tools.

How many types of memory areas are allocated by JVM?
Ans: Many types:

  • Class(Method) Area
  • Heap
  • Stack
  • Program Counter Register
  • Native Method Stack

What is a JIT compiler?
Ans: Just-In-Time(JIT) compiler: It is used to improve performance. JIT compiles parts of the bytecode that have similar functionality at the same time and hence reduces the amount of time needed for compilation. Here the term โ€œcompilerโ€ refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

What is a platform?
Ans: A platform is the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides a software-based platform.

What is the main difference between the Java platform and other platforms?
Ans: The Java platform differs from most other platforms in the sense that it’s a software-based platform that runs on top of other hardware-based platforms. It has two components:

  • Runtime Environment
  • API(Application Programming Interface)

Core Java Interview Questions 5 Years Experience

What gives Java its ‘write once and run anywhere’ nature?
Ans: The bytecode. Java is compiled to be bytecode, which is the intermediate language between source code and machine code. This bytecode is not platform-specific and, hence, can be fed to any platform.

What is a classloader?
Ans: The classloader is a subsystem of the JVM that loads classes and interfaces. There are many types of classloaders, such as Bootstrap, Extension, System, and Plugin.

Is the Empty .java file name a valid source file name?
Ans: Yes, save your java file by .java only, compile it by javac .java, and run by java your class name. Let’s take a simple example:

//save by .java only
class A{
public static void main(String args[]){
System.out.println("Hello java");
}
}
//compile by javac .java
//run by java A
compile it by javac .java

Ans: run it by java A

If I don’t provide any arguments on the command line, will the String array of the Main method be empty or null?
Ans: It is empty. But not null.

What if I write static public void instead of the public static void?
Ans: The program compiles and runs properly.

What is the default value of the local variables?
Ans: The local variables are not initialized to any default value, neither primitives nor object references.

What is the difference between an object-oriented programming language and an object-based programming language?
Ans: Object-based programming languages follow all the features of OOPs except Inheritance. Examples of object-based programming languages are JavaScript, VBScript, etc.

What will be the initial value of an object reference which is defined as an instance variable?
Ans: The object references are all initialized to null in Java.

What is a constructor?
Ans: Constructor is just like a method that is used to initialize the state of an object. It is invoked at the time of object creation.

What is the purpose of a default constructor?
Ans: The default constructor provides the default values for the objects. The Java compiler creates a default constructor only if there is no constructor in the class.

Does the constructor return any value?
Ans: Yes, that is a current instance (you cannot use the return type yet; it returns a value).

Is the constructor inherited?
Ans: No, the constructor is not inherited.

Can you make a constructor final?
Ans: No, the constructor can’t be final.

Core Java Interview Questions For 10 Years Experienced

What is a static variable?
Ans: A static variable refers to the common property of all objects (that is not unique for each object), e.g., the company name of employees, the college name of students, etc. A static variable gets memory only once in a class area at the time of class loading.

What is the static method?
Ans: A static method belongs to the class rather than an object of a class. A static method can be invoked without the need for creating an instance of a class. the static method can access static data member and can change their value.

Why is the main method static?
Ans: Because the object is not required to call the static method if it were a non-static method, the JVM creates the object first and then calls the main() method, which leads to the problem of extra memory allocation.

What is a static block?
Ans: Is used to initialize the static data member. It is executed before the main method at the time of class loading.

Can we execute a program without the main() method?
Ans: Yes, one of the ways is a static block.

What if the static modifier is removed from the signature of the main method?
Ans: Program compiles. But at runtime throws an error “NoSuchMethodError”.

What is the difference between the static (class) method and the instance method?
Ans: static or class method instance method

Static MethodInstance Method
A method, i.e. declared as static is known as a static method.A method, i.e. not declared as static, is known as an instance method.
The object is not required to call the static method.The object is required to call instance methods.
Non-static (instance) members cannot be accessed in a static context (static method, static block, and static nested class) directly.Static and non-static variables can be accessed in instance methods.
For example: public static int cube(int n){ return n*n*n;}For example: public void msg(){…}.

What is this in java?
Ans: It is a keyword that refers to the current object.

What is Inheritance?
Ans: Inheritance is a mechanism by which one object acquires all the properties and behavior of another object in another class. It represents the IS-A relationship. It is used for Code Reusability and Method Overriding.

Which class is the superclass of every class?
Ans: Object class.

Why are multiple inheritances not supported in Java?
Ans: To reduce the complexity and simplify the language, multiple inheritances are not supported in java in case of class.

What is composition?
Ans: Holding the reference of the other class within some other class is known as composition.

What is the difference between aggregation and composition?
Ans: Aggregation represents a weak relationship, whereas composition represents a strong relationship. For example, the bike has an indicator (aggregation), but the bike has an engine (composition).

Why does Java not support pointers?
Ans: Pointer is a variable that refers to the memory address. They are not used in Java because they are unsafe(unsecured) and complex to understand.

What is super in java?
Ans: It is a keyword that refers to the immediate parent class object.

Can you use this() and super() both in a constructor?
Ans: No. Because super() or this() must be the first statement.

What is object cloning?
Ans: Object cloning is used to create the exact copy of an object.

What is method overloading?
Ans: If a class has multiple methods with the same name but different parameters, this is known as Method Overloading. It increases the program’s readability.

Why is method overloading not possible by changing the return type in Java?
Ans: Because of ambiguity.

Core Java Interview Questions For 3 Years of Experience

Can we overload the main() method?
Ans: Yes, You can have many main() methods in a class by overloading the main method.

What is method overriding:
Ans: If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to provide the specific implementation of the method.

Can we override the static method?
Ans: No, you can’t override the static method because they are part of the class, not an object.

Why can we not override the static method?
Ans: It is because the static method is part of a class and is bound to the class, whereas the instance method is bound to an object. Static gets memory in the class area, and instance gets memory in a heap.

Can we override the overloaded method?
Ans: Yes.

Difference between method Overloading and Overriding.
Ans:

Method OverloadingMethod Overriding
Method overloading increases the readability of the program.Method overriding provides the specific implementation of the method that is already provided by its superclass.
Method overloading occurs within the class.Method overriding occurs in two classes that have an IS-A relationship.
In this case, a parameter must be different.In this case, a parameter must be the same.

Core Java Interview Questions For Selenium

What is the final variable?
Ans: If you make any variable final, you cannot change the value of a final variable(It will be constant).

What is the final method?
Ans: Final methods can’t be overridden.

What is the final class?
Ans: Final class can’t be inherited.

What is the final blank variable?
Ans: A final variable that is not initialized at the time of declaration is known as a final blank variable.

Can we initialize the final blank variable?
Ans: Yes, only in the constructor if it is non-static. If it is a static blank final variable, it can be initialized only in the static block.

Can you declare the main method as final?
Ans: Yes, such as public static final void main(String[] args){}.

What is Runtime Polymorphism?
Ans: Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The method to be called is determined based on the object referred to by the reference variable.

Can you achieve Runtime Polymorphism by data members?
Ans: No.

What is the difference between static binding and dynamic binding?
Ans: The type of object’s static binding is determined at compile time, whereas the type of object’s dynamic binding is determined at runtime.

What is abstraction?
Ans: Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Abstraction lets you focus on what the object does instead of how it does it.

What is the difference between abstraction and encapsulation?
Ans: Abstraction hides the implementation details, whereas encapsulation wraps code and data into a single unit.

What is an abstract class?
Ans: A class that is declared as abstract is known as an abstract class. It needs to be extended, and its method must be implemented. It cannot be instantiated.

Can there be any abstract method without an abstract class?
Ans: No, if there is an abstract method in a class, that class must be abstract.

Can you use abstract and final both with a method?
Ans: No, because the abstract method needs to be overridden, whereas you can’t override a final method.

Is it possible to instantiate the abstract class?
Ans: No, the abstract class can never be instantiated.

What is an interface?
Ans: Interface is a blueprint for a class that has static constants and abstract methods. It can be used to achieve full abstraction and multiple inheritances.

Can you declare an interface method static?
Ans: No, because interface methods are abstract by default, and static and abstract keywords can’t be used together.

Can an Interface be final?
Ans: No, because another class provides its implementation.

What is a marker interface?
Ans: An interface that has no data member and method is known as a marker interface. For example, Serializable, Cloneable, etc.

What is the difference between abstract class and interface?
Ans: Abstract class Interface

  • An abstract class can have a method body (non-abstract methods). The interface has only abstract methods.
  • An abstract class can have instance variables. An interface cannot have instance variables.
  • An abstract class can have a constructor. An interface cannot have a constructor.
  • An abstract class can have static methods. An interface cannot have static methods.
  • You can extend one abstract class. You can implement multiple interfaces.

Can we define private and protected modifiers for variables in interfaces?
Ans: No, they are implicitly public.

When can an object reference be cast to an interface reference?
Ans: An object reference can be cast to an interface reference when the object implements the referenced interface.

What is a package?
Ans: A package is a group of similar types of classes, interfaces, and sub-packages. It provides access protection and removes naming collision.

Do I need to import the Java.lang package at any time? Why?
Ans: No. It is, by default, loaded internally by the JVM.

Can I import the same package/class twice? Will the JVM load the package twice at runtime?
Ans: One can import the same package or class multiple times. Neither the compiler nor the JVM complains about it. However, the JVM will internally load the class only once, no matter how many times you import the same class.

What is a static import?
Ans: By static import, we can access the static members of a class directly; there is no need to qualify them with the class name.

What is Exception Handling?
Ans: Exception Handling is a mechanism to handle runtime errors. It is mainly used to handle checked exceptions.

What is the difference between a Checked Exception and an Unchecked Exception?
Ans:

Checked ExceptionUnchecked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.The classes that extend RuntimeException are known as unchecked exceptions, e.g. ArithmeticException, NullPointerException etc. Unchecked exceptions are not checked at compile-time.

What is the base class for Error and Exception?
Ans: Throwable.

Is it necessary that a catch block must follow each try block?
Ans: It is not necessary that a catch block follow each try block. It should be followed by either a catch block or a finally block. Whatever exceptions are likely to be thrown should be declared in the method’s throws clause.

What is finally block?
Ans: finally block is a block that is always executed.

Can finally block be used without a catch?
Ans: Yes, by try block. finally must be followed by either try or catch.

Is there any case when finally will not be executed?
Ans: finally, it will not be executed if the program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

What is the difference between throw and throws?
Ans:

Throw KeywordThrows Keyword
throw is used to throw an exception explicitly.Throws are used to declare an exception.
Checked exceptions cannot be propagated with throw only.A checked exception can be propagated with throws.
An instance follows the throw.Throws are followed by class.
the throw is used within the method.Throws are used with the method signature.
You cannot throw multiple exceptionsYou can declare multiple exceptions, e.g. public void method()throws IOException, SQLException.

Can an exception be rethrown?
Ans: Yes.

Can the subclass overriding method declare an exception if the parent class method doesn’t throw an exception?
Ans: Yes, but only unchecked exceptions are not checked.

What is exception propagation?
Ans: Forwarding the exception object to the invoking method is known as exception propagation.

What is the meaning of immutable in terms of String?
Ans: The simple meaning of immutable is unmodifiable or unchangeable. Once the string object has been created, its value can’t be changed.

Why are string objects immutable in Java?
Ans: Java uses the concept of a string literal. Suppose there are five reference variables, all referring to one object, “Sachin.” If one reference variable changes the value of the object, it will be affected by all the reference variables. That is why string objects are immutable in Java.

How many ways can we create the string object?
Ans: There are two ways to create the string object: by a string literal and by a new keyword.

Core Java Coding Interview Questions

How many objects will be created in the following code?
Ans:
String s1=”Welcome”;
String s2=”Welcome”;
String s3=”Welcome”;
Only one object.

Why Java uses the concept of a string literal?
Ans: This will make Java more memory efficient (because no new objects are created if they already exist in the constant string pool).

How many objects will be created in the following code?
Ans: String s = new String(“Welcome”);
Two objects, one in constant string pool and the other in non-pool(heap).

What is the basic difference between a string and a StringBuffer object?
Ans: String is an immutable object. StringBuffer is a mutable object.

What is the difference between StringBuffer and StringBuilder?
Ans: StringBuffer is synchronized, whereas StringBuilder is not synchronized.

How can we create an immutable class in Java?
Ans: We can create an immutable class as the String class by defining a final class and

What is the purpose of the toString() method in Java?
Ans: The toString() method returns the string representation of an object. If you print any object, the Java compiler internally invokes the toString() method on the object. So, overriding the toString() method returns the desired output. It can be the state of an object, etc., depending on your implementation.

What is a nested class?
Ans: A class that is declared inside another class is known as a nested class. There are four types of nested class members: inner class, local inner class, anonymous inner class, and static nested class.

Is there any difference between nested classes and inner classes?
Ans: Yes, inner classes are non-static nested classes, i.e., they are part of nested classes.

Can we access the non-final local variable inside the local inner class?
Ans: No, the local variable must be constant if you want to access it in a local inner class.

What is a nested interface?
Ans: Any interface, i.e. declared inside the interface or class, is known as a nested interface. It is static by default.

Can a class have an interface?
Ans: Yes, it is known as the nested interface.

Can an Interface have a class?
Ans: Yes, they are static implicitly.

What is a Garbage Collection?
Ans: Garbage collection is a process of reclaiming unused runtime objects. It is performed for memory management.

What is GC()?
Ans: GC() is a daemon thread. The GC() method is defined in the System class and is used to send a request to the JVM to perform garbage collection.

What is the purpose of the finalize() method?
Ans: finalize() method is invoked just before the object is garbage collected. It is used to perform cleanup processing.

Can unreferenced objects be referenced again?
Ans: Yes.

What kind of thread is the Garbage collector thread?
Ans: Daemon thread.

What is the difference between final, finally and finalize?
Ans:

  • Final: final is a keyword, final can be variable, method or class. You can’t change the value of the final variable, can’t override the final method, can’t inherit the final class.
  • Finally: finally block is used in exception handling. Finally, the block is always executed.
  • finalize(): The finalize() method is used in garbage collection.finalize() method is invoked just before the object is garbage collected. The finalize() method can be used to perform any cleanup processing.

What is the purpose of the Runtime class?
Ans: The purpose of the Runtime class is to provide access to the Java runtime system.

How will you invoke any external process in Java?
Ans: By Runtime.getRuntime().exec(?) method.

What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
Ans: The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

What is an I/O filter?
Ans: An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

What is serialization?
Ans: Serialization is a process of writing an object’s state into a byte stream. It is mainly used to transport an object’s state on the network.

What is Deserialization?
Ans: Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization.

What is a transient keyword?
Ans: If you define any data member as transient, it will not be serialized.

What is Externalizable?
Ans: The externalizable interface is used to write an object’s state into a compressed byte stream. It is not a marker interface.

What is the difference between a Serializable and an Externalizable interface?
Ans: Serializable is a marker interface, but Externalizable is not a marker interface. When you use the Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject(), two methods to control more complex object serialization processes. When you use an Externalizable interface, you have complete control over your class’s serialization process.

What is a reflection?
Ans: Reflection is the process of examining or modifying the runtime behavior of a class at runtime. It is used in:
IDE (Integrated Development Environment), e.g. Eclipse, MyEclipse, NetBeans. Debugger Test Tools etc.

Can you access the private method from outside the class?
Ans: Yes, by changing the runtime behaviour of a class if the class is not secured.

What are wrapper classes?
Ans: Wrapper classes are classes that allow primitive types to be accessed as objects.

What is a native method?
Ans: A native method is a method that is implemented in a language other than Java.

What is the purpose of the System class?
Ans: The purpose of the System class is to provide access to system resources.

What comes to mind when someone mentions a shallow copy in Java?
Ans: Object cloning.

What is a singleton class?
Ans: A singleton class means that at any given time, only one instance of the class is present in one JVM.

What is the difference between an Inner Class and a Sub-Class?
Ans: An Inner class is a class that is nested within another class. It has access rights for the class that is nesting it and can access all variables and methods defined in the outer class.

A subclass is a class that inherits from another class called a superclass. Subclass can access all public and protected methods and fields of its super class.

What are the various access specifiers for Java classes?
Ans: In Java, access specifiers are the keywords used before a class name that defines the access scope. The types of access specifiers for classes are:

  • Public: Class, Method, and Field are accessible from anywhere.
  • Protected: Method and Field can be accessed from the same class to which they belong, from subclasses, and from the class of the same package, but not from outside.
  • Default: Method, Field, and class can be accessed only from the same package and not from outside of its native package.
  • Private: Method, Field can be accessed from the same class to which they belong.

What’s the purpose of Static methods and static variables?
Ans: When a method or variable must be shared between multiple objects of a class instead of being created as separate copies for each object, we use the static keyword to make the method or variable shared for all objects.

What is data encapsulation, and what’s its significance?
Ans: Encapsulation is a concept in Object-Oriented Programming that combines properties and methods in a single unit. It helps programmers follow a modular approach to software development, as each object has its own set of methods and variables and serves its functions independently of other objects. Encapsulation also serves a data-hiding purpose.

What is a singleton class? Give a practical example of its usage.
A singleton class in Java can have only one instance, and hence, all its methods and variables belong to that instance. The singleton class concept is useful for situations when the number of objects for a class needs to be limited.

The best example of a singleton usage scenario is when there is a limit of having only one connection to a database due to driver limitations or licensing issues.

What is an infinite Loop? How is the infinite loop declared?
Ans: An infinite loop runs without any condition and runs infinitely. An infinite loop can be broken by defining any breaking logic in the body of the statement blocks.

for(::)
{
	// Statements to execute
	// Add any loop breaking logic
}

What is the difference between double and float variables in Java?
Ans: In Java, float takes 4 bytes in memory, while Double takes 8 bytes in memory. Float is a single-precision floating-point decimal number, while Double is a double-precision decimal number.

How can you generate random numbers in Java?
Using Math random(), you can generate random numbers in the range greater than or equal to 0.1 and less than 1.0
Using random class in the java.util package.

What’s the base class in Java from which all classes are derived?
Ans: java.lang.object

List the features of the Java Programming language.
A few of the significant features of Java Programming Language are:

  • Easy: Java is a language that is considered easy to learn. One fundamental concept of OOP Java has a catch to understand.
  • System Feature: Java has a secure feature that helps develop a virus-free and tamper-free system for users.
  • Independent Platform: Java is not compiled into a platform-specific machine; instead, it is compiled into platform-independent bytecode. The virtual Machine on which the platform runs interprets this code.

What is an Association?
An Association can be defined as a relationship that has no ownership over another. For example, a person can be associated with multiple banks, and a bank can be related to various people, but no one can own the other.

What do you mean by aggregation?
The term aggregation refers to the relationship between two classes best described as a “whole/part” and “has-a” relationship. This kind is the most specialized version of an association relationship. It contains the reference to another class and is said to have.

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

What is Object Cloning?
In Java, object cloning is the ability to recreate an object entirely similar to an existing object. Java provides a clone() method to clone a current object offering the same functionality as the original object.

Can the main() method in Java return any data?
Ans: In Java, the main() method can’t return any data, so it’s always declared with a void return type.

What are Java Packages? What’s the significance of packages?
Ans: In Java, a package is a collection of classes and interfaces bundled together because they are related to each other. Packages help developers modularize code and group it for proper reuse. Once code has been packaged in Packages, it can be imported into other classes and used.

Can we declare a class as Abstract without having any abstract method?
Ans: Yes, we can create an abstract class by using the abstract keyword before the class name, even if it doesn’t have any abstract methods. However, if a class has even one abstract method, it must be declared as abstract; otherwise, it will give an error.

What are the performance implications of Interfaces over abstract classes?
Ans: Interfaces are slower in performance as compared to abstract classes as extra indirections are required for interfaces. Another key factor for developers to take into consideration is that any class can extend only one abstract class while a class can implement many interfaces. The use of interfaces also puts an extra burden on the developers as any time an interface is implemented in a class; the developer is forced to implement each and every method of
interface.

What is an object-oriented paradigm?
A Paradigm based on the concepts of ‘Objects.’ It contains data and code. Data in the form of fields and regulations in the form of procedures. The exciting feature of this paradigm is that the object’s procedures can access and often modify the data fields themselves.

Does Importing a package import its sub-packages as well in Java?
Ans: In Java, when a package is imported, its sub-packages aren’t imported, and the developer needs to import them separately if required. For example, if a developer imports a package university.*, all classes in the package named universities are loaded, but no classes from the sub-package are loaded. To load the classes from its sub-package ( say department), the developer has to import it explicitly as follows:
Import university.department.*

Can we declare the main method of our class as private?
Ans: In Java, the main method must be public static in order to run any application correctly. If the main method is declared as private, the developer won’t get any compilation error however, it will not get executed and will give a runtime error.

How can we pass arguments to a function by reference instead of pass-by-value?
Ans: In Java, we can pass arguments to a function only by value and not by reference.

How is an object serialized in Java?
Ans: In Java, to convert an object into a byte stream by serialization, a class implements an interface named Serializable. All objects of a class implementing serializable interfaces get serialized, and their state is saved in a byte stream.

When should we use serialization?
Ans: Serialization is used when data needs to be transmitted over the network. Using serialization, an object’s state is saved and converted into a byte stream. The byte stream is transferred over the network, and the object is re-created at the destination.

Is it compulsory for a Try Block to be followed by a Catch Block in Java for Exception handling?
Ans: The try block needs to be followed by either the Catch block or the finally block, or both. Any exception thrown from the try block needs to be either caught in the catch block or put in the finally block. Any specific tasks to be performed before code abortion are put in the Finally block.

Is there any way to skip the Finally block of exception even if some exception occurs in the exception block?
Ans: If an exception is raised in the Try block, control passes to the catch block if it exists; otherwise, it will transferred to finally blocked. Finally, block is always executed when an exception occurs, and the only way to avoid execution of any statements in the Finally block is by aborting the code forcibly by writing the following line of code at the end of the try block:
System.exit(0):

Can a class have multiple constructors?
Ans: Yes, a class can have multiple constructors with different parameters. Which constructor gets used for object creation depending on the arguments passed while creating the objects?

Define Wrapper Classes in Java.
In Java, when you declare primitive data types, then Wrapper classes are responsible for converting them into objects(Reference types).

Can we override static methods of a class?
Ans: We cannot override static methods. Static methods belong to a class and not to individual objects and are resolved at the time of compilation (not at runtime). Even if we try to override static methods, we will not get a compilation error, nor will we experience the impact of overriding when running the Code.

Is String a data type in Java?
Ans: String is not a primitive data type in Java. When a string is created in Java, it’s actually an object of Java.Lang.String class that gets created. After the creation of this string object, all built-in methods of the String class can be used on the string object.

What’s the difference between an array and a Vector?
Ans: An array groups data of the same primitive type and is static in nature, while vectors are dynamic in nature and can hold data of different data types.

Define package in Java.
A package is a collective bundle of classes and interfaces, the necessary libraries, and JAR files. Packages help ensure code reusability.

Differentiate between instance and local variables.
For instance, variables are declared inside a class, and the scope of variables in Java is limited to only a specific object.
A local variable can be anywhere inside a method or a specific block of code. Also, the scope is limited to the code segment where the variable is declared.

Why is Java a platform-independent language?
One of the most well-known and widely used programming languages is Java. It is a programming language that is independent of platforms. Java doesn’t demand that the complete program be rewritten for every possible platform.

The Java Virtual Machine and Java Bytecode are used to support platform independence. Any JVM operating system can run this platform-neutral byte code. The application is run after JVM translates the byte code into machine code. Because Java programs can operate on numerous systems without having to be individually rewritten for each platform, the language is referred to as Write Once, RunAnywhere” (WORA).

What is multithreading?
Ans: Multithreading is a programming concept for running multiple tasks concurrently within a single program. Threads share the same process stack and run in parallel. It helps improve the performance of any program.

Why is the Runnable Interface used in Java?
Ans: Java uses the runnable interface to implement multi-threaded applications. The Java.Lang. Runnable interface is implemented by a class to support multi-threading.

What are the two ways of implementing multithreading in Java?
Ans: Multi-threaded applications can be developed in Java by using any of the following two methodologies:

  • By using Java.Lang.Runnable Interface. Classes implement this interface to enable multi-threading. There is a Run method in this interface which is implemented.
  • By writing a class that extends Java.Lang. Thread class.

When a lot of changes are required in data, which one should be a preference for use? String or StringBuffer?
Ans: Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects, unlike String, which is immutable, it’s always a good choice to use StringBuffer when data is being changed too much. If we use String in such a case, for every data change, new String objects will be created, which will be an extra overhead.

What’s the purpose of using Break in each case of Switch Statement?
Ans: A break is used after each case (except the last one) in a switch so that code breaks after the valid case and doesn’t flow in the proceeding cases, either. If the break isn’t used after each case, all cases after the valid case also get executed, resulting in wrong results.

How is garbage collection done in Java?
Ans: In Java, when an object is no longer referenced, garbage collection takes place, and the object is destroyed automatically. For automatic garbage collection, Java calls either the System.gc() method or the Runtime.gc() method.

How can we execute any code even before the main method?
Ans: If we want to execute any statements before creating objects at class load time, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class, even before creating objects in the main method.

How objects of a class are created if no constructor is defined in the class?
Ans: Even if no explicit constructor is defined in a Java class, objects get created successfully as a default constructor is implicitly used for object creation. This constructor has no parameters.

What are the differences between the constructor and method of a class in Java?
Initializing the state of the object is done by constructors. A function Object 0 ( [native code] ). like methods, contains a group of statements (or instructions) that are carried out when an object is created. A method is a group of statements that work together to complete a certain task and return the outcome to the caller. A method has the option of working without returning anything

In multi-threading, how can we ensure that a resource isn’t used by multiple threads simultaneously?
Ans: In multi-threading, access to resources shared among multiple threads can be controlled using the concept of synchronization. Using the synchronized keyword, we can ensure that only one thread can use a shared resource at a time, and others can get control of the resource only once it has become free from the other one using it.

Can we call the constructor of a class more than once for an object?
Ans: The constructor is called automatically when we create an object using a new keyword. It’s called only once for an object at the time of creation, and hence, we can’t invoke the constructor again for an object after its creation.

There are two classes named classA and classB. Both classes are in the same package. Can a private member of a classA can be accessed by an object of classB?
Ans: Private members of a class aren’t accessible outside the scope of that class, and any other class, even in the same package, can’t access them.

What happens if there are multiple main methods inside one class in Java?
There is no limit to the number of major approaches you can use. Overloading is the ability to have main methods with different signatures than the main(String []), and the JVM will disregard those main methods.

What is the benefit of using inheritance?
Ans: The key benefit of inheritance is code reuse, as inheritance enables subclasses to reuse the code of their superclass. Polymorphism (Extensibility ) is another great benefit, allowing new functionality to be introduced without affecting existing derived classes.

What’s the default access specifier for variables and methods of a class?
Ans: The default access specifier for variables and methods is package protected, i.e., variables and classes are available to any other class but in the same package, not outside the package.

Give an example of the use of Pointers in Java class.
Ans: Java does not have pointers, so we can’t use the concept of pointers in Java.

What’s the difference between Stack and Queue?
Ans: Stack and Queue are both used as placeholders for the collection of data. The primary difference between them is that a stack is based on the Last in, First out (LIFO) principle, while a queue is based on the FIFO (First In, First Out) principle.

How can we use primitive data types as objects?
Wap perise a real in he ana are as heise of t pen. Ce can apply different methods to a wrapper class, just like any other object.

Which types of exceptions are caught at compile time?
Ans: Checked exceptions can be caught during program compilation. To compile the code successfully, checked exceptions must be handled using a try-catch block.

Describe the different states of a thread.
Ans: A thread in Java can be in either of the following states:

  • Ready: When a thread is created, it’s in a Ready state.
  • Running: A thread currently being executed is in a running state.
  • Waiting: A thread waiting for another thread to free certain resources is in a waiting state.
  • Dead: A thread that has gone dead after execution is in a dead state.

Can we use a default constructor of a class even if an explicit constructor is defined?
Ans: Java provides a default no-argument constructor if no explicit constructor is defined in a Java class. But if an explicit constructor has been defined, the default constructor can’t be invoked, and developers can use only those constructors defined in the class.

Can we override a method by using the same method name and arguments but different return types?
Ans: The basic condition of method overriding is that the method name, arguments, and return type must be exactly the same as those of the method being overridden. Hence, using a different return type doesn’t override a method.

A person says that he compiled a Java class successfully without even having a main method in it. Is it possible?
Ans: The main method is an entry point to the Java class and is required for the program’s execution; however, a class gets compiled successfully even if it doesn’t have a main method. It can’t be run, though.

How does an exception propagate in the code?
If an exception is not caught, it is initially thrown from the top of the stack and then moves down the call stack to the preceding method. The runtime system looks for a way to handle an exception that a method throws. The ordered list of methods that were called to get to the method where the error occurred is the collection of potential “somethings” that can be used to manage the exception. The call stack is the list of methods, and exception propagation is the search technique.

How many overloaded add() and addAll) methods are available in the List interface? Describe the needs and uses.
The list is an interface in the Java Collections Framework. The add() and addAll) methods are
the main methods at the List interface. The add() method is used to add an element to the list.
while the addAll) method is used to add a collection of elements to the list.
The List interface contains two overloaded versions of the add() method:

  • The first add() method accepts a single argument of type E, the element to be added to the list.
  • The second add() method accepts a variable number of arguments of type E, which are the elements to be added to the list.

The List interface also contains two overloaded versions of the addAll() method:

  • The first addAll() method accepts a single argument of type Collection, which is the collection of elements to be added to the list.
  • The second addAll() method accepts a variable number of arguments of type E, which are the elements to be added to the list.

What are Composition and Aggregation? State the difference.
Aggregation (HAS-A) and composition are its two forms (Belongs-to). In contrast to composition, which has a significant correlation, the aggregation has a very modest association. Aggregation can be thought of as a more confined version of the composition. Since all compositions are aggregates but not all aggregates are compositions, aggregate can be thought of as the superset of composition.

Can we call a non-static method from inside a static method?
Ans: Non-static methods are owned by class objects and have an object-level scope. To call them from a static block (like from a static main method), the class object needs to be created first. Then, using an object reference, these methods can be invoked.

What are the two environment variables that must be set in order to run any Java programs?
Ans: Java programs can be executed in a machine only once the following two environment variables have been properly set:

  1. PATH variable
  2. CLASSPATH variable

Can variables be used in Java without initialization?
Ans: In Java, if a variable is used in code without prior initialization by a valid value, the program doesn’t compile and gives an error, as no default value is assigned to variables in Java.

Can a class in Java be inherited from more than one class?
Ans: In Java, a class can be derived from only one class and not from multiple classes. Multiple inheritance is not supported by Java.

Can a constructor have a different name than a Class name in Java?
Ans: The constructor in Java must have the same name as the class name, and if the name is different, it doesn’t act as a constructor, and the compiler thinks of it as a normal method.

What will be the output of Round(3.7) and Ceil(3.7)?
Ans: Round(3.7) returns 4 and Ceil(3.7) returns 4.

Can we use goto in Java to go to a particular line?
Ans: In Java, there is no goto keyword, and Java doesn’t support this feature of going to a particular labeled line.

Can a dead thread be started again?
In Java, a thread in a dead state cannot be started again. There is no way to restart a dead thread.

IS JDK Required on each machine to run a Java program?
Ans: JDK is a Java development kit required for development only. It isn’t required to run a Java program on a machine; only JRE is required.

Is it possible to define a method in Java class but provide its implementation in the code of another language like C?
Ans: Yes, we can do this by using native methods. In native method-based development, we define public static methods in our Java class without their implementation, and then implementation is done in another language, like C, separately.

Why is synchronization necessary? Explain with the help of a relevant example.
Multiple threads trying to access the same resources in a multi-threaded software may frequently result in unexpected and incorrect outcomes. Therefore, it must be ensured through some form of synchronization that only one thread can access the resource at any given time. Java offers a method for setting up threads and synchronizing their operations with the aid of synchronized blocks. The synchronized keyword in Java is used to identify synchronized blocks.

In Java, a synchronized block is tied to an object. Since synchronized blocks are all synchronized on the same object, only one thread can be running at a time inside them. Until the thread inside the synchronized block exits, all other threads trying to enter the block are blocked.

Explain the ‘this’ keyword in Java.
The term “this” is a particular keyword designated as a reference keyword. It refers to the current class properties like methods, instances, variables, and constructors.

How are destructors defined in Java?
Ans: In Java, there are no destructors defined in the class, as there is no need to do so. Java has its own garbage collection mechanism, which does the job automatically by destroying objects when they are no longer referenced.

Can a variable be local and static at the same time?
Ans: No, a variable can’t be static and local at the same time. Define a local variable as static gives a compilation error.

Can we have static methods in an Interface?
Ans: Static methods can’t be overridden in any class, while methods in an interface are, by default, abstract and are supposed to be implemented in the classes implementing the interface. So, it makes no sense to have static methods in an interface in Java.

In a class implementing an interface, can we change the value of any variable defined in the interface?
Ans: No, we can’t change the value of any variable of an interface in the implementing class as all variables defined in the interface are, by default, public, static, and Final, and final variables are like constants, which can’t be changed later.

Is it correct to say that a Java program never runs out of memory due to the garbage collection feature in Java?
Ans: Even though Java provides automatic garbage collection, it doesn’t ensure that a Java program will not run out of memory. There is a possibility that creating Java objects is being done at a faster pace than garbage collection, resulting in filling all the available memory resources.

So, garbage collection helps reduce the chances of a program running out of memory, but it doesn’t ensure that.

Can we have any other return type than void for the main method?
Ans: No, the Java class main method can have only a void return type for the program to get successfully executed. Nonetheless, if you absolutely must retum a value to at the completion of main method, you can use System.exit(int status)

I want to re-reach and use an object once it has been garbage collected. How is it possible?
Ans: Once a garbage collector destroys an object, it no longer exists on the heap and cannot be accessed again. There is no way to reference it again.

In Java thread programming, which method is a must-implement for all threads?
Ans: Run() is a method of Runnable interface that must be implemented by all threads.

I want to control database connections in my program and want only one thread to be able to make database connections at a time. How can I implement this Logic?
Ans: This can be implemented using the concept of synchronization. Database-related code can be placed in a method with a synchronized keyword so that only one thread can access it at a time.

How can an exception be thrown manually by a programmer?
Ans: The throw keyword is used to manually throw an exception in a block of code. The exception is then caught and handled in the catch block.

public void topMethod()
{
	try 
	{
		excMethod();
	} 
	catch (ManualException e) 
	{
	}
}
public void excMethod()
{
	String name = null;
	if (name == null)
	{
		throw (new ManualException("Exception thrown manually");
	}
}

I want my class to be developed so that no other class (even a derived class) can create its objects. How can I do so?
Ans:
If we declare a class’s constructor private, it will not be accessible by any other class, and hence, no other class will be able to instantiate it. The formation of its object will be limited to itself only.

How are objects stored in Java?
Ans: In Java, each object, when created, gets a memory space from a heap. When an object is destroyed by a garbage collector, the space allocated to it from the heap is reallocated to the heap and becomes available for any new objects.

How can we find the actual size of an object on the heap?
Ans: In Java, there is no way to determine an object’s exact size on the heap.

Which of the following classes will have more memory allocated?
Class A: Three methods, four variables, no object
Class B: Five methods, three variables, no object

Ans: Memory isn’t allocated before objects are created. Since no objects are created for both classes, no memory is allocated on the heap for any class.

What happens if an exception is not handled in a program?
Ans: If an exception is not handled in a program using try-catch blocks, the program is aborted, and no statement executes after it, which causes an exception to throw.

I have multiple constructors defined in a class. Is it possible to call a constructor from another constructor’s body?
Ans: If a class has multiple constructors, it’s possible to call one constructor from the body of another one using this().

Explain the ‘super’ keyword in Java.
The term “super” is a particular keyword designated as a reference keyword. The “super” keywords refer to the immediate parent class object.

Is there a way to increase the size of an array after its declaration?
Ans: Arrays are static and once we have specified its size, we can’t change it. If we want to use such collections where we may require a change of size (no of items), we should prefer vector over array.

If an application has multiple classes in it, is it okay to have a main method in more than one class?
Ans: If there is a main method in more than one class in a Java application, it won’t cause any issue as an entry point for any application will be a specific class, and the code will start from the main method of that particular class only.

I want to persist data of objects for later use. What’s the best approach to do so?
Ans: The best way to persist data for future use is to use the concept of serialization.

What is a Local class in Java?
Ans: In Java, if we define a new class inside a particular block, it’s called a local class. Such a class has local scope and isn’t usable outside the block where it’s defined.

String and StringBuffer both represent String objects. Can we compare String and StringBuffer in Java?
Ans: Although String and StringBuffer both represent String objects, we can’t compare them, and if we try to compare them, we get an error.

Which AP| is provided by Java for operations on a set of objects?
Ans: Java provides a Collection API, which provides many useful methods for applying to a set of objects. Some of the important classes provided by the Collection API include ArrayList, HashMap, TreeSet, and TreeMap.

Can we cast any other type to Boolean Type with type casting?
Ans: No, we can neither cast any other primitive type to the Boolean data type nor can we cast the Boolean data type to any other primitive data type.

What’s the base class of all exception classes?
Ans: In Java, Java lang. Throwable is the superclass of all exception classes, and all exception classes are derived from this base class.

Can we overload a static method?
No, Java does not support the Overloading of a static method. The process would throw an error reading “static method cannot be referenced.”

What’s the order of call of constructors in inheritance?
Ans: In the case of inheritance, when a new object of a derived class is created, first, the constructor of the superclass is invoked, and then the constructor of the derived class is involved.

What is the Daemon Thread?
The Daemon thread can be defined as the thread with the least priority. This Daemon thread is designed to run in the background during the Garbage Collection in Java.
The setDaemon() method creates a Daemon thread in Java.

Can you run a code before executing the main method?
Yes, we can execute any code, even before the main method. We will be using a static block of code when creating the objects at the class’s load time. Any statements within this static block of code will get executed at once while loading the class, even before creating objects in the main method.

Can “this” and “super” keywords be used together?
No, “this” and “super” keywords should be used in the first statement in the class constructor. The following code gives you a brief idea.

public class baseClass
{
	baseClass()
	{
		super();
		this();
		System.out.println("BaseClass Object is Created");
	}
	public static void main(String[] args)
	{
		baseClass obj=new baseClass();
	}
}

What is the difference between System.out, System.err, and System.in?
System.out and System.err represent the monitor by default and thus can be used to send data or results to the monitor. System.out is used to display normal messages and results, and System.err is used to display error messages. System.in represents the InputStream object, which by default represents the standard input device, I.e., the keyboard.

Do final, finally and finalize keywords have the same function?
No, final, finally and finalize keywords have different functionalities.

  • Final is used to restrict classes, variables, or methods, the final keyword.
  • Finally is used to execute the code written inside the block without handling any exceptions.
  • Finalize is used to call the function of the implementation of cleaning the garbage collection of an object.

When can you use the “super” keyword?
Basically, the super keyword refers to the parent class. When the same fields are present in both parent and child classes, one can use a super keyword to access data members of the parent class.

What are shallow copy and deep copy in Java?
In a shallow copy, primitive data types are copied, whereas in a deep copy, the object references are also copied along with primitive data types.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment