1. forEach method in java.lang.Iterable interface

    Java 8 has introduced forEach method in java.lang.Iterable interface so that while writing code we focus on business logic. The forEach method takes java.util.function.Consumer object as an argument, so it helps in having our business logic at a separate location that we can reuse.

  2. myList.forEach(new Consumer < Integer > () {
        public void accept(Integer t) {
            System.out.println("forEach anonymous class Value::" + t);
        }
    
    });
    
    //traversing with Consumer interface implementation
    MyConsumer action = new MyConsumer();
    myList.forEach(action);
    

    Consumer implementation that can be reused

    class MyConsumer implements Consumer<Integer>{
    
    	public void accept(Integer t) {
    		System.out.println("Consumer impl Value::"+t);
    	}
    }
    
  3. Interfaces with default and static methods

    From Java 8, interfaces are enhanced to have a method with implementation. We can use default and static keyword to create interfaces with method implementation

  4. We know that Java doesn’t provide multiple inheritance in Classes because it leads to Diamond Problem. So how it will be handled with interfaces now since interfaces are now similar to abstract classes. Compiler will throw an exception in this scenario and we will have to provide implementation logic in the class implementing the interfaces.

    @FunctionalInterface
    public interface Interface1 {
    
        void method1(String str);
    
        default void log(String str) {
            System.out.println("I1 logging::" + str);
        }
    
        static void print(String str) {
            System.out.println("Printing " + str);
        }
    }    
    

    interfaces are not allowed to have Object default methods.

  5. @FunctionalInterface annotation. Functional interfaces are a new concept introduced in Java 8. An interface with exactly one abstract method becomes a Functional Interface. We don’t need to use @FunctionalInterface annotation to mark an interface as a Functional Interface.

    @FunctionalInterface annotation is a facility to avoid the accidental addition of abstract methods in the functional interfaces. You can think of it like @Override annotation and it’s best practice to use it. java.lang.Runnable with a single abstract method run() is a great example of a functional interface.

    Anonymous Class Implementation

    Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.println("My Runnable");
        }
    };
    

    Lambda Expression Implementation

    Runnable r1 = () - > {
        System.out.println("My Runnable");
    };
    

    If you have single statement in method implementation anonymous class can be instantiated using lambda expression as below
    lambda expressions Implementation

    Interface1 i1 = (s) -> System.out.println(s);		
    i1.method1("abc");
    
  6. New java.util.stream has been added in Java 8 to perform filter/map/reduce like operations with the collection. Stream API will allow sequential as well as parallel execution.
    public static void main(String[] args) {
    
        List < Integer > myList = new ArrayList < > ();
        for (int i = 0; i < 100; i++) myList.add(i);
    
        //sequential stream
        Stream < Integer > sequentialStream = myList.stream();
    
        //parallel stream
        Stream < Integer > parallelStream = myList.parallelStream();
    
        //using lambda with Stream API, filter example
        Stream < Integer > highNums = parallelStream.filter(p - > p > 90);
        //using lambda in forEach
        highNums.forEach(p - > System.out.println("High Nums parallel=" + p));
    
        Stream < Integer > highNumsSeq = sequentialStream.filter(p - > p > 90);
        highNumsSeq.forEach(p - > System.out.println("High Nums sequential=" + p));
    
    }
    

    parallel processing values are not in order, so parallel processing will be very helpful while working with huge collections.

  7. IO improvements known to me are:

    Files.list(Path dir) that returns a lazily populated Stream, the elements of which are the entries in the directory.
    Files.lines(Path path) that reads all lines from a file as a Stream.
    Files.find() that returns a Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file.
    BufferedReader.lines() that return a Stream, the elements of which are lines read from this BufferedReader.

  8. Java Time API packages, I can sense that they will be very easy to use. It has some sub-packages java.time.format that provides classes to print and parse dates and times and java.time.zone provides support for time zones and their rules.
  1. What is the Difference between Map and Filter?
    Both perform intermediate Operations and returns stream as output.By using map, you transform the object values.
    Map returns a stream consisting of the results of applying the given function to the elements of this stream. In a simple sentence, the map returns the transformed object value.
    Filter is used for filtering the data, it always returns the boolean value. If it returns true, the item is added to list else it is filtered out (ignored)
  2. Find the Sum of Nos in List?
    public class ReduceEgs {
        public static void main(String[] args) {
            List<Integer> arrNumbers =  Arrays.asList(1,2,3,4,5,6,7,8,9);
    
            Integer sum = arrNumbers.stream().reduce(0, Integer::sum);
            Integer sum2 = arrNumbers.stream().reduce(0, (x,y)->x+y);
            Integer sum3 = arrNumbers.stream().reduce(0, ReduceEgs::sumNos);
        }
    
        public static Integer sumNos(int x, int y){
            System.out.println("a -"+ x + " b - "+  y);
            return x+y;
        }
    }
    
  3. Find the Min and Max in Nos List?
     public static void main(String[] args) {
            List<Integer> arrNumbers =  Arrays.asList(1,2,3,4,5,-6,7,-8,9);
    
            arrNumbers =  Arrays.asList(-5,-6,-8);
            Integer Max = arrNumbers.stream().reduce(0, (x,y)->x>y?x:y);
            System.out.println("Output 1 ="+ Max);
    
            //Its good to start with Identity as Negative Value in order to address negative Integer Comparison
            //If you start with 0 then 0 would be returned like above
            Integer Max2 = arrNumbers.stream().reduce(Integer.MIN_VALUE, (x,y)->x>y?x:y);
            System.out.println("Output 2 ="+ Max2);
    
            arrNumbers =  Arrays.asList(5,6,8);
    
            Integer Min = arrNumbers.stream().reduce(0, (x,y)->x<y?x:y);
            System.out.println("Output 3 ="+ Min);
    
            //Its good to start with Identity as Max Positive Value in order to address Integer Comparison
            Integer Min2 = arrNumbers.stream().reduce(Integer.MAX_VALUE, (x,y)->x<y?x:y);
            System.out.println("Output 4 ="+ Min2);
        }
    

    Output

    Output 1 =0
    Output 2 =-5
    Output 3 =0
    Output 4 =5
    
  4. Find the Sum of Square of Nos in List?
    public class ReduceEgs {
        public static void main(String[] args) {
            List<Integer> arrNumbers =  Arrays.asList(1,2,3);
    
            Integer squareSum = arrNumbers.stream().map(x->x*x).reduce(0, Integer::sum);
            System.out.println("Output 1 ="+ squareSum);
        }
    }
    

    Output

    Output 1 =14
    
  5. Find the Sum of Odd Nos in List?
    public class ReduceEgs {
        public static void main(String[] args) {
            List<Integer> arrNumbers =  Arrays.asList(1,2,3);
    
            Integer squareSum = arrNumbers.stream().filter(x-> x%2==1).reduce(0, Integer::sum);
            System.out.println("Output 1 ="+ squareSum);
        }
    }
    

    Output

    Output 1 =4
    
  6. Distinct elements from List?
    public class ReduceEgs {
        public static void main(String[] args) {
            List<Integer> arrNumbers =  Arrays.asList(1,2,3,1,4,2);
    
            System.out.println("Output 1");
            arrNumbers.stream().distinct().forEach(System.out::println);
        }
    }
    
    

    Output

    Output 1
    1
    2
    3
    4
    
  7. Sort Elements in List?
     public static void main(String[] args) {
       List<Integer> arrNumbers =  Arrays.asList(1,2,3,1,4,2);
    
       System.out.println("Output 2");
       arrNumbers.stream().sorted().forEach(System.out::println);
    }
    

    Output

    Output 2
    1
    1
    2
    2
    3
    4
    
  8. Sorting based on Natural Order, Reverse Order and Length of String?
    public static void main(String[] args) {
            List<String> arrSkills = Arrays.asList("Java", "Python",  "Ant");
    
            System.out.println("Sorting in Natural Order");
            arrSkills.stream().sorted(Comparator.naturalOrder()).forEach(System.out::println);
    
            System.out.println("Sorting in Reverse Order");
            arrSkills.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
    
            System.out.println("Sorting based on Length");
            arrSkills.stream().sorted(Comparator.comparing(str -> str.length())).forEach(System.out::println);
    
        }
    

    Output

    Sorting in Natural Order
    Ant
    Java
    Python
    Sorting in Reverse Order
    Python
    Java
    Ant
    Sorting based on Length
    Ant
    Java
    Python
    
  9. Collect the Elements in the List – Collect Even Nos and Length of String ?
        public static void main(String[] args) {
            List<Integer> arrNumbers = Arrays.asList(1,2,4,5,7,6);
            List<String> arrNames = Arrays.asList("Java", "Oracle", "Maven", "Ant");
    
            System.out.println("Collect Even Nos in list");
            List<Integer> arrEvenNumbers = arrNumbers.stream().filter(x->x%2==0).collect(Collectors.toList());
            arrEvenNumbers.stream().forEach(System.out::println);
    
            System.out.println("Length of Elements");
            List<Integer> arrEvenNumbers2 = arrNames.stream().map(str->str.length()).collect(Collectors.toList());
            arrEvenNumbers2.stream().forEach(System.out::println);
        }
    

    Output

    Collect Even Nos in list
    2
    4
    6
    Length of Elements
    4
    6
    5
    3
    
  10. Find the Sum of Nos in List?
    
    
  11. Find the Sum of Nos in List?
    
    
  12. Find the Sum of Nos in List?
    
    

