Saturday, 16 March 2024

Important Core Java Interview Questions for Freshers - 2024

    In this post I am sharing important core java interview questions with answers for freshers.

1) Difference between c++ and java


2) What is mean by platform independent?

      We can say java is a platform independent it means that you can compile java code in one platform(e.g windows machine) and run it in another platform(e.g linux) without changing the code.


3) Difference between jdk, jre and jvm.

Refer - difference between jdk, jre and jvm


4) What are access modifiers in java.

      The Access Modifiers in java are Default, Public, Protected and Private.

  • Default 

       This is a default access modifier in java. The scope of the default modifier is within the package.

  • Public
      Public modifier is used with an entity/model or any java class or variables that particular object or class is accessible throughout the application within or outside the package.

  • Protected 
      The scope of this access modifier is within a package and this is also accessible outside the package through inherited class or child class.

  • Private 
      The scope of this access modifier is within a package, it can not access outside the package. 


5) Explain main method in java - public static void main(String[] args).

In the main main public static void main(String[] args) -> 

public -> public is a access modifier and it's accessible whole over the application within or outside the package.

static -> It's a keyword in java and it's used to call the variable or methods without creating the object.

void -> it's return type and void doesn't return anything.

main ->main is the method name here.

String[] args -> It stores the command line arguments and it's  an array of type Strings. args is the argument name, it should be anything.


6) Why java is not pure object oriented language.

     Java has a primitive data type so those are not objects. So except primitive everything is objects but due to primitive data type we can not say java is pure object oriented language.


7) Explain OOP's concept.

Refer - OOP's Concept


8) Explain data types in java.

There are 8 primitive data type as follows,

a) boolean

  Boolean data type represents only one bit of information either true or false. The default value is false.

Syntax:- boolean booleanVarName;

b) byte

    The byte data type is an 8-bit signed two’s complement integer - default value of byte is zero.

1 byte = 8 bits

Syntax :- byte byteVarName;

c) char 

The char data type is a single 16-bit Unicode character with the size of 2 bytes. The default value is \u0000.

Synatx :- char charVarName;

d) short

   The short data type is a 16-bit signed two’s complement integer. The default value of short is zero.

Syntax :- short shortVarName;

e) int 

    It is a 32-bit signed two’s complement integer. The default value of int is zero. 32 bits = 4 bytes

Syntax :- int intVarName;

f) long 

   The long data type is a 64-bit two’s complement integer. The deafult value of long is zero.

Syntax :- long longVarName;

g) float 

    The float data type is a single-precision 32-bit floating-point. The default value of float is 0.0.

Syntax :- float floatVarName;

h) double 

    The double data type is a double-precision 64-bit floating-point. The default value of double is 0.0.

Syntax :- double doubleVarName;


9) What are wrapper classes in java.

Each primitive data type has corresponding wrapper class so there are 8 wrapper classes in java.

Wrapper classes are Character, Byte, Short, Integer, Long, Float, Double and Boolean.

Using wrapper classes we can access object class methods like equals, compare, compareTo, hashcode and thread methods like wait, notify and notifyAll. Collection classes accept only object i.e wrapper not a primitive so this is also one of the advantage of wrapper class instead of primitive.


10) What is JIT compiler.

      JIT stands for Just-in-Time Compiler, it's part of JVM and it optimizes the process of converting byte code to machine specific language. It reduces the compilation time so that it improves the performance.


11) What is mean by instance variable and local variable in java

      The Variables defined inside methods, constructors or blocks are called local variablesThe variable will be declared and initialized within the method and it will be destroyed when the method has completed.

      Instance variables are variables within a class but outside the method or constructors or blocks. These variables are instantiated when the class is loaded and need to call the variables using class object.

Example :- 

public class VariableEx{

    int instanceVar;  //instance variable

    public static void main(String args[]){

        VariableEx obj = new VariableEx();
        int a = 100;                           //local variable
        System.out.println("instance variable instanceVar value is : "
                    +obj.instanceVar);
        System.out.println("local variable a value is  : "+a);
     }
  }


12) Difference between equals and == operator.



13) What is constructor in java ? How many types constructors in java?

     Constructor in java is a block of code that used to create a object of the class. It's similar to method except name and return type, the constructor name should be same as class name and it doesn't have return type.

There are two types of constructors in java, 

1) Default or No-args parameter constructor.

2) Parameterized constructor.


14) What is Constructor chaining?

Constructor chaining in Java is a technique of calling one constructor from within another constructor by using this and super keywords.

  • Using this() keyword to call the current class constructor within the same class.
  • Using super() keyword to call the superclass constructor from the base class.


15) What are interface and abstract class ? Difference between interface and abstract class.

Refer - difference between abstract and interface in java


16) What is marker interface in java 

Refer - Marker interface in java


17) Can we create object of abstract class?

   No, we can not create an object of abstract class but we can create object of child class that extends the abstract class.


18) What is inheritance in java ? What are the types of inheritance in java.

Refer - OOP's Concept


19) Is java supports multiple inheritance

No, Java doesn't support multiple inheritance.


20) What is polymorphism

Refer - Polymorphism in Java


21) Difference between method overloading and overriding.

Refer - Polymorphism in Java


22) What is static keyword in java?

Static is a keyword in java to apply to a variables, methods, blocks and nested classes.

If you declare variable as a final, that variable can not be reassigned. If we used final keyword for method level then the method can't be overriden. 


23) Can we overload static method?

Yes, we can overload static method in java.


24) Can we override static method?

No, we can not override static methods, it won't shows any error but it will execute only parent class static method.


25) Can we overload the main() method?

Yes. Main method executes when class is being invoked but overloaded method need to call using class object.

26) Difference between static and non static method.

     Static methods belongs to a class and it's not belongs to an object of the class. We can call static method using class name directly no need to create an object of the class. Static method access only static variables and other static methods. Inside static methods we can't able to call non static methods.

     Non static methods belongs to an object of the class. Non static methods can access any static methods and static variables directly without creating an instance of the object.


27) What is transient keyword in java.

     The transient is a keyword in java and this is mainly used in serialization process. During serialization, transient variables won't persist or won't consider part of the serialization process.


28) What is serialization in java.

Serialization process in java is to convert an Object to byte stream that we can send over the network or save it as a file or store in a DB.

If you want a class object to be serializable, then need to implement java.io.Serializable interface.  Serializable is a marker interface means it doesn't have any fields or implemented methods.

Reference - Serialization in java


29) What is infinite loop in java.

  Infinite loop in java is a loop that executes indefinitely and the system will terminate or crash beacuse of the memory leak.

Code :- 

 for (;;) {
  System.out.println("Inside a infinite loop");
}


30) Difference between finally block and final keyword.

final is a keyword to used for methods, variables and classes and those values can not change i mean the value should be constant.

finally is a block to use a clean up resouces like closing connections, closing file object and it executes always whether the exception throws or not.


31) When finally block won't execute? 

The finally block always executes except System.exit()


32) What is the use of super keyword.

     The super keyword is used to call parent class constructor, to call parent/override parent class method and to call parent class variables.

  • to call parent class constructor
public ClassChild(String parameter) {
      super(parameter);
}
  • to call parent class method.
public void method1() {
     super.method2();   //this is a parent class method
}
  • to call parent class variable
super.variable;

33) What is grabage collection in java.

Garbage Collection is the process of reclaiming unused memory by destroying the unused objects during run time.

   This is automatic process to de-allocate the memory for unused objects so that it avoids memory leak.


34) What is cloning and explain the types of cloning in java.

Cloning is java is nothing but creating a copy of the original object. To clone the object to use clone() method from the object class, will copy attributes and data from the original object.

