Core java interview questions and answers for 3-5 years experience

 Part 1

Core java interview questions and answers for 3-5 years experience covered in this post:



    Core java interview questions and answers for 3-5 years experience

        Will the code compile If the parent class method is not throwing any exception but the child class method is throwing an unchecked exception or Runtime Exception?

    -  Yes. Code will compile if parent class method is not throwing any exception but child class method throws runtime exception or unchecked exception.

    package simplifiedjava.crackedInterview; 

    public class OverrideOverloadedMethodDemo { 

          public static void main(String[] args) {       

                Parent p = new Parent();

                Child c = new Child();       

                c.check("Brother");

          }

    } 

    package simplifiedjava.crackedInterview; 

    import java.io.IOException; 

    public class Parent {           

          public void check(String relation){

                System.out.println("Parent Class check() method.");

          }    

    } 

    package simplifiedjava.crackedInterview; 

    public class Child extends Parent{ 

          public void check(String relation)throws NullPointerException{

                System.out.println("Child Class check() method.");

          }    

    }

    Output : Child Class check() method.


        Can we have a constructor in abstract class? If we can't instantiate abstract class then why there is a need for a constructor in abstract class?

    -          Yes. We can declare a constructor inside the abstract class.

    -  Absolutely right we cannot instantiate abstract class but when its Implementation class or child class instantiate that time abstract class constructor will be called.   


     

    Click here to Purchase on AmazonClick here to Purchase on Amazon

    Click here to Purchase on Amazon

    Note: Please click on Image to Purchase the books from Amazon.in

        Can we declare a class inside a class?

    -          Yes we can declare a class inside a class.

    -          For a demonstration please refer to the below example.

    package simplifiedjava.crackedInterview; 

    public class ClassInsideClass { 

          class Inner{

                public void greetings() {

                      System.out.println("Hello From Inner Class");

                }

          }         

          public static void main(String[] args) {

                ClassInsideClass.Inner inner = new ClassInsideClass().new Inner();

                inner.greetings();

          }

    }

    Output: Hello From Inner Class


        When the constructor will be executed once you declare the constructor inside the enum?

    -          When constant enum values are passed to the constructor.


        Can we create a custom exception class? If yes then what are the steps to create a custom exception class?

    -          Yes we can create a custom exception class.

    -          Please follow the following steps to create your custom exception.

    1.   Create one Custom class and extends the Exception class.

    2. Create one String type local variable and assign your custom message to that variable.

    3. Pass the custom message in the Custom class constructor while instantiating the custom class.

    4.   Override toString() method to print the custom message.

    5.   We can simply throw a custom exception in any method and pass a custom message while creating a custom object.

    -          Please refer to the below example to create a custom exception. 

    package simplifiedjava.crackedInterview; 

    public class CustomException extends Exception { 

          private String message;     

          public CustomException(String message) {

                this.message = message;

          } 

          public String toString() {

                return message;

          }     

          public static void main(String[] args) {       

                try {

                       if(args.length >= -1) {

                          throw new CustomException("No Argument Exception");

                       }                

                }catch(CustomException e) {

                      System.out.println(e);

                }

          }

    }

    Output: No Argument Exception

     

        What are the rules we must follow while throwing an exception in an overridden method?

    -   If the superclass method does not declare an exception, the subclass’s overridden method cannot declare the checked exception.

    -   If the superclass method does not declare an exception, the subclass’s overridden method can declare an unchecked or runtime exception.

    -     If the superclass method declares an exception, the subclass’s overridden method can declare the same exception or child class of that exception but cannot declare the parent class of that exception.

    -          Please refer to the below examples for more clarity.

    Parent Class Method

    Child Class Method

    Status

    Calculate()

    Calculate() throws IOException

    Not Allowed. Reason: If the parent class method doesn’t throw any exception then the child class method should not through any checked exception. You can throw unchecked exception.  

    Calculate()

    Calculate() throws NullPointerException

    Allowed.

    Calculate() throws IOException

    Calculate()

    Allowed.

    Calculate() throws NullPointerException

    Calculate()

    Allowed.

    Calculate() throws ArithmeticException

    Calculate()throws Exception

    Not Allowed. Reason: Child class method cannot throw parent exception of Parent class.

    Calculate() throws Exception

    Calculate() throws Exception

    Allowed.


        What is Synchronization?

            -    Synchronization is a technique used in a multi-threading environment to control the access of shared resources on multiple threads.

    -    We can achieve thread-safety in multiple ways. Please refer to the below 8 options. 

    1.       Synchronized Methods.

    2.       Synchronized Blocks.

    3.       Synchronized Collection. (Using Collections Utility Class).

    4.       Concurrent Collection.

    5.       Immutable Implementation.

    6.       Thread-Local Field.

    7.       Volatile Field.

    8.       Stateless Implementation.

              Explanation in details.

    1.       Synchronized Methods:

    Ø  The method can be declared with a synchronized keyword.

    Ø  Once you declared the method with a synchronized keyword then only one thread can execute shared resources at a time. Other threads will be blocked until the first thread finishes its execution.

    Ø  synchronized method depends on either “Intrinsic Lock” or “Monitor Lock”.

    Ø  When the thread calls the synchronized method, it acquires the intrinsic lock.

    Ø  The Monitor is just a reference to the role that the lock performs on the associated objects.

    Ø  Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    public class SynchronizedMethodDemo { 

          int counter = 0;

          public synchronized void getCounter() {

                counter =+ 1; // Similar to counter = counter +1;

                System.out.println("Counter is "+ counter);

          }     

          public static void main(String[] args) {       

                new SynchronizedMethodDemo().getCounter();

          }

    }

     

    2.       Synchronized Block:

    Ø  A synchronized block can be called a statement block.

    Ø  Method synchronization is highly expensive so to avoid this situation we can perform synchronization at the statement level which is less expensive from a performance perspective.

    Ø  A synchronized block generally declares inside a method.

    Ø  Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    import java.util.ArrayList;

    import java.util.Arrays;

    import java.util.Collection;

    import java.util.Collections; 

    public class SynchronizedBlockDemo {     

          int counter = 0;

          public void getCounter() {   

                synchronized(this) {

                      counter =+ 1; // Similar to counter = counter +1;

                }          

                System.out.println("Counter is "+ counter);

          }     

          public static void main(String[] args) {       

                new SynchronizedMethodDemo().getCounter();           

          }

    }

     

    3.               Synchronized Collection:

    Ø  We can create a thread-safe collection by using utility methods of the Collections utility class.

    Ø  Once you create the thread-safe collection object then only one thread can execute at a time. While other threads will be blocked until the collection object is unblocked by the first thread.

    Ø  Please refer to the below example. 

    package simplifiedjava.crackedInterview; 

    import java.util.Arrays;

    import java.util.Collections;

    import java.util.List; 

    public class SynchronizedCollectionDemo { 

          public static void main(String[] args) {

                Thread t1 = new Thread(new MyClass1());

                Thread t2 = new Thread(new MyClass2());

                t1.start();

                t2.start();

          }

    } 

    class MyClass1 implements Runnable{ 

          @Override

          public void run() {          

                List<Integer> list1 = Arrays.asList(10,20,30,40,50);

                List<Integer> synchronizedList1 = Collections.synchronizedList(list1);     

                for(Integer i : list1) {

                      System.out.println(i);

                }

          }    

    } 

    class MyClass2 implements Runnable{ 

          @Override

          public void run() {

                List<Integer> list2 = Arrays.asList(60,70,80,90,100);

                List<Integer> synchronizedList2 = Collections.synchronizedList(list2);

                for(Integer i : list2) {

                      System.out.println(i);

                }

          }    

    }

     

    4.       Concurrent Collection:

    Ø  Java provides java.util.concurrent package for thread safety.

    Ø  Java.util.concurrent package has some thread safe classes like ConcurrentHashMap, CopyOnWriteArrayList, CopyOnWriteArraySet.

    Ø  Please refer to the below example.               

    package simplifiedjava.crackedInterview; 

    import java.util.Map;

    import java.util.concurrent.ConcurrentHashMap; 

    public class ConcurrentCollectionDemo { 

          public static void main(String[] args) {

               Map<String,Integer> concurrentMap = new ConcurrentHashMap<>();

                concurrentMap.put("one", 1);

                concurrentMap.put("two", 2);

                concurrentMap.put("three", 3);

          }

    }

     

    5.       Immutable Implementation:

    Ø  Immutable means its internal states can’t be changed once it is created.

    Ø  If we need to share the state between different threads, we can create thread-safe classes by making them immutable classes.

    Ø  If the state will be fixed forever then immutable objects can be used thread-safely.

    Ø  Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    public final class ImmutableClassDemo { 

          private final String empCode="E001"; 

          public String getEmpCode() {

                return empCode;

          }

    }

     

    6.       Thread-Local Field:

    Ø  We can easily create classes whose fields are thread-local by simply defining private fields in the Thread class.

    Ø  We can create thread-safe classes that don’t share states between threads by making their fields thread-local.

    Ø  Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    import java.util.Arrays;

    import java.util.List; 

    public class ThreadLocalDemo1 extends Thread { 

          private final List<Integer> numList = Arrays.asList(10,20,30,40,50);     

          @Override

          public void run() {

                for(int n : numList) {

                      System.out.println(n);

                }

          }

    } 

    package simplifiedjava.crackedInterview; 

    import java.util.Arrays;

    import java.util.List; 

    public class ThreadLocalDemo2 extends Thread{ 

          private final List<String> wordList = Arrays.asList("Hi","Hello","GM","GA","GN");     

          @Override

          public void run() {

                for(String str : wordList) {

                      System.out.println(str);

                }

          }

    }

     

    7.       Volatile Field:

    Ø  If you declare a variable as volatile, JVM will store those variables on main memory.

    Ø  We can make sure every time JVM reads the value from the main memory.

    Ø  Every time JVM writes the value it will write on the main memory.

    Ø  Volatile keyword ensures that variable will be visible to all thread and thread can read the value from main memory.

    Ø  Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    public class ThreadLocalVariableDemo { 

          private volatile int empId;

          private String name;        

          public static void main(String[] args) {           

          }

    }

     

    8.       Stateless Implementation:

    Ø  Stateless implementation is the simplest way to achieve thread safety.

    Ø  Stateless implementation is nothing but function implementation which produces the same result every time. There is no change to change the state by any thread.

    Ø  Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    public class StateLessImplementationDemo { 

          public static void main(String[] args) {           

                int i = 10;

                int square = i * i ;

                System.out.println(square);

          }

    }


        What is the purpose of join() method?

    -    Thread class provides the join() method which allows one thread to wait until another thread completes its execution.

    -    If a thread wants to wait until completing some other thread then we should go for the  join(); method.

    -     In above example, Thread1.join(Thread2) and Thread2.join(Thread3) in the above case Thread3 will execute first and then thread2 and then thread1.


        What are the methods used for Serialization and Deserialization?

    -     For Serialization we have to use writeObject() method which belongs to ObjectOutputStream.

    -  For Deserialization we have to use readObject() method which belongs to ObjectInputStream.


        Can we declare outer class as a Default or Strictfp or Final?

    -    Yes, all three keywords are applicable to the outer class.



    • Java interview questions and answers all MNC - Click here
    • Basic core java interview questions and answers for freshers - Click here
    • Core java interview questions for 3 years experience - Click here
    • Core java interview questions and answers for 3-5 years exp - Click here
    • Core java interview questions and Answers for 5 - 7 Years exp - Click here
    • Basic Java Interview Questions and Answers - Click here
    • Java interview questions and answers on oops - Click here
    • Java interview questions and answers on Strings - Click here
    • Java interview questions on exception handling - Click here
    • Interview questions on multithreading in java for experienced - Click here
    • Interview questions on serialization in java for experienced - Click here

    • Interview questions on inner class in java for experienced - Click here
    • Interview questions on Collections in java for experienced - Click here



    Upcoming questions in next post:

    11. Can constructor have return type.

    12. What's the difference between stackoverflowerror and outofmemoryerror in java

    13. What happend when exception occured in thread.

    14. What are the methods used for Externalization.

    15. What is method local inner class.

    16. How many .class files will be created if there are 2 inner classes inside outer class.

    17. What is the difference between Collection and Collections.

    18. What is Circular Queue.

    19. What is Dictionary class? 

    20. Can you declare public static void main() method inside functional interface.


    Previous Post                                                                    Next Post



    Thank you techies for visiting this blog. I hope you enjoyed this blog and got more technical knowledge. I have tried to cover all types of questions and provided examples tested on eclipse as much as I can. Guys, please don’t just mug up the questions and answers. Try to clear your concepts with examples. Try to write a code on eclipse once you read the concepts. It will help you to memorize the concepts for a very long time. Simultaneously you will be prepared for interview programs as well. It will help you to survive in the IT sector for a long time. It may be easy to crack an interview but it's really tough to survive in the IT industry with inadequate knowledge and skills. 

    I have collected all the questions from actual interviews attended by my friends, colleagues, college mate and classmate. I have covered frequently asked questions as well as challenging questions. I have included many programs to understand the concept thoroughly. I will try to explain the concept with the help of a real-time program in eclipse. 

    You can share more questions which are not covered in this blog or post. Always welcome your suggestions and queries. I will definitely try to resolve it. 

    Please comment your queries and new set of questions under the comment sections. I will create a new post for those questions. 

    My total experience is 10. Initially I had worked on some support projects and then I moved to java projects. I had worked with many multi-national companies like R-Systems, Tata Consultancy Services, Cybage Softwares.  Fortunately, TCS and Cybage has given me an opportunity to take interviews for experienced candidates. I have conducted more than 1000 interviews by now.

    Mock sessions will be conducted for minimal charges. I will guide you personally on how to crack interviews. All sessions will be online sessions only. My interview book will be provided free of cost if you enroll for personal training. Once you have done practice then I assured you will definitely crack almost all java interviews. 

    I have published my book named with "All MNC Java Interview" which is available on amazon. You can go through it or you can directly contact to me if you are interested to read the book. I will give you special discount. I have covered near about 550 questions and answers with program tested on eclipse and necessary diagram. 

    I have covered interview questions asked in all reputed MNC like TCS, Infosys, Capgemini, Tech Mahindra, Cognizant, City Bank, Barclays, Amdocs, Mindtree etc. My purpose behind this book is, help you to get a job in your dream company. I can understand this is a struggling period for job seekers and freshers. Everybody must have gone from this phase. so never give up. Keep upgrading yourself. I am sure you will get a job in your dream company. All the best!!! 

    Please reach out to me for personal training for interview preparation. 

    You can reach out to me at mncjavainterview@gmail.com.

     


    Post a Comment

    0 Comments