Showing posts with label Core Java Interview Questions with Answers. Show all posts
Showing posts with label Core Java Interview Questions with Answers. Show all posts

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 variables. The 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


      Saturday, 30 September 2023

      Difference Between PermGen (Permanent Generation) and Metaspace in Java

              In this post, we will discuss the differences between PermGen (Permanent Generation) and Metaspace in Java.

      Before Java 8, class metadata was stored in the PermGen (Permanent Generation) memory space. If the allocated PermGen space was exhausted, the JVM threw an OutOfMemoryError. By default, the PermGen size was limited, and if required, it could be increased using JVM options such as -XX:MaxPermSize.

      Java 8 removed PermGen and introduced Metaspace to address these limitations. Unlike PermGen, Metaspace stores class metadata in native memory rather than in the JVM heap. By default, Metaspace automatically expands as needed (subject to the available native memory), eliminating the need to manually increase its size in most cases. If required, its maximum size can still be limited using the -XX:MaxMetaspaceSize JVM option.

      PermGen and Metaspace difference

      Thank you for visiting the blog.

      Wednesday, 27 September 2023

      Difference Between equals() Method and == Operator in Java

           In this post, we will discuss one of the most common Java interview questions: the difference between the equals() method and the == operator. We will also explore practical examples to understand when and how each should be used.

      equals and == operator in java

      The equals() method compares the contents (or logical equality) of two objects, whereas the == operator compares their object references to determine whether both references point to the same object in memory.

      Let's look at a few examples to understand the difference between the equals() method and the == operator.

      • Created two string objects using new operator and applied equals and == operator to check the equality.
      public class DemoClass {
      
           public static void main(String[] args) {
      
      	  String s1 = new String("A");
      	  String s2 = new String("A");
      
      	  if (s1.equals(s2)) {
      		System.out.println("s1 equals s2 are equal");
      	  } else {
      		System.out.println("s1 equals s2 are not equal");
      	  }
      
      	  if (s1 == s2) {
      	       System.out.println("s1 == s2 are equal");
      	  } else {
      	       System.out.println("s1 == s2 are not equal");
      	  }
      
            }
      }
      

      Output:- 
      s1 equals s2 are equal
      s1 == s2 are not equal
      

      Used new operator to create String objects and those objects will store in heap memory of JVM and will create two different objects in the heap even the contents are same. So == operator result will return false.
      • Created two string objects using literal and applied equals and == operator to check the equality.
      public class DemoClass {
      
           public static void main(String[] args) {
      
      	  String s1 = "A";
      	  String s2 = "A";
      
      	  if (s1.equals(s2)) {
      		System.out.println("s1 equals s2 are equal");
      	  } else {
      		System.out.println("s1 equals s2 are not equal");
      	  }
      
      	  if (s1 == s2) {
      	       System.out.println("s1 == s2 are equal");
      	  } else {
      	       System.out.println("s1 == s2 are not equal");
      	  }
      
            }
      }
      

      Output:-

      s1 equals s2 are equal
      s1 == s2 are equal
      

      Thank you for visiting blog.

      Thursday, 7 September 2023

      Sort a List in Ascending and Descending Order Using the Java 8 Stream API

              In one of my previous posts, I covered several Java 8 Stream API coding questions and answers. In this post, we will discuss one of the most commonly asked coding interview questions: how to sort a list in ascending and descending order using the Java 8 Stream API.

      1) Sort a List of Strings in Ascending Order Using the Java 8 Stream API

      import java.util.Arrays;
      import java.util.List;
      
      public class SortExample {
      
          public static void main(String[] args) {
      
      	 List<String> listOfStrings = Arrays.asList("A", "E", "B", "C");
      
               listOfStrings.stream().sorted().forEach(s -> System.out.println(s));
          }
      
      }
      

      Output:- A
                    B
                    C
                    E

      2) Sort a List of Strings in Descending Order Using the Java 8 Stream API

      import java.util.Arrays;
      import java.util.Comparator;
      import java.util.List;
      
      public class SortExample {
      
           public static void main(String[] args) {
      
      	  List<String> listOfStrings = Arrays.asList("A", "E", "B", "C");
      
                listOfStrings.stream().sorted(Comparator.reverseOrder())
                                                    .forEach(s -> System.out.println(s));
           }
      
      }
      

      Output:-   E
                      C
                      B
                      A

      3) Sort a List of Custom Java Objects (Employee Class) in Ascending or Descending Order Using the Java 8 Stream API

      Employee.java,
      public class Employee {
      	
      	private Long id;
      	private String firstName;
      	private String lastName;
      	private String address;
            
              //constructor, setter and getter
             // and toString metghod
      }
      

      SortExample.java,
      package com.main;
      
      import java.util.ArrayList;
      import java.util.List;
      
      public class SortExample {
      
           public static void main(String[] args) {
      		
      	 Employee e1 = new Employee(1L, "Anil", "Nivargi", "XYZ");
      	 Employee e2 = new Employee(2L, "Mahesh", "Nivargi", "XYZ");
      
      	 List<Employee> employeeList = new ArrayList<>();
      	 employeeList.add(e1);
      	 employeeList.add(e2);
      		
      	  System.out.println("Sort a list in ascending order using firstName -");
      		
      	  //sort a list in ascending order using firstName
      	  employeeList.stream().sorted((s1,s2) -> 
                              s1.getFirstName().compareTo(s2.getFirstName())).forEach(
                                       s -> System.out.println(s));
      		
      	  System.out.println("Sort a list in descending order using firstName -");
      		
      	    //sort a list in descending order using firstName
      	  employeeList.stream().sorted((s1,s2) -> 
                              s2.getFirstName().compareTo(s1.getFirstName())).forEach(
                                       s -> System.out.println(s));
      
           }
      
      }
      

      Output:- 
      Sort a list in ascending order using firstName -
      Employee [id=1, firstName=Anil, lastName=Nivargi, address=XYZ]
      Employee [id=2, firstName=Mahesh, lastName=Nivargi, address=XYZ]
      Sort a list in descending order using firstName -
      Employee [id=2, firstName=Mahesh, lastName=Nivargi, address=XYZ]
      Employee [id=1, firstName=Anil, lastName=Nivargi, address=XYZ]
      

      Thank you reading the blog post.

      Reference Posts:-

      Wednesday, 16 August 2023

      Java 8 Optional Class with Examples

               Java 8 introduced a new class called Optional, which helps handle NullPointerException without requiring explicit null checks. (Refer to: Java 8 Features.) It provides several utility methods that make the code more readable, maintainable, and cleaner.

      When a value is null, you can use methods such as orElse() to provide a default value or execute alternative logic.

      Below are some of the commonly used methods available in the Optional class:

      Java 8 optional class methods

      The Optional.ofNullable() --- > method returns a Non-empty Optional if a value present in the given object. Otherwise returns an empty Optional. 

      Optional.empty() -- > method is useful to create an empty Optional object.

      Optional.of(value) --> creates an Optional object using value. 

      Optional.ifPresent -- > If optional variable value is present, invoke the specified consumer with the value, otherwise, do nothing.

      orElse --> If optional variable value is null then invokes orElse method.

       orElseGet --> If optional variable value is null then invokes orElse method and return the result of that invocation.

       orElseThrow --> If optional variable value is null then invokes orElseThrow method and throws the exception provided in the method.

       get -- > method returns the value from the optional.

       isPresent - if optional variable value is present/exist then return true else it's false.


      Optional Class Code Example - 

      import java.util.Optional;
      
      public class OptionalClassUsages {
      	
      	public static void main(String[] args) {
      		
      		//ofNullable, orElse, orElseGet and orElseThrow method example
      		String str = "Optional with ofNullable method usage";
      		System.out.println(Optional.ofNullable(str).orElse("null logic"));
      		
      		str = null;
      		System.out.println(Optional.ofNullable(str).orElse("null logic"));
      		System.out.println(Optional.ofNullable(str).orElseGet(() -> "orElseGet method"));
      		
      		try {
      			Optional.ofNullable(str).orElseThrow(() -> {
      				return new Exception("orElseThrow Exception");
      			});
      		} catch (Exception e) {
      			e.printStackTrace();
      		}
      		
      		//optional of, ifPresent, filter usages
      		Optional<String> optional = Optional.of("ab");
      		optional.ifPresent(s-> System.out.println(s));
      		optional.filter(s->s.equals("ab"))
      				.ifPresent(s-> System.out.println("ifPresent method usage"));
      		
      		//isPresent and get method usage example
      		System.out.println(optional.isPresent());
      		System.out.println(optional.get());	
      	}
      }
      

      Output:- 

      Optional with ofNullable method usage
      null logic
      orElseGet method
      java.lang.Exception: orElseThrow Exception
      	at com.main.OptionalClassUsages.lambda$1(OptionalClassUsages.java:19)
      	at java.util.Optional.orElseThrow(Optional.java:290)
      	at com.main.OptionalClassUsages.main(OptionalClassUsages.java:18)
      ab
      ifPresent method usage
      true
      ab
      


      Thank you for visiting the blog.

      Previous                                                    Home                                                                            Next

      Reference posts: