Saturday, November 27, 2021

Top 30 Java8 Interview Questions and Answers

************************************
Top 30 Java8 Interview Questions and Answers
************************************


1)  What are new features which got introduced in Java 8?
There are lots of new features which were added in Java 8. Here is the list of important features:
  1. Lambda Expression
  2. Stream API
  3. Default methods in the interface
  4. Functional Interface
  5. Optional
  6. Method reference
  7. Date API
  8. Nashorn, JavaScript Engine

2) What are main advantages of using Java 8?
  • More compact code
  • Less boiler plate code
  • More readable and reusable code
  • More testable code
  • Parallel operations


3) What is lambda expression?
Lambda expression is anonymous function which have set of parameters and a lambda (->) and a function body .You can call it function without name.

Structure of Lambda Expressions
(Argument List) ->{expression;} or
(Argument List) ->{statements;}
 
 Let see a simple example of thread execution:

public class ThreadSample {
 
 public static void main(String[] args) {
 
  // old way
  new Thread(new Runnable() {
 
   @Override
   public void run() {
    System.out.println("Thread is started");
   }
  }).start();
 
  // using lambda Expression
  new Thread(()->System.out.println("Thread is started")).start();
 }
}
 


4) Can you explain the syntax of Lambda expression?
So we can divide structure of Lambda expression to three parts:

1. Argument list or parameters
Lambda expression can have zero or more arguments.
()->{System.out.println("Hello")}; //Without argument, will print hello 
(int a)->{System.out.println(a)} //; One argument, will print value of a
(int a,int b)-> {a+b};//two argument, will return sum of these two integers
 
You can choose to not declare type of arguments as it can be inferred from context.
(a,b)->{a+b};//two argument, will return sum of these two numbers
 
you can not declare one argument’s type and do not declare type for other argument. 
(int a,b)->{a+b};//Compilation error
 
When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses
a->{System.out.println(a)}; // Will print value of number a
 
2. Array token (->)
3. Body -  Body can have expression or statements.
If there is only one statement in body,curly brace is not needed and return type of the anonymous function is same as of  body expression
If there are more than one statements, then it should be in curly braces and return type of anonymous function is same as value return from code block, void if nothing is returned.


5) What are functional interfaces?
Functional interfaces are those interfaces which can have only one abstract method.It can have static method, default methods or can override Object’s class methods.
There are many functional interfaces already present in java such as Comparable, Runnable.
As we have only one method in Runnable, hence it is considered as functional interface.


6) How lambda expression and functional interfaces are related?
Lambda expressions can only be applied to abstract method of functional interface.
For example

Runnable has only one abstract method called run, so it can be used as below:
 
// Using lambda expression
Thread t1=new Thread(
()->System.out.println("In Run method")
);
 
Here we are using Thread constructor which takes Runnable as parameter. As you can see we did not specify any function name here, as Runnable has only one abstract method, java will implicitly create anonymous Runnable and execute run method.
It will be as good as below code.

Thread t1=new Thread(new Runnable() { 
   @Override
   public void run() {
    System.out.println("In Run method");
   }
  });
 

7) Can you create your own functional interface?
Yes, you can create your own functional interface. Java can implicitly identify functional interface but you can also annotate it with @FunctionalInterface.
Example:
Create interface named "Printable" as below

package org.arpit.java2blog;
 
public interface Printable {
 
    void print();
    default void printColor()
    {
        System.out.println("Printing Color copy");
    }
}
 
Create main class named "FunctionalIntefaceMain"

package org.arpit.java2blog.constructor;
 
public class FunctionalIntefaceMain {
 
    public static void main(String[] args)
    {
        FunctionalIntefaceMain pMain=new FunctionalIntefaceMain();
        pMain.printForm(() -> System.out.println("Printing form"));
    }
 
    public void printForm(Printable p)
    {
        p.print();
    }
}
 
When you run above program, you will get below output:

Printing form

As you can see, since Printable has only one abstract method called print(), we were able to call it using lambda expression.


8) What is method reference in java 8?
Method reference is used refer method of functional interface. It is nothing but compact way of lambda expression.You can simply replace lambda expression with method reference.
Syntax:
class::methodname


9) What is Optional? Why and how can you use it?
Java 8 has introduced new class Called Optional. This class is basically introduced to avoid NullPointerException in java.
Optional class encapsulates optional value which is either present or not.
It is a wrapper around object and can be use to avoid NullPointerExceptions.

Let’s take a simple example
You have written below function to get first non repeated character in String.

public static Character getNonRepeatedCharacter(String str) {
    Map<Character, Integer> countCharacters = new LinkedHashMap<Character, Integer>();
          for (int i = 0; i < str.length() - 1; i++) {
           Character c = str.charAt(i);
           if (!countCharacters.containsKey(c)) {
            countCharacters.put(c, 1);
           } else {
            countCharacters.put(c, countCharacters.get(c) + 1);
           }
          }
          // As LinkedHashMap maintains insertion order, first character with
          // count 1 should return first non repeated character
          for (Entry<Character, Integer> e : countCharacters.entrySet()) {
           if (e.getValue() == 1)
            return e.getKey();
          }
          return null;
         }
 
You call above method as below.

  Character c=getNonRepeatedCharacter("SASAS");
    System.out.println("Non repeated character is :"+c.toString());
 
Do you see the problem, there is no non repeating character for getNonRepeatedCharacter("SASAS") hence it will return null and we are calling c.toString(), so it will obviously throw NullPointerException.
You can use Optional to avoid this NullPointerException.
Let’s change the method to return Optional object rather than String.