1.What is the Default Size and Capacity of ArrayList in Java 8?What is the Maximum Size of ArrayList?
Size is the number of elements you have placed into the arrayList while capacity is the max number of elements the arrayList can take. Once you’ve reached max, the capacity is doubled.The initial List size is zero (unless you specify otherwise).However the initial capacity of ArrayList is 10.The size of the list is the number of elements in it. The capacity of the list is the number of elements the backing data structure can hold at this time. The size will change as elements are added to or removed from the list. The capacity will change when the implementation of the list you’re using needs it to. (The size, of course, will never be bigger than the capacity.)

When it has to grow, this is used:

 int newCapacity = oldCapacity + (oldCapacity >> 1)

oldCapacity >> 1 is division by two, so it grows by 1.5

int newCapacity = oldCapacity + (oldCapacity >> 1);
int newCapacity = oldCapacity + 0.5*oldCapacity; 
int newCapacity = 1.5*oldCapacity ;

Maximum Size of ArrayList
It would depend on the implementation, but the limit is not defined by the List interface.An ArrayList can’t hold more than Integer.MAX_VALUE elements

2.Difference is between a fixed size container (data structure) and a variable size container.
An array is a fixed size container, the number of elements it holds is established when the array is created and never changes. (When the array is created all of those elements will have some default value, e.g., null for reference types or 0 for ints, but they’ll all be there in the array: you can index each and every one.)