There are two types of cloning in java,

  • Shallow Cloning - Stores the copy of the original object and points the references to the objects. This cloning is faster compared to deep cloning.
  • Deep Cloning - Stores the copy of the original object and recursively copies the objects as well.


    35) How many ways to create an object in java.

    There are four ways to create an object in java, 

    • Using new Operator 
    • Using Class.forName()
    • Using cloning
    • Object deserialization
    For more details, refer - object creation in java

    36) Difference between comparable and comparator.

    Refer - Difference between comparable and comparator in java


      37) What is singleton class in Java and how can we make a class singleton?

        Singleton pattern/class restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. 

       Singleton pattern is used for logging, drivers objects, caching and thread pool. Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc.

         To implement the Singleton Design Pattern,you do the following the things,

      • private constructor - no other class can instantiate a new object.
      • private reference - no external modification.
      • public static method is the only place that can get an object.

      Reference :- Singleton Class


      38) How many ways to create String object.

      There are two ways to create a String object 

      • Using String literal - e.g String a = "ABC";
      • Using new operator - e.g String a = new String("ABC");


      39) Difference between String , StringBuffer and StringBuilder.

      String : - It's an immutable means once we define the value it can not be changed so it's thread safety. For concatenation of two strings we can use + operator or .concat method. String can use for the fixed length of content.

      StringBuffer :-  StringBuffer is a mutable, we can modify the content without creating new Object. This is synchronization in nature so it's thread safety. We can use append method to concatenate the two objects. StringBuffer can use in multithreaded environment for frequent text changes.

      StringBuilder :- StringBuilder is a mutable, we can modify the content without creating new Object. This is not synchronized so it's not a thread safe. We can use append method to concatenate the two objects. StringBuilder can use in a single threaded environment for frequent text changes.


      40) Explain exception hierarchy.

      Throwable is the base class in exception and there are sub classes i.e Exception and Error. Again in Exception there are two types , Checked and Unchecked Exception. 

      Below diagram shows the exception hierarchy,


      41) Difference between Exception and Error.

      The Throwable class is the base class for both the exception and error.

      Exception :-   An exception is an abnormal execution of the program, it stops the normal flow. Examples - NullPointerException, IOException and so on. There are two types of Exceptions,

      • Checked Exception 
      • Unchecked Exception. 
      These exceptions can handle using try catch block in java.

      Error :- Error indicates that a non-recoverable condition has occurred that should not be handled, examples - OutOfMemoryError and StackOverflowError .


      42) Can we write try without catch ?

      Yes, we can write try without catch, but try with finally block should exist, catch is not mandatory if finally block exists.

      try {
      //code 
      ....
      
      } finally {
      
      }
      


      • Java 8

      43) What are the new features in java 8.

      Some of the important Java 8 features are,

      • Lambda Expression
      • static and default methods in interface
      • Java Stream
      • Functional Interfaces
      • Java Time API
      • Collection Improvement.
      • Concurrency API improvement
      • Java IO improvement

      44) What are the adantages of using Stream in java 8.

      Stream API is is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
           A stream does not store data means it is not a data structure. It also never modifies the underlying data source.

      Advantages :- In Stream,  there many intermediate methods to perform operations like filter, map, sorted, filterMap and so on to reduce the code and also it's more readable and cleaner code. Using loop prior java 8 need to handle loop related exception explicitly in the code like ArrayindexOutOfBoundsException but using Stream, developer no need to bother about the loop issues, it handles internally.


      45) What is functional interface.

      Functional interface is an interface that contains only one abstract method. @FunctionalInterface annotation is used to define the interface as Functional interface.

      @FunctionalInterface
      public interface Area {
           public int calculateArea(int side);
      }
      


      • Thread

      46) What is synchronization in java ?

             Synchronization is a process of controlling the access of shared resources by the multiple threads in such a way that only one thread can access one resource at a time. In non synchronized multi threaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object so in this case there is data inconsistency in the application.

      Synchronization prevents such type of data corruption.


      47) What is a thread ? How many ways to create thread in java and which one is preferred?

      Thread in java is a light weight process and it's a path of execution within a process.

      There are two ways to create a thread in Java.

      • Extending the Thread class
      • Using Runnable interface(this one prefer)
      The preferred way to create a thread is to implement Runnable interface 

      48) Explain thread life cycle.

      A thread can be in one of the following states ,

      • New born state(New)
      • Ready to run state (Runnable)
      • Running state(Running)
      • Blocked state
      • Dead state

      49) What is daemon thread.

      A daemon thread is a thread that executes the some tasks in the background like handling requests or various chronjobs that can exist in an application.

      The setDaemon() method of the Thread class is used to mark/set a particular thread as either a daemon thread or a user thread.

      thread.setDaemon(true);//if set false then it's normal thread.
      


      50) Difference between wait and sleep method in a thread.

      wait - It's belongs to a Object class. The wait method should be called within a synchronized method or block and this is not a static method. 

      sleep - This method belongs to a Thread class. No need to call this in synchronized block or method.


      51) Difference between start and run method. 

      52) Explain join and yield method in thread

      53) What is multithreading in java?

      54) What is the volatile variable in java

      55) What is use of atomicinteger 


      • Collection

      56) What is collection framework in java ? Explain each interface in collection framework

      57) Difference between arraylist and linked list

      58) How can you synchronize an ArrayList in Java?

      59) Difference between set and list 

      60) Difference between HashMap and concurrentHashMap

      61) Difference between Treeset and HashSet

      62) Difference between HashMap and LinkedHashMap

      63) What is blocking queue?

      64) Difference between iterator listiterator

      65) Difference between failsafe and failfast


      No comments:

      Post a Comment