public static Optional<Character> getNonRepeatedCharacterOpt(String str) {
          Map<Character, Integer> countCharacters = new LinkedHashMap<Character, Integer>();
          for (int i = 0; i < str.length(); i++) {
           Character c = str.charAt(i);
           if (!countCharacters.containsKey(c)) {
            countCharacters.put(c, 1);
           } else {
            countCharacters.put(c, countCharacters.get(c) + 1);
           }
          }
          // As LinkedHashMap maintains insertion order, first character with
          // count 1 should return first non repeated character
          for (Entry<Character, Integer> e : countCharacters.entrySet()) {
           if (e.getValue() == 1)
            return Optional.of(e.getKey());
          }
          return Optional.ofNullable(null);
         }
 
When above method returned Optional, you are already aware that it can return null value too.
You can call Optional’s isPresent method to check if there is any value wrapped in Optional.

Optional<Character> opCh=getNonRepeatedCharacterOpt("SASAS");
        if(opCh.isPresent())
            System.out.println("Non repeated character is :"+opCh.toString());
        else
        {
            System.out.println("No non repeated character found in String");
        } 
If there is no value present in Optional, it will simply print "No non repeated character found in String".


10) What are defaults methods?
Default method are those methods in interface which have body and use default keywords. Default method are introduced in Java 8 mainly because of backward compatibility.

☀ Until 1.7 version onwards inside interface we can take only public abstract methods and public static final variables (every method present inside interface is always public and abstract whether we are declaring or not). 
☀ Every variable declared inside interface is always public static final whether we are declaring or not. ☀ But from 1.8 version onwards in addition to these, we can declare default concrete methods also inside interface, which are also known as defender methods. 
☀ We can declare default method with the keyword “default” as follows
☀ Interface default methods are by-default available to all implementation classes. Based on requirement implementation class can use these default methods directly or can override.
☀ The main advantage of default methods is without effecting implementation classes we can add new functionality to the interface (backward compatibility)




What is static method?
☀ From 1.8 version onwards in addition to default methods we can write static methods also inside interface to define utility functions. 
☀ Interface static methods by-default not available to the implementation classes hence by using implementation class reference we can’t call interface static
 ☀ methods. We should call interface static methods by using interface name.

☀ As interface static methods by default not available to the implementation class, overriding concept is not applicable.
☀ Based on our requirement we can define exactly same method in the implementation class, it’s valid but not overriding
It’s valid but not overriding




11) What is the difference between Predicate and Function?
Both are functional interfaces.
Predicate<T> is single argument function and either it returns true or false.This can be used as the assignment target for a lambda expression or method reference.
Function<T,R> is also single argument function but it returns an Object.Here T denotes type of input to the function and R denotes type of Result.
This can also be used as the assignment target for a lambda expression or method reference.


12) Are you aware of Date and Time API introduced in Java 8? What the issues with Old Date and time API?
Issues with old Date and TIme API:
Thread Safety: You might be already aware that java.util.Date is mutable and not thread safe. Even java.text.SimpleDateFormat is also not Thread-Safe. New Java 8 date and time APIs are thread safe.
Performance: Java 8 ‘s new APIs are better in performance than old Java APIs.
More Readable: Old APIs such Calendar and Date are poorly designed and hard to understand. Java 8 Date and Time APIs are easy to understand and comply with ISO standards.


13) Can you provide some APIs of Java 8 Date and TIme?
LocalDate, LocalTime, and LocalDateTime are the Core API classes for Java 8. As the name suggests, these classes are local to context of observer. It denotes current date and time in context of Observer.


14) How will you get current date and time using Java 8 Date and TIme API?
You can simply use now method of LocalDate to get today’s date.
 
LocalDate currentDate = LocalDate.now();
System.out.println(currentDate); 

It will give you output in below format: 2017-09-09
You can use now method of LocalTime to get current time.

LocalTime currentTime = LocalTime.now();
System.out.println(currentTime);
 
It will give you output in below format: 23:17:51.817


15) Do we have PermGen in Java 8? Are you aware of MetaSpace?
Until Java 7, JVM used an area called PermGen to store classes. It got removed in Java 8 and replaced by MetaSpace.
Major advantage of MetaSpace over permgen:
PermGen was fixed in term of mazimum size and can not grow dynamically but Metaspace can grow dynamically and do not have any size constraint.
Next 7 questions will be based on below class.
package org.arpit.java2blog;
 
public class Employee {
    private String name;
    private int age;
 
    public Employee(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
        public String toString()
    {
        return "Employee Name: "+name+" age: "+age;
    }
}
 

16) Given a list of employees, you need to filter all the employee whose age is greater than 20 and print the employee names.(Java 8 APIs only)
You can simply do it using below statement.
 
List<String> employeeFilteredList = employeeList.stream()
                  .filter(e->e.getAge()>20)
                  .map(Employee::getName)
                  .collect(Collectors.toList());
 
Complete main program for above logic.
 
package org.arpit.java2blog;
 
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
 
public class MaximumUsingStreamMain {
    public static void main(String args[])
    {
        List<Employee> employeeList = createEmployeeList();
        List<String> employeeFilteredList = employeeList.stream()
                  .filter(e->e.getAge()>20)
                  .map(Employee::getName)
                  .collect(Collectors.toList());
 
        employeeFilteredList.forEach((name)-> System.out.println(name));
 
    }
 