A list is a variable size container, the number of elements in it can change, ranging from 0 to as many as you want (subject to implementation limits). After creation the number of elements can either grow or shrink. At all times you can retrieve any element by its index.

List is actually an interface and it can be implemented in many different ways. Thus, ArrayList, LinkedList, etc. There is a data structure “behind” the list to actually hold the elements. And that data structure itself might be fixed size or variable size, and at any given time might have the exact size of the number of elements in the list, or it might have some extra “buffer” space.The LinkedList, for example, always has in its underlying data structure exactly the same number of “places for elements” as are in the list it is representing. But the ArrayList uses a fixed length array as its backing store.

3.How to create a Synchronized ArrayList
There are two ways to Synchronize ArrayList

  1. Collections.synchronizedList() method – It returns synchronized list backed by the specified list.
  2. CopyOnWriteArrayList class – It is a thread-safe variant of ArrayList.It achieves thread-safety by creating a separate copy of List which is a is different way than vector or other collections use to provide thread-safety

More here

4.Why to use arrayList when vector is synchronized?
Vector synchronizes at the level of each individual operation. Generally a programmer like to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe and slower.Vectors are considered obsolete an d unofficially deprecated in java.

5.Difference between CopyOnWriteArrayList and synchronizedList
Both synchronizedList and CopyOnWriteArrayList take a lock on the entire array during write operations.The difference emerges if you look at other operations, such as iterating over every element of the collection. The documentation for Collections.synchronizedList says It is imperative that the user manually synchronize on the returned list when iterating over it.Failure to follow this advice may result in non-deterministic behavior.

 List list = Collections.synchronizedList(new ArrayList());
    ...
    synchronized (list) {
        Iterator i = list.iterator(); // Must be in synchronized block
        while (i.hasNext())
            foo(i.next());
    }