    public static List<Employee> createEmployeeList()
    {
        List<Employee> employeeList=new ArrayList<>();
 
        Employee e1=new Employee("John",21);
        Employee e2=new Employee("Martin",19);
        Employee e3=new Employee("Mary",31);
        Employee e4=new Employee("Stephan",18);
        Employee e5=new Employee("Gary",26);
 
        employeeList.add(e1);
        employeeList.add(e2);
        employeeList.add(e3);
        employeeList.add(e4);
        employeeList.add(e5);
 
        return employeeList;
    }
}
 

17) Given the list of employees, count number of employees with age 25?
You can use combination of filter and count to find this.
 
List<Employee> employeeList = createEmployeeList();
long count = employeeList.stream()
.filter(e->e.getAge()>25)
.count();
System.out.println("Number of employees with age 25 are : "+count);
 

18) Given the list of employees, find the employee with name “Mary”.
It is again very simple logic, change the main function in above class as following.

List<Employee> employeeList = createEmployeeList();
        Optional<Employee> e1 = employeeList.stream()
                  .filter(e->e.getName().equalsIgnoreCase("Mary")).findAny();
 
        if(e1.isPresent())
            System.out.println(e1.get());
 

19)Given a list of employee, find maximum age of employee?
It is again very simple logic, change the main function in above class as following.

List<Employee> employeeList = createEmployeeList();
        OptionalInt max = employeeList.stream().
                          mapToInt(Employee::getAge).max();
 
        if(max.isPresent())
            System.out.println("Maximum age of Employee: "+max.getAsInt());
 

20) Given a list of employees, sort all the employee on the basis of age? Use java 8 APIs only
You can simply use sort method of list to sort the list of employees.

  List<Employee> employeeList = createEmployeeList();
        employeeList.sort((e1,e2)->e1.getAge()-e2.getAge());
        employeeList.forEach(System.out::println);
 

21) Join the all employee names with “,” using java 8?

  List<Employee> employeeList = createEmployeeList();
        List<String> employeeNames = employeeList
                                     .stream()
                                     .map(Employee::getName)
                                     .collect(Collectors.toList());
        String employeeNamesStr = String.join(",", employeeNames);
        System.out.println("Employees are: "+employeeNamesStr);
 
Output: Employees are: John,Martin,Mary,Stephan,Gary


22) Given the list of employee, group them by employee name?
You can use Collections.groupBy() to group list of employees by employee name.

package org.arpit.java2blog; 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
public class MaximumUsingStreamMain {
    public static void main(String args[])
    {
        List<Employee> employeeList = createEmployeeList();
        Map<String, List<Employee>> map = employeeList.stream()
                                              .collect(Collectors.groupingBy(Employee::getName));
        map.forEach((name,employeeListTemp)->System.out.println("Name: "+name+" ==>"+employeeListTemp));
    }
 
    public static List<Employee> createEmployeeList()
    {
        List<Employee> employeeList=new ArrayList<>();
 
        Employee e1=new Employee("John",21);
        Employee e2=new Employee("Martin",19);
        Employee e3=new Employee("Mary",31);
        Employee e4=new Employee("Mary",18);
        Employee e5=new Employee("John",26);
 
        employeeList.add(e1);
        employeeList.add(e2);
        employeeList.add(e3);
        employeeList.add(e4);
        employeeList.add(e5);
 
        return employeeList;
    }
}
 
Output: 
Name: John ==>[Employee Name: John age: 21, Employee Name: John age: 26] Name: Martin ==>[Employee Name: Martin age: 19] Name: Mary ==>[Employee Name: Mary age: 31, Employee Name: Mary age: 18]


23) Difference between Intermediate and terminal operations in Stream?
Java 8 Stream supports both intermediate and terminal operation.
Intermediate operations are lazy in nature and do not get executed immediately. Terminal operations are not lazy, they are executed as soon as encountered. Intermediate operation is memorized and is called when terminal operation is called.
All Intermediate operations return stream as it just transforms stream into another and terminal operation don’t.
Example of Intermediate operations are:
filter(Predicate)
map(Function)
flatmap(Function)
sorted(Comparator)
distinct()
limit(long n)
skip(long n)

Example of terminal operations are :
forEach
toArray
reduce
collect
min
max
count
anyMatch
allMatch
noneMatch
findFirst
findAny


24) Given the list of numbers, remove the duplicate elements from the list.
You can simply use stream and then collect it to set using Collections.toSet() method.

package org.arpit.java2blog; 
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
 
public class RemoveDuplicatesFromListMain {
    public static void main(String[] args)
    {
        Integer[] arr=new Integer[]{1,2,3,4,3,2,4,2};
        List<Integer> listWithDuplicates = Arrays.asList(arr);
 
        Set<Integer> setWithoutDups = listWithDuplicates.stream().collect(Collectors.toSet());
        setWithoutDups.forEach((i)->System.out.print(" "+i));
    }
}
 
You can use distinct as well to avoid duplicates as following.
change main method of above program as below.


Integer[] arr=new Integer[]{1,2,3,4,3,2,4,2};
        List<Integer> listWithDuplicates = Arrays.asList(arr);
List<Integer> listWithoutDups = listWithDuplicates.stream().distinct().collect(Collectors.toList());
        listWithoutDups.forEach((i)->System.out.print(" "+i));
 


25) Difference between Stream’s findFirst() and findAny()?
findFirst will always return the first element from the stream whereas findAny is allowed to choose any element from the stream.
findFirst has deterministic behavior whereas findAny is nondeterministic behavior.


26) Given a list of numbers, square them and filter the numbers which are greater 10000 and then find average of them.( Java 8 APIs only)
You can use the map function to square the number and then filter to avoid numbers which are less than 10000.We will use average as terminating function in this case.

package org.arpit.java2blog; 
import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;
 
public class RemoveDuplicatesFromListMain {
    public static void main(String[] args)
    {
        Integer[] arr=new Integer[]{100,24,13,44,114,200,40,112};
        List<Integer> list = Arrays.asList(arr);
        OptionalDouble average = list.stream()
                                 .mapToInt(n->n*n)
                                 .filter(n->n>10000)
                                 .average();
 
        if(average.isPresent())
            System.out.println(average.getAsDouble());
 
    }
}
 
output:
21846.666666666668


27) What is use of Optional in Java 8?
Java 8 optional can be used to avoid NullPointerException.You can read about the detailed tutorial.


28) What is predicate function interface?
Predicate is single argument function which returns true or false. It has test method which returns boolean.
When we are using filter in above example, we are actually passing Predicate functional interface to it.


29) What is consumer function interface?
Consumer is single argument functional interface which does not return any value.
When we are using foreach in above example, we are actually passing Consumer functional interface to it.


30) What is supplier function interface?
Supplier is function interface which does not take any parameter but returns the value using get method.

Thursday, November 25, 2021

Top Java Interview Question and Answers series - Part4

********************************************
Top Java Interview Question and Answers series - Part4
********************************************


***Java Interview questions on threads***


76) What are user defined exceptions?
To create customized error messages we use userdefined exceptions. We can create user defined exceptions as checked or unchecked exceptions. We can create user defined exceptions that extend Exception class or subclasses of checked exeptions so that userdefined exception becomes checked. Userdefined exceptions can extend RuntimeException to create userdefined unchecked exceptions.
Note : It is recommended to keep our customized exception class as unchecked,i.e we need to extend Runtime Exception class but not Excpetion class.


77) Can we rethrow the same exception from catch handler?
Yes we can rethrow the same exception from our catch handler. If we want to rethrow checked exception from a catch block we need to declare that exception.


78) Can we nested try statements in java?
Yes try statements can be nested. We can declare try statements inside the block of another try statement.


79) Explain the importance of throwable class and its methods?
Throwable class is the root class for Exceptions. All exceptions are derived from this throwable class. The two main subclasses of Throwable are Exception and Error. The three methods defined in throwable class
are :
1) void printStackTrace() : This prints the exception information in the following format : Name of the exception, description followed by stack trace.
2) getMessage(): This method prints only the description of Exception.
3) toString(): It prints the name and description of Exception.


80) Explain when ClassNotFoundException will be raised ?
When JVM tries to load a class by its string name, and couldn’t able to find the class classNotFoundException will be thrown. An example for this exception is when class name is misspelled and when we try to load the class by string name hence class cannot be found which raises ClassNotFoundException.


81) Explain when NoClassDefFoundError will be raised ?
This error is thrown when JVM tries to load the class but no definition for that class is found NoClassDefFoundError will occur. The class may exist at compile time but unable to find at runtime. This might be due to misspelled classname at command line, or classpath is not specified properly , or the class file with byte code is no longer available.


83) What is process ?
A process is a program in execution. Every process have their own memory space.Process are heavy weight and requires their own address space. One or more threads make a process.


84) What is thread in java?
Thread is separate path of execution in program. Threads are
1) Light weight
2) They share the same address space.
3) creating thread is simple when compared to process because creating thread requires less resources when compared to process
4) Threads exists in process. A process have atleast one thread.


85) Difference between process and thread?
Process Thread
1) Program in execution. Separate path of execution in program. One or more threads is called as process.
2) Processes are heavy weight Threads are light weight.
3) Processes require separate address space. Threads share same address space.
4) Interprocess communication is expensive. Interthread communication is less expensive compared to processes.
5) Context switching from one process to another is costly. Context switching between threads is low cost.


86) What is multitasking ?
Multitasking means performing more than one activity at a time on the computer. Example Using spreadsheet and using calculator at same time.


87) What are different types of multitasking?
There are two different types of multitasking :
1) Process based multitasking
2) Thread based multitasking
Process based multitasking : It allows to run two or more programs concurrently. In process based multitasking a process is the smallest part of code .
Example : Running Ms word and Ms powerpoint at a time.
Thread based multitasking : It allows to run parts of a program to run concurrently.
Example : Formatting the text and printing word document at same time . Java supports thread based multitasking and provides built in support for multithreading.


88) What are the benefits of multithreaded programming?
Multithreading enables to use idle time of cpu to another thread which results in faster execution of program. In single threaded environment each task has to be completed before proceeding to next task making cpu idle.


89) Explain thread in java?
1) Thread is independent path of execution with in a program.
2) A thread consists of three parts Virtual Cpu, Code and data.
3) At run time threads share code and data i.e they use same address space.
4) Every thread in java is an object of java.lang.Thread class.


90) List Java API that supports threads?
java.lang.Thread : This is one of the way to create a thread. By extending Thread class and overriding run() we can create thread in java.
java.lang.Runnable : Runnable is an interface in java. By implementing runnable interface and overriding run() we can create thread in java.
java.lang.Object : Object class is the super class for all the classes in java. In object class we have three
methods wait(), notify(), notifyAll() that supports threads. java.util.concurrent : This package has classes and interfaces that supports concurrent programming.
Ex : Executor interface, Future task class etc.


91) Explain about main thread in java?
Main thread is the first thread that starts immediately after a program is started Main thread is important because :
1) All the child threads spawn from main thread.
2) Main method is the last thread to finish execution. When JVM calls main method() it starts a new thread. Main() method is temporarily stopped while the new thread starts running.


92) In how many ways we can create threads in java?
We can create threads in java by any of the two ways :
1) By extending Thread class
2) By Implementing Runnable interface.