Iterating over a synchronizedList is not thread-safe unless you do locking manually. Note that when using this technique, all operations by other threads on this list, including iterations, gets, sets, adds, and removals, are blocked. Only one thread at a time can do anything with this collection.

CopyOnWriteArrayList uses “snapshot” style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException. The iterator will not reflect additions, removals, or changes to the list since the iterator was created. “snapshot” style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException. The iterator will not reflect additions, removals, or changes to the list since the iterator was created.

Operations by other threads on this list can proceed concurrently, but the iteration isn’t affected by changes made by any other threads. So, even though write operations lock the entire list, CopyOnWriteArrayList still can provide higher throughput than an ordinary synchronizedList.

6.What is Functional Interface?What are the rules to define a Functional Interface?Is it Mandatory to define @FunctionalInterface annotation?
Functional Interface also know as Single Abstract Method(SAM) interface contains one and only one abstract method. @FunctionalInterface is not amndatory but tells other developers the interface is Functional and prevents them from adding anymore methods to it.We can have any number of Default methods and Static methods.Overridding methods in java.lang.object such as equals and hashcode doesnot count as an abstract method. More here

7.Difference between Streams and Collections?

Stream Collections
A stream is not a data structure that stores elements; instead, it conveys elements from a source such as a data structure, an array, a generator function, or an I/O channel, through a pipeline of computational operations. Collection is a Datastructure
An operation on a stream produces a result, but does not modify its source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection. Operation on collection will have direct impact on collection object itself
Streams are based on ‘process-only, on-demand’ strategy.Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy. All Data Values in collections are processed in single shot
Stream acts upon infinite set of Values i.e. infinite stream Collections always act upon finite set of Data
The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source. Collections can be iterated any number of Times

8.How do I read / convert an InputStream into a String in Java?
Using Apache commons IOUtils to copy the InputStream into a StringWriter

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
String theString = IOUtils.toString(inputStream, encoding); 

Using only the standard Java library

static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

Scanner iterates over tokens in the stream, and in this case we separate tokens using “beginning of the input boundary” (\A), thus giving us only one token for the entire contents of the stream.

9.How do I convert a String to an InputStream in Java?

InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));

Using Apache Commons IO

String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");

Using StringReader

String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);

10.Difference between hashtable and hashmap?
Click here

11.What is exception-masking?
When code in a try block throws an exception, and the close method in the finally also throws an exception, the exception thrown by the try block gets lost and the exception thrown in the finally gets propagated. This is usually unfortunate, since the exception thrown on close is something unhelpful while the useful exception is the informative one. Using try-with-resources to close your resources will prevent any exception-masking from taking place.

11.Try With Resources vs Try-Catch

  1. The main point of try-with-resources is to make sure resources are closed, without requiring the application code to do it.
  2. when there are situations where two independent exceptions can be thrown in sibling code blocks, in particular in the try block of a try-with-resources statement and the compiler-generated finally block which closes the resource. In these situations, only one of the thrown exceptions can be propagated. In the try-with-resources statement, when there are two such exceptions, the exception originating from the try block is propagated and the exception from the finally block is added to the list of exceptions suppressed by the exception from the try block. As an exception unwinds the stack, it can accumulate multiple suppressed exceptions.
  3. On the other hand if your code completes normally but the resource you’re using throws an exception on close, that exception (which would get suppressed if the code in the try block threw anything) gets thrown. That means that if you have some JDBC code where a ResultSet or PreparedStatement is closed by try-with-resources, an exception resulting from some infrastructure glitch when a JDBC object gets closed can be thrown and can rollback an operation that otherwise would have completed successfully.

12.How to get Suppressed Exceptions?
only one exception can be thrown by a method (per execution) but it is possible, in the case of a try-with-resources, for multiple exceptions to be thrown. For instance one might be thrown in the block and another might be thrown from the implicit finally provided by the try-with-resources.The compiler has to determine which of these to “really” throw. It chooses to throw the exception raised in the explicit code (the code in the try block) rather than the one thrown by the implicit code (the finally block). Therefore the exception(s) thrown in the implicit block are suppressed (ignored). This only occurs in the case of multiple exceptions.