93) Explain creating threads by implementing Runnable class?
This is first and foremost way to create threads . By implementing runnable interface and implementing run() method we can create new thread.
Method signature : public void run() Run is the starting point for execution for another thread within our program.
Example :
public class MyClass implements Runnable {
@Override
public void run() {
// T
}
}


94) Explain creating threads by extending Thread class ?
We can create a thread by extending Thread class. The class which extends Thread class must override the run() method.
Example :
public class MyClass extends Thread {
@Override
public void run() {
24
// Starting point of Execution
}
}



95) Which is the best approach for creating thread ?
The best way for creating threads is to implement runnable interface. When we extend Thread class we can’t extend any other class. When we create thread by implementing runnable interface we can implement Runnable interface. In both ways we have to implement run() method.


96) Explain the importance of thread scheduler in java?
Thread scheduler is part of JVM use to determine which thread to run at this moment when there are multiple threads. Only threads in runnable state are choosen by scheduler.
Thread scheduler first allocates the processor time to the higher priority threads. To allocate microprocessor time in between the threads of the same priority, thread scheduler follows round robin
fasion.



97) Explain the life cycle of thread?
A thread can be in any of the five states :
1) New : When the instance of thread is created it will be in New state.
Ex : Thread t= new Thread(); In the above example t is in new state. The thread is created but not in active state to make it active we need to call start() method on it.
2) Runnable state : A thread can be in the runnable state in either of the following two ways :
a) When the start method is invoked or
b) A thread can also be in runnable state after coming back from blocked or sleeping or waiting state.
3) Running state : If thread scheduler allocates cpu time, then the thread will be in running state.
4) Waited /Blocking/Sleeping state: In this state the thread can be made temporarily inactive for a short period of time. A thread can be in
the above state in any of the following ways:
1) The thread waits to acquire lock of an object.
2) The thread waits for another thread to complete.
3) The thread waits for notification of other thread.
5) Dead State : A thread is in dead state when thread’s run method execution is complete. It dies
automatically when thread’s run method execution is completed and the thread object will be garbage
collected.


98) Can we restart a dead thread in java?
If we try to restart a dead thread by using start method we will get run time exception since the thread is not alive.


99) Can one thread block the other thread?
No one thread cannot block the other thread in java. It can block the current thread that is running.


100) Can we restart a thread already started in java?
A thread can be started in java using start() method in java. If we call start method second time once it is started it will cause RunTimeException(IllegalThreadStateException). A runnable thread cannot be restarted.

Wednesday, November 24, 2021

Top Java Interview Question and Answers series - Part3



********************************************
Top Java Interview Question and Answers series - Part3
********************************************


***Java Exception Handling***




51) What are abstract methods in java?
An abstract method is the method which does’nt have any body. Abstract method is declared with keyword abstract and semicolon in place of method body.
Signature : public abstract void <method name>();
Ex : public abstract void getDetails();
It is the responsibility of subclass to provide implementation to abstract method defined in abstract class.


52) What is an exception in java?
In java exception is an object. Exceptions are created when an abnormal situations are arised in our program. Exceptions can be created by JVM or by our application code. All Exception classes are defined
in java.lang. In otherwords we can say Exception as run time error.


53) State some situations where exceptions may arise in java?
1) Accesing an element that does not exist in array.
2) Invalid conversion of number to string and string to number. (NumberFormatException)
3) Invalid casting of class (Class cast Exception)
4) Trying to create object for interface or abstract class (Instantiation Exception)


54) What is Exception handling in java?
Exception handling is a mechanism what to do when some abnormal situation arises in program. When an exception is raised in program it leads to termination of program when it is not handled properly. The significance of exception handling comes here in order not to terminate a program abruptly and to
continue with the rest of program normally. This can be done with help of Exception handling.


55) What is an eror in Java?
Error is the subclass of Throwable class in java. When errors are caused by our program we call that as Exception, but some times exceptions are caused due to some environment issues such as running out of memory. In such cases we can’t handle the exceptions. Exceptions which cannot be recovered are called
as errors in java.
Ex : Out of memory issues.


56) What are advantages of Exception handling in java?
1) Separating normal code from exception handling code to avoid abnormal termination of program.
2) Categorizing in to different types of Exceptions so that rather than handling all exceptions with Exception root class we can handle with specific exceptions. It is recommended to handle exceptions with specific Exception instead of handling with Exception root class.
3) Call stack mechanism : If a method throws an exception and it is not handled immediately, then that exception is propagated or thrown to the caller of that method. This propogation continues till it finds an appropriate exception handler ,if it finds handler it would be handled otherwise program terminates abruptly.


57) In how many ways we can do exception handling in java? 
We can handle exceptions in either of the two ways :
1) By specifying try catch block where we can catch the exception.
2) Declaring a method with throws clause .


58) List out five keywords related to Exception handling ?
1) Try
2) Catch
3) throw
4) throws
5) finally


59) Explain try and catch keywords in java?
In try block we define all exception causing code. In java try and catch forms a unit. A catch block catches the exception thrown by preceding try block. Catch block cannot catch an exception thrown by another try block. If there is no exception causing code in our program or exception is not raised in our code jvm ignores the try catch block.
Syntax :
try
{
}
Catch(Exception e)
{
}


60) Can we have try block without catch block?
Each try block requires atleast one catch block or finally block. A try block without catch or finally will result in compiler error. We can skip either of catch or finally block but not both.


61) Can we have multiple catch block for a try block?
In some cases our code may throw more than one exception. In such case we can specify two or more catch clauses, each catch handling different type of exception. When an exception is thrown jvm checks each catch statement in order and the first one which matches the type of exception is execution and remaining catch blocks are skipped.
Try with multiple catch blocks is highly recommended in java. If try with multiple catch blocks are present the order of catch blocks is very important and the order should be from child to parent.


62) Explain importance of finally block in java?
Finally block is used for cleaning up of resources such as closing connections, sockets etc. if try block executes with no exceptions then finally is called after try block without executing catch block. If there is exception thrown in try block finally block executes immediately after catch block. If an exception is thrown,finally block will be executed even if the no catch block handles the exception.


63) Can we have any code between try and catch blocks?
We shouldn’t declare any code between try and catch block. Catch block should immediately start after try block.
try{
//code
}
System.out.println(“one line of code”); // illegal
catch(Exception e){
//
}


64) Can we have any code between try and finally blocks?
We shouldn’t declare any code between try and finally block. finally block should immediately start after catch block.If there is no catch block it should immediately start after try block.
try{
//code
}
System.out.println(“one line of code”); // illegal
finally{
//
}


65) Can we catch more than one exception in single catch block?
From Java 7, we can catch more than one exception with single catch block. This type of handling reduces the code duplication.
Note : When we catch more than one exception in single catch block , catch parameter is implicity final. We cannot assign any value to catch parameter.
Ex : catch(ArrayIndexOutOfBoundsException || ArithmeticException e)
{

}
In the above example e is final we cannot assign any value or modify e in catch statement.


66) What are checked Exceptions?
1) All the subclasses of Throwable class except error,Runtime Exception and its subclasses are checked exceptions.
2) Checked exception should be thrown with keyword throws or should be provided try catch block, else the program would not compile. We do get compilation error.
Examples :
1) IOException,
2) SQlException,
3) FileNotFoundException,
4) InvocationTargetException,
5) CloneNotSupportedException
6) ClassNotFoundException
7) InstantiationException


67) What are unchecked exceptions in java?
All subclasses of RuntimeException are called unchecked exceptions. These are unchecked exceptions because compiler does not checks if a method handles or throws exceptions. Program compiles even if we do not catch the exception or throws the exception.
If an exception occurs in the program,program terminates . It is difficult to handle these exceptions because there may be many places causing exceptions.
Example : 
1) Arithmetic Exception
3) ArrayIndexOutOfBoundsException
4) ClassCastException
5) IndexOutOfBoundException
6) NullPointerException
7) NumberFormatException
8) StringIndexOutOfBounds
9) UnsupportedOperationException


68) Explain differences between checked and Unchecked exceptions in java?
Unchecked Exception Checked Exception
1) All the subclasses of RuntimeException are called unchecked exception. All subclasses of Throwable class except RuntimeException are called as checked exceptions
2) Unchecked exceptions need not be handled at compile time Checked Exceptions need to be handled at compile time.
3) These exceptions arise mostly due to coding mistakes in our program.
4) ArrayIndexOutOfBoundsException, ClassCastException, IndexOutOfBoundException SqlException, FileNotFoundException, ClassNotFoundException


69) What is default Exception handling in java?
When JVM detects exception causing code, it constructs a new exception handling object by including the following information.
1) Name of Exception
2) Description about the Exception
3) Location of Exception.
After creation of object by JVM it checks whether there is exception handling code or not. If there is exception handling code then exception handles and continues the program. If there is no exception handling code JVM give the responsibility of exception handling to default handler and terminates abruptly.
Default Exception handler displays description of exception,prints the stacktrace and location of exception and terminates the program.
Note : The main disadvantage of this default exception handling is program terminates abruptly.


70) Explain throw keyword in java?
Generally JVM throws the exception and we handle the exceptions by using try catch block. But there are situations where we have to throw userdefined exceptions or runtime exceptions. In such case we use throw keyword to throw exception explicitly.
Syntax : throw throwableInstance;
Throwable instance must be of type throwable or any of its subclasses. After the throw statement execution stops and subsequent statements are not executed. Once exception object is thrown JVM checks is there any catch block to handle the exception. If not then the next catch statement till it finds the appropriate handler. If appropriate handler is not found ,then default exception handler halts the program and prints the description and location of exception.
In general we use throw keyword for throwing userdefined or customized exception.


71) Can we write any code after throw statement?
After throw statement jvm stop execution and subsequent statements are not executed. If we try to write any statement after throw we do get compile time error saying unreachable code.


72) Explain importance of throws keyword in java?
Throws statement is used at the end of method signature to indicate that an exception of a given type may be thrown from the method.
The main purpose of throws keyword is to delegate responsibility of exception handling to the caller methods, in the case of checked exception. In the case of unchecked exceptions, it is not required to use throws keyword. We can use throws keyword only for throwable types otherwise compile time error saying incompatible types.
An error is unchecked , it is not required to handle by try catch or by throws.
Syntax : Class Test{
Public static void main(String args[]) throws IE
{
}
}
Note : The method should throw only checked exceptions and subclasses of checked exceptions. It is not recommended to specify exception superclasses in the throws class when the actual exceptions thrown in the method are instances of their subclass.


73) Explain the importance of finally over return statement?
finally block is more important than return statement when both are present in a program. For example if there is any return statement present inside try or catch block , and finally block is also present first finally statement will be executed and then return statement will be considered.

74) Explain a situation where finally block will not be executed?
Finally block will not be executed whenever jvm shutdowns. If we use system.exit(0) in try statement finally block if present will not be executed.


75) Can we use catch statement for checked exceptions?
If there is no chance of raising an exception in our code then we can’t declare catch block for handling checked exceptions .This raises compile time error if we try to handle checked exceptions when there is no possibility of causing exception.