The try-catch-resource block does expose the suppressed exception using the new (since Java 1.7) getSuppressed() method. This method returns all of the suppressed exceptions by the try-catch-resource block (notice that it returns ALL of the suppressed exceptions if more than one occurred). A caller might use the following structure to reconcile with existing behavior

try { 
  testJava7TryCatchWithExceptionOnFinally(); //Method throws exception in both try and finally block
} catch (IOException e) {   
  Throwable[] suppressed = e.getSuppressed();
    for (Throwable t : suppressed) {
    // Check T's type and decide on action to be taken
  }
}

13.How do you avoid fuzzy try-catch blocks in code like one below?

try{ 
     ...
     stmts
     ...
} 
catch(Exception ex) {
     ... 
     stmts
     ... 
} finally {
     connection.close // throws an exception
}

Write a SQLUtils class that contains static closeQuietly methods that catch and log such exceptions, then use as appropriate.

public class SQLUtils 
{
  private static Log log = LogFactory.getLog(SQLUtils.class);

  public static void closeQuietly(Connection connection)
  {
    try
    {
      if (connection != null)
      {
        connection.close();
      }
    }
    catch (SQLExcetpion e)
    {
      log.error("An error occurred closing connection.", e);
    }
  }

  public static void closeQuietly(Statement statement)
  {
    try
    {
      if (statement!= null)
      {
        statement.close();
      }
    }
    catch (SQLExcetpion e)
    {
      log.error("An error occurred closing statement.", e);
    }
  }

  public static void closeQuietly(ResultSet resultSet)
  {
    try
    {
      if (resultSet!= null)
      {
        resultSet.close();
      }
    }
    catch (SQLExcetpion e)
    {
      log.error("An error occurred closing result set.", e);
    }
  }
}

and

Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try 
{
  connection = getConnection();
  statement = connection.prepareStatement(...);
  resultSet = statement.executeQuery();

  ...
}
finally
{
  SQLUtils.closeQuietly(resultSet);
  SQLUtils.closeQuietly(statment);
  SQLUtils.closeQuietly(connection);
}

14.What is Difference between Iterator and Split Iterator
A Spliterator can be used to split given element set into multiple sets so that we can perform some kind of operations/calculations on each set in different threads independently, possibly taking advantage of parallelism. It is designed as a parallel analogue of Iterator. Other than collections, the source of elements covered by a Spliterator could be, for example, an array, an IO channel, or a generator function.

There are 2 main methods in the Spliterator interface.

  1. tryAdvance()- With tryAdvance(), we can traverse underlying elements one by one (just like Iterator.next()). If a remaining element exists, this method performs the consumer action on it, returning true; else returns false.
  2. forEachRemaining() -For sequential bulk traversal we can use forEachRemaining()

A Spliterator is also a “smarter” Iterator, via it’s internal properties like DISTINCT or SORTED, etc (which you need to provide correctly when implementing your own Spliterator). These flags are used internally to disable unnecessary operations, also called optimizations, like this one for example:

 someStream().map(x -> y).count();

Because size does not change in case of the stream, the map can be skipped entirely, since all we do is counting.

You can create a Spliterator around an Iterator if you would need to, via:

Spliterators.spliteratorUnknownSize(yourIterator, properties)

15.What is Type Inference?
Type Inference means determining the Type by compiler at compile-time.It is not new feature in Java SE 8. It is available in Java 7 and before Java 7 too.Java 8 uses Type inference for calling lambda expressions. Refer here

16.What is Optional in Java 8? What is the use of Optional?Advantages of Java 8 Optional?
Optional is a final Class introduced as part of Java SE 8. It is defined in java.util package.It is used to represent optional values that is either exist or not exist. It can contain either one value or zero value. If it contains a value, we can get it. Otherwise, we get nothing.It is a bounded collection that is it contains at most one element only. It is an alternative to “null” value.