Saturday, November 6, 2021

Top Java Interview Question and Answers series - Part2


********************************************
Top Java Interview Question and Answers series - Part2
********************************************
    

26) Explain Java Coding Standards for classes or Java coding conventions for classes?
Sun has created Java Coding standards or Java Coding Conventions . It is recommended highly to follow java coding standards. Classnames should start with uppercase letter. Classnames names should be nouns. If Class name is of multiple words then the first letter of inner word must be capital letter. 
Ex : Employee, EmployeeDetails, ArrayList, TreeSet, HashSet


27) Explain Java Coding standards for interfaces?
1) Interface should start with uppercase letters
2) Interfaces names should be adjectives
Example : Runnable, Serializable, Marker, Cloneable


28) Explain Java Coding standards for Methods?
1) Method names should start with small letters.
2) Method names are usually verbs
3) If method contains multiple words, every inner word should start with uppercase letter.
Ex : toString()
4) Method name must be combination of verb and noun
Ex : getCarName(),getCarNumber()


29) Explain Java Coding Standards for variables ?
1) Variable names should start with small letters.
2) Variable names should be nouns
3) Short meaningful names are recommended.
4) If there are multiple words every innerword should start with Uppecase character.
Ex : string,value,empName,empSalary


30) Explain Java Coding Standards for Constants?
Constants in java are created using static and final keywords.
1) Constants contains only uppercase letters.
2) If constant name is combination of two words it should be separated by underscore.
3) Constant names are usually nouns.
Ex:MAX_VALUE, MIN_VALUE, MAX_PRIORITY, MIN_PRIORITY


31) Difference between overriding and overloading in java?
Overriding Overloading
In overriding method names must be same In overloading method names must be same
Argument List must be same Argument list must be different atleast order of arguments.

Return type can be same or we can return covariant type. From 1.5 covariant types are allowed

Return type can be different in overloading.
We cant increase the level of checked exceptions. No restrictions for unchecked exceptions In overloading different exceptions can be thrown.
A method can only be overridden in subclass A method can be overloaded in same class or subclass

Private,static and final variables cannot be overridden.

Private , static and final variables can be overloaded.

In overriding which method is called is decided at runtime based on the type of object referenced at run time In overloading which method to call is decided at compile time based on reference type.

Overriding is also known as Runtime polymorphism, dynamic polymorphism or late binding Overloading is also known as Compile time polymorphism, static polymorphism or early binding.


32) What is ‘IS-A ‘ relationship in java? 
‘is a’ relationship is also known as inheritance. We can implement ‘is a’ relationship or inheritance in java using extends keyword. The advantage or inheritance or is a relationship is reusability of code instead of duplicating the code.
Ex : Motor cycle is a vehicle
Car is a vehicle Both car and motorcycle extends vehicle.


33) What is ‘HAS A’’ relationship in java?
‘Has a ‘ relationship is also known as “composition or Aggregation”. As in inheritance we have ‘extends’ keyword we don’t have any keyword to implement ‘Has a’ relationship in java. The main advantage of  ‘Has-A‘ relationship in java code reusability.


34) Difference between ‘IS-A’ and ‘HAS-A’ relationship in java?
IS-A relationship HAS- A RELATIONSHIP. Is a relationship also known as inheritance Has a relationship also known as composition or aggregation. For IS-A relationship we uses extends keyword For Has a relationship we use new keyword  
Ex : Car is a vehicle. 
Ex : Car has an engine. We cannot say Car is an engine. The main advantage of inheritance is reusability of code. The main advantage of has a relationship is reusability of code.


35) Explain about instanceof operator in java?

Instanceof operator is used to test the object is of which type.
Syntax : <reference expression> instanceof <destination type>
Instanceof returns true if reference expression is subtype of destination type.
Instanceof returns false if reference expression is null.
Example :
public classInstanceOfExample{
         public static voidmain(String[] args) {
                Integer a = newInteger(5);
           if (a instanceof java.lang.Integer) {
                System.out.println(true);
          } else {
                System.out.println(false);
                }
            }
        }


Since a is integer object it returns true.
There will be a compile time check whether reference expression is subtype of destination type. If it is not a subtype then compile time error will be shown as Incompatible types


36) What does null mean in java?

When a reference variable doesn’t point to any value it is assigned null.
Example : Employee employee;
In the above example employee object is not instantiate so it is pointed no where


37) Can we have multiple classes in single file ?

Yes we can have multiple classes in single file but it people rarely do that and not recommended. We can have multiple classes in File but only one class can be made public. If we try to make two classes in File public we get following compilation error. “The public type must be defined in its own file”.


38) What all access modifiers are allowed for top class ?

For top level class only two access modifiers are allowed. public and default. If a class is declared as public it is visible everywhere. If a class is declared default it is visible only in same package. If we try to give private and protected as access modifier to class we get the below compilation error.
Illegal Modifier for the class only public, abstract and final are permitted.


39 ) What are packages in java?
Package is a mechanism to group related classes ,interfaces and enums in to a single module.
Package can be declared using the following statement :
Syntax : package <package-name>
Coding Convention : package name should be declared in small letters.
package statement defines the namespace. 
The main use of package is
1) To resolve naming conflicts
2) For visibility control : We can define classes and interfaces that are not accessible outside the class.


40) Can we have more than one package statement in source file ?

We can’t have more than one package statement in source file. In any java program there can be atmost only 1 package statement. We will get compilation error if we have more than one package statement in source file.


41) Can we define package statement after import statement in java?

We can’t define package statement after import statement in java. package statement must be the first statement in source file. We can have comments before the package statement.