17.What is difference between initialization and instantiation?
instantiation – This is when memory is allocated for an object. This is what the new keyword is doing. A reference to the object that was created is returned from the new keyword.
initialization – This is when values are put into the memory that was allocated. This is what the Constructor of a class does when using the new keyword.A variable must also be initialized by having the reference to some object in memory passed to it.
Refer here

18.What are different Method References in Java?

  1. Reference to a static method – ClassName::MethodName
  2. Reference to an instance method – Object::methodName
  3. Reference to a constructor – ClassName::new

Refer Here

19.What are the difference between predicate and function?
Predicate interface has an abstract method test(T t) which has a Boolean return type. Usage, when we need to return/check the condition as True or False. It is best suited to code.

Function interface has an abstract method apply which takes the argument of type T and returns a result of type R. Here, R is nothing but the type of result user wants to return. It may be Integer, String, Boolean, Double, Long.

20.Why to go for Optional instead of NULL Check?
The Effectiveness of Optional could be only seen during Chaining in Streams or when accessing multiple getters at once like one below

.
.
computer.getSoundcard().getUSB().getVersion();
.
.
.
Optional.ofNullable(modem2)
       .map(Modem::getPrice)
       .filter(p -> p >= 10)
       .filter(p -> p <= 15)
       .isPresent();

21.What is Lambda Expressions?
The Lambda expression is used to provide the implementation for abstract method in functional interface. No need to define the method again for providing the implementation. Here, we just write the implementation code.

@FunctionalInterfac
interface Drawable {
 public void draw();
}

public class LambdaExpressionExample2 {
 public static void main(String[] args) {
  int width = 10;

  //with lambda  
  Drawable d2 = () -> {
   System.out.println("Drawing " + width);
  };
  d2.draw();
 }
}

22.How to handle Checked Exceptions in Lambda Expressions?
To handle checked exception we use a lambda wrapper for the lambda function. Refer here

23.What is the Difference between Lambda Expression and Anonymous Inner Class?
The key difference between Anonymous class and Lambda expression is the usage of ‘this’ keyword. In the anonymous classes, ‘this’ keyword resolves to anonymous class itself, whereas for lambda expression ‘this’ keyword resolves to enclosing class where lambda expression is written.

Another difference between lambda expression and anonymous class is in the way these two are compiled. Java compiler compiles lambda expressions and convert them into private method of the class. It uses invokedynamic instruction that was added in Java 7 to bind this method dynamically.

Functions reside in permanent memory whereas for classes the memory is loaded on demand.
Functions act on unrelated data whereas objects act on their own data.

Refer here

24.Why static methods are Not allowed in Interface prior to Java 8?
Prior to Java 8 Interface could only have abstract methods. If you are writing a static method and defining it then the defining of the static methods may vary based on the implementing classes. So if two classes implement static method and since the
purpose of interface is to provide multiple inheritance when the fourth class implementsthe second and third method which is overrided the it would lead to Diamond of Death Problem.
This is similar to same thing with default methods in Java 8

This Works

class Animal {
    public static void identify() {
        System.out.println("This is an animal");
    }
}
class Cat extends Animal {}

public static void main(String[] args) {
    Animal.identify();
    Cat.identify(); // This compiles, even though it is not redefined in Cat.
}

This Doesnot Works

interface Animal {
    public static void identify() {
        System.out.println("This is an animal");
    }
}
class Cat implements Animal {}

public static void main(String[] args) {
    Animal.identify();
    Cat.identify(); // This does not compile, because interface static methods do not inherit. (Why?)
}

Cat can only extend one class so if Cat extends Animal, Cat.identify has only one meaning. Cat can implement multiple interfaces each of which can have a static implementation.
So Java Compiler is not sure which implementation to call

25.Explain different memory Allocation in JVM?
Memory in Java is divided into two portions

Stack: One stack is created per thread and it stores stack frames which again stores local variables and if a variable is a reference type then that variable refers to a memory location in heap for the actual object.

Heap: All kinds of objects will be created in heap only.

Heap memory is again divided into 3 portions
Young Generation: Stores objects which have a short life, Young Generation itself can be divided into two categories Eden Space and Survivor Space.
Old Generation: Store objects which have survived many garbage collection cycles and still being referenced.
Permanent Generation: Stores metadata about the program e.g. runtime constant pool.