42) What are identifiers in java?
Identifiers are names in java program. Identifiers can be class name, method name or variable name.
Rules for defining identifiers in java:
1) Identifiers must start with letter, Underscore or dollar($) sign.
2) Identifiers can’t start with numbers .
3) There is no limit on number of characters in identifier but not recommended to have more than 15 characters
4) Java identifiers are case sensitive.
5) First letter can be alphabet ,or underscore and dollar sign. From second letter we can have numbers.
6) We shouldn't use reserve words for identifiers in java.


43) What are access modifiers in java?

The important feature of encapsulation is access control. By preventing access control we can misuse of class, methods and members. A class, method or variable can be accessed is determined by the access modifier. There are three types of access modifiers in java. public, private, protected. If no access modifier is specified then it has a default access.


44) What is the difference between access specifiers and access modifiers in java?

In C++ we have access specifiers as public, private, protected and default and access modifiers as static, final. But there is no such division of access specifiers and access modifiers in java. In Java we have access modifiers and non access modifiers.
Access Modifiers : public, private, protected, default
Non Access Modifiers : abstract, final, strictfp.


45) What access modifiers can be used for class ?

We can use only two access modifiers for class public and default.
public: A class with public modifier can be visible
1) In the same class
2) In the same package subclass
3) In the same package non subclass
4) In the different package subclass
5) In the different package non subclass.
default : A class with default modifier can be accessed
1) In the same class
2) In the same package subclass
3) In the same package non subclass
4) In the different package subclass
5) In the different package non subclass.


46) Explain what access modifiers can be used for methods?

We can use all access modifiers public, private, protected and default for methods.
public : When a method is declared as public it can be accessed
6) In the same class
7) In the same package subclass
8) In the same package nonsubclass
9) In the different package subclass
10) In the different package non subclass.
default : When a method is declared as default, we can access that method in
1) In the same class
2) In the same package subclass
3) In the same package non subclass
We cannot access default access method in
1) Different package subclass
2) Different package non subclass.
protected : When a method is declared as protected it can be accessed
1) With in the same class
2) With in the same package subclass
3) With in the same package non subclass
4) With in different package subclass
It cannot be accessed non subclass in different package.
private : When a method is declared as private it can be accessed only in that class.
It cannot be accessed in
1) Same package subclass
2) Same package non subclass
3) Different package subclass
4) Different package non subclass.


47) Explain what access modifiers can be used for variables?
We can use all access modifiers public, private, protected and default for variables.
public : When a variables is declared as public it can be accessed
1) In the same class
2) In the same package subclass
3) In the same package nonsubclass
4) In the different package subclass
5) In the different package non subclass.
default : When a variables is declared as default, we can access that method in
1) In the same class
2) In the same package subclass
3) In the same package non subclass
We cannot access default access variables in
4) Different package subclass
5) Different package non subclass.
protected : When a variables is declared as protected it can be accessed
1) With in the same class
2) With in the same package subclass
3) With in the same package non subclass
4) With in different package subclass
It cannot be accessed non subclass in different package.
private : When a variables is declared as private it can be accessed only in that class.
It cannot be accessed in
1) Same package subclass
2) Same package non subclass
3) Different package subclass
4) Different package non subclass.


48) What is final access modifier in java?
final access modifier can be used for class, method and variables. The main advantage of final access
modifier is security no one can modify our classes, variables and methods. The main disadvantage of final access modifier is we cannot implement oops concepts in java. Ex : Inheritance, polymorphism.
final class : A final class cannot be extended or subclassed. We are preventing inheritance by marking a
class as final. But we can still access the methods of this class by composition. Ex: String class
final methods: Method overriding is one of the important features in java. But there are situations where we may not want to use this feature. Then we declared method as final which will print overriding. To allow a method from being overridden we use final access modifier for methods.
final variables : If a variable is declared as final ,it behaves like a constant . We cannot modify the value of final variable. Any attempt to modify the final variable results in compilation error. The error is as follows “final variable cannot be assigned.”


49) Explain about abstract classes in java?
Sometimes we may come across a situation where we cannot provide implementation to all the methods in a class. We want to leave the implementation to a class that extends it. In such case we declare a class as abstract. To make a class abstract we use key word abstract. Any class that contains one or more  abstract methods is declared as abstract. If we don’t declare class as abstract which contains abstract methods we get compile time error. We get the following error. “The type <class-name> must be an abstract class to define abstract methods.”
Signature ; 
abstract class <class-name>
{
}

For example if we take a vehicle class we cannot provide implementation to it because there may be two
wheelers , four wheelers etc. At that moment we make vehicle class abstract. All the common features of vehicles are declared as abstract methods in vehicle class. Any class which extends vehicle will provide its method implementation. It’s the responsibility of subclass to provide implementation.
The important features of abstract classes are :
1) Abstract classes cannot be instantiated.
2) An abstract classes contains abstract methods, concrete methods or both.
3) Any class which extends abstract class must override all methods of abstract class.
4) An abstract class can contain either 0 or more abstract methods.
Though we cannot instantiate abstract classes we can create object references .
Through superclass references we can point to subclass.


50) Can we create constructor in abstract class ?
We can create constructor in abstract class , it doesn't give any compilation error. But when we cannot instantiate class there is no use in creating a constructor for abstract class.


50) Can we override the constructor ?
A constructor cannot be overridden. If you try to write a super class’s constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.
Compile time error would be - "Invalid method declaration; return type required"

How to install Java on EC2

***************************************** How to install Java on EC2 ***************************************** To be continued, In this post...

All Time Popular Post