Java Basics
Java Basics
hint: part of JVM that loads bytecodes for classes. You can write your own.
hint: you can use bitwise operator, like bitwise AND, remember, even the number has
zero at the end in binary format and an odd number has 1 in the end.
hint: all differences between List and Set are applicable here, e.g. ordering, duplicates,
random search, etc. See Java Fundamentals: Collections by Richard Warburton to learn
more about ArrayList, HashSet and other important Collections in Java.
2
hint: two-time check whether instances are initialized or not, first without locking and
second with locking.
hint: many ways, like using Enum or by using double-checked locking pattern or using a
nested static class.
hint: when you need to instruct the JVM that a variable can be modified by multiple
threads and give hint to JVM that does not cache its value.
hint: when you want to make a variable non-serializable in a class, which implements the
Serializable interface. In other words, you can use it for a variable whose value you don’t
want to save. See The Complete Java MasterClass to learn about transient variables in
Java.
hint: totally different, one used in the context of serialization while the other is used in
concurrency.
hint: Externalizable gives you more control over the Serialization process.
hint: No, because it’s not visible in the subclass, a primary requirement for overriding a
method in Java.
hint: several but most important is Hashtable, which is synchronized, while HashMap is
not. It's also legacy and slow as compared to HashMap.
4
hint: List is ordered and allows duplicate. Set is unordered and doesn't allow duplicate
elements.
hint: Many, but most important is that ArrayList is non-synchronized and fast while
Vector is synchronized and slow. It's also legacy class like Hashtable.
hint: more scalable. See Java Fundamentals: Collections by Richard Warburton to learn
more.
hint: by dividing the map into segments and only locking during the write operation.
17) Which two methods you will override for an Object to be used as Key in HashMap?
(answer)
hint: The wait() method releases the lock or monitor, while sleep doesn't.
5
hint: notify notifies one random thread is waiting for that lock while notifyAll inform to
all threads waiting for a monitor. If you are certain that only one thread is waiting then
use notify, or else notifyAll is better. See Threading Essentials Mini-Course by Java
Champion Heinz Kabutz to learn more about threading basics.
20) Why do you override hashcode, along with equals() in Java? (answer)
hint: to be compliant with equals and hashcode contract, which is required if you are
planning to store your object into collection classes, e.g. HashMap or ArrayList.
hint: The threshold that triggers the re-sizing of HashMap is generally 0.75, which means
HashMap resize itself if it's 75 percent full.
hint: same as an array and linked list, one allows random search while the other doesn't.
Insertion and deletion are easy on the linked list but a search is easy on an array. See
Java Fundamentals: Collections, Richard Warburton’s course on Pluralsight, to learn
more about essential Collection data structure in Java.
6
hint: You can reuse CyclicBarrier after the barrier is broken but you cannot reuse
CountDownLatch after the count reaches to zero.
hint: always
hint: It means you cannot assign an instance of different Enum type to an Enum variable.
e.g. if you have a variable like DayOfWeek day then you cannot assign it value from
DayOfMonth enum.
hint: PATH is used by the operating system while Classpath is used by JVM to locate Java
binary, e.g. JAR files or Class files. See Java Fundamentals: The Core Platform to learn
more about PATH, Classpath, and other Java environment variable.
hint: Overriding happens at subclass while overloading happens in the same class. Also,
overriding is a runtime activity while overloading is resolved at compile time.
29) How do you prevent a class from being sub-classed in Java? (answer)
30) How do you restrict your class from being used by your client? (answer)
hint: make the constructor private or throw an exception from the constructor
hint: Inheritance allows code reuse and builds the relationship between classes, which is
required by Polymorphism, which provides dynamic behavior. See Grokking the
Object-Oriented Design Interview courses on Educative to learn more about OOP
features and designing classes using OOP techniques.
hint: No, because overriding resolves at runtime while static method call is resolved at
compile time.
hint: yes, in the same class but not outside the class
hint: from Java 8, the difference is blurred. However, a Java class can still implement
multiple interfaces but can only extend one class.
hint: DOM loads the whole XML File in memory while SAX doesn’t. It is an event-based
parser and can be used to parse a large file, but DOM is fast and should be preferred for
small files.
37) Difference between the throw and throws keyword in Java? (answer)
hint: throws declare what exception a method can throw in case of error but throw
keyword actually throws an exception. See Java Fundamentals: Exception Handling to
learn more about Exception handling in Java.
9
hint: Iterator also gives you the ability to remove an element while iterating while
Enumeration doesn’t allow that.
hint: A Map, which uses the == equality operator to check equality instead of the
equals() method.
hint: A pool of String literals. Remember it's moved to heap from perm gen space in JDK
7.
10
hint: this refers to the current instance while super refers to an instance of the
superclass.
hint: Comparator defines custom ordering while Comparable defines the natural order
of objects, e.g. the alphabetic order for String. See The Complete Java MasterClass to
learn more about sorting in Java.
hint: former contains both date and time while later contains only date part.
46) Why wait and notify methods are declared in Object class in Java? (answer)
hint: It doesn’t support because of a bad experience with C++, but with Java 8, it does in
some sense — only multiple inheritances of Type are not supported in Java now.
hint: In case of checked, you must handle exception using catch block, while in case of
unchecked, it’s up to you; compile will not bother you.
13
hint: both are errors that occur in a concurrent application, one occurs because of
thread scheduling while others occur because of poor coding. See Multithreading and
Parallel Computing in Java to learn more about deadlock, Race Conditions, and other
multithreading issues.
14
● public: Public is an access modifier, which is used to specify who can access this
method. Public means that this Method will be accessible by any Class.
● static: It is a keyword in java which identifies it is class-based. main() is made
static in Java so that it can be accessed without creating the instance of a Class. In
case, main is not made static then the compiler will throw an error as main() is
called by the JVM before any objects are made and only static methods can be
directly invoked via the class.
● void: It is the return type of the method. Void defines the method which will not
return any value.
● main: It is the name of the method which is searched by JVM as a starting point
for an application with a particular signature only. It is the method where the
main execution occurs.
15
Java is not 100% Object-oriented because it makes use of eight primitive data types such
as boolean, byte, char, int, float, double, long, short which are not objects.
1. Default Constructor: In Java, a default constructor is the one which does not take
any inputs. In other words, default constructors are the no argument constructors
which will be created by default in case you no other constructor is defined by the
user. Its main purpose is to initialize the instance variables with the default values.
Also, it is majorly used for object creation.
2. Parameterized Constructor: The parameterized constructor in Java, is the
constructor which is capable of initializing the instance variables with the
provided values. In other words, the constructors which take the arguments are
called parameterized constructors.
16
Q7. What is singleton class in Java and how can we make a class singleton?
Singleton class is a class whose only one instance can be created at any given time, in
one JVM. A class can be made singleton by making its constructor private.
Q8. What is the difference between Array list and vector in Java?
When you create a subclass instance, you’re also creating an instance of the parent class,
which is referenced to by the super reference variable.
Q12. What are the differences between HashMap and HashTable in Java?
18
Reflection is a runtime API for inspecting and changing the behavior of methods, classes,
and interfaces. Java Reflection is a powerful tool that can be really beneficial. Java
Reflection allows you to analyze classes, interfaces, fields, and methods during runtime
without knowing what they are called at compile time. Reflection can also be used to
create new objects, call methods, and get/set field values. External, user-defined classes
can be used by creating instances of extensibility objects with their fully-qualified
names. Debuggers can also use reflection to examine private members of classes.
The Non-Serialized attribute can be used to prevent member variables from being
serialized.
You should also make an object that potentially contains security-sensitive data
non-serializable if possible. Apply the Non-Serialized attribute to certain fields that store
sensitive data if the object must be serialized. If you don’t exclude these fields from
serialization, the data they store will be visible to any programs with serialization
permission.
Yes, we can call a constructor of a class inside another constructor. This is also called as
constructor chaining. Constructor chaining can be done in 2 ways-
19
1. Within the same class: For constructors in the same class, the this() keyword can
be used.
2. From the base class: The super() keyword is used to call the constructor from the
base class.
The constructor chaining follows the process of inheritance. The constructor of
the sub class first calls the constructor of the super class. Due to this, the creation
of sub class’s object starts with the initialization of the data members of the super
class. The constructor chaining works similarly with any number of classes. Every
constructor keeps calling the chain till the top of the chain.
Q16. Contiguous memory locations are usually used for storing actual values in an array
but not in ArrayList. Explain.
An array generally contains elements of the primitive data types such as int, float, etc. In
such cases, the array directly stores these elements at contiguous memory locations.
While an ArrayList does not contain primitive data types. An arrayList contains the
reference of the objects at different memory locations instead of the object itself. That is
why the objects are not stored at contiguous memory locations.
Q17. How is the creation of a String using new() different from that of a literal?
When we create a string using new(), a new object is created. Whereas, if we create a
string using the string literal syntax, it may return an already existing object with the
same name.
Q18. Why is synchronization necessary? Explain with the help of a relevant example.
Java allows multiple threads to execute. They may be accessing the same variable or
object. Synchronization helps to execute threads one after another.
1
public synchronized void increment()
2
{
3
a++;
4
}
As we have synchronized this function, this thread can only use the object after the
previous thread has used it.
Double Brace Initialization is a Java term that refers to the combination of two
independent processes. There are two braces used in this. The first brace creates an
anonymous inner class. The second brace is an initialization block. When these both are
used together, it is known as Double Brace Initialization. The inner class has a reference
to the enclosing outer class, generally using the ‘this’ pointer. It is used to do both
creation and initialization in a single statement. It is generally used to initialize
collections. It reduces the code and also makes it more readable.
Q20. Why is it said that the length() method of String class doesn’t return accurate
results?
The length() method of String class doesn’t return accurate results because
it simply takes into account the number of characters within in the String. In other
words, code points outside of the BMP (Basic Multilingual Plane), that is, code points
having a value of U+10000 or above, will be ignored.
The reason for this is historical. One of Java’s original goals was to consider all text as
Unicode; yet, Unicode did not define code points outside of the BMP at the time. It was
too late to modify char by the time Unicode specified such code points.
Q21. What are the differences between Heap and Stack Memory in Java?
21
JIT stands for Just-In-Time compiler in Java. It is a program that helps in converting the
Java bytecode into instructions that are sent directly to the processor. By default, the JIT
compiler is enabled in Java and is activated whenever a Java method is invoked. The JIT
compiler then compiles the bytecode of the invoked method into native machine code,
compiling it “just in time” to execute. Once the method has been compiled, the JVM
summons the compiled code of that method directly rather than interpreting it. This is
why it is often responsible for the performance optimization of Java applications at the
run time.
1. Default
2. Private
3. Protected
4. Public
A class in Java is a blueprint which includes all your data. A class contains fields
(variables) and methods to describe the behavior of an object. Let’s have a look at the
syntax of a class.
1
class Abc {
2
member variables // class body
3
methods}
An object is a real-world entity that has a state and behavior. An object has three
characteristics:
1. State
2. Behavior
3. Identity
Q30. What is the difference between a local variable and an instance variable?
In Java, a local variable is typically used inside a method, constructor, or a block and has
only local scope. Thus, this variable can be used only within the scope of a block. The
best benefit of having a local variable is that other methods in the class won’t be even
aware of that variable.
Example
1
if(x > 100)
2
{
3
String test = "Edureka";
4
}
Whereas, an instance variable in Java, is a variable which is bounded to its object itself.
These variables are declared within a class, but outside a method. Every object of that
class will create it’s own copy of the variable while using it. Thus, any changes made to
the variable won’t reflect in any other instances of that class and will be bound to that
particular instance only.
1
class Test{
2
public String EmpName;
3
public int empAge;
4
}
Q31. Differentiate between the constructors and methods in Java?
25
In case you are facing any challenges with these Core Java interview questions, please
comment on your problems in the section below.
● final variable
When the final keyword is used with a variable then its value can’t be changed once
assigned. In case the no value has been assigned to the final variable then using only the
class constructor a value can be assigned to it.
● final method
When a method is declared final then it can’t be overridden by the inheriting class.
● final class
When a class is declared as final in Java, it can’t be extended by any subclass class but it
can extend other class.
Example break:
1
2 for (int i = 0; i < 5; i++)
3 {
4
5 if (i == 3)
6
{
7
8 break;
System.out.println(i);
}
Example continue:
1
2 for (int i = 0; i < 5; i++)
3 {
4
5 if(i == 2)
6
{
7
8 continue;
System.out.println(i);
27
}
Q34. What is an infinite loop in Java? Explain with an example.
An infinite loop is an instruction sequence in Java that loops endlessly when a
functional exit isn’t met. This type of loop can be the result of a programming
error or may also be a deliberate action based on the application behavior. An
infinite loop will terminate automatically once the application exits.
For example:
2 {
4 for(;;)
5 System.out.println("Welcome to Edureka!");
7 }
8 }
Java String pool refers to a collection of Strings which are stored in heap
memory. In this, whenever a new object is created, String pool first checks
whether the object is already present in the pool or not. If it is present, then the
same reference is returned to the variable else new object will be created in the
String pool and the respective reference will be returned.
1. Bootstrap ClassLoader
2. Extension ClassLoader
3. System/Application ClassLoader
Q45. What is collection class in Java? List down its methods and interfaces.
In Java, the collection is a framework that acts as an architecture for storing and
manipulating a group of objects. Using Collections you can perform various tasks
like searching, sorting, insertion, manipulation, deletion, etc. Java collection
framework includes the following:
● Interfaces
● Classes
● Methods
The below image shows the complete hierarchy of the Java Collection.
1
2 class Car {
3 void run()
4
5 {
6
System.out.println(“car is running”);
7
8 }
9
10 }
11
class Audi extends Car {
12
13 void run()
14
15 {
16
System.out.prinltn(“Audi is running safely with 100km”);
17
33
b.run();
}
Q3. What is abstraction in Java?
Abstraction refers to the quality of dealing with ideas rather than events. It
basically deals with hiding the details and showing the essential things to the
user. Thus you can say that abstraction in Java is the process of hiding the
implementation details from the user and revealing only the functionality to
them. Abstraction can be achieved in two ways:
A class which inherits the properties is known as Child Class whereas a class
whose properties are inherited is known as Parent class.
1
2 class Adder {
3 Static int add(int a, int b)
4
5 {
6
return a+b;
7
8 }
9
10 Static double add( double a, double b)
11
{
12
13 return a+b;
14
}
36
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Method Overriding:
● In Method Overriding, the subclass has the same method with the same
name and exactly the same number and type of parameters and same
return type as a superclass.
● Method Overriding is to “Change” existing behavior of the method.
● It is a run time polymorphism.
● The methods must have the same signature.
● It always requires inheritance in Method Overriding.
1
2 class Car {
3 void run(){
4
5 System.out.println(“car is running”);
6
}
7
8 Class Audi extends Car{
9
10 void run()
11
{
12
13 System.out.prinltn("Audi is running safely with 100km");
14
15 }
b.run();
}
Q9. Can you override a private or static method in Java?
You cannot override a private or static method in Java. If you create a similar
method with the same return type and same method arguments in child class
then it will hide the superclass method; this is known as method hiding.
Similarly, you cannot override a private method in subclass because it’s not
accessible there. What you can do is create another private method with the
same name in the child class. Let’s take a look at the example below to
understand it better.
1
2 class Base {
3 private static void display() {
4
5 System.out.println("Static or class method from Base");
6
}
7
8 public void print() {
9
10 System.out.println("Non-static or instance method from Base");
11
}
12
13 class Derived extends Base {
14
15 private static void display() {
16
System.out.println("Static or class method from Derived");
17
18 }
38
19
20 public void print() {
21 System.out.println("Non-static or instance method from Derived");
22
}
obj1.display();
obj1.print();
}
Q10. What is multiple inheritance? Is it supported by Java?
The problem with multiple inheritance is that if multiple parent classes have the
same method name, then at runtime it becomes difficult for the compiler to
decide which method to execute from the child class.
39
In case you are facing any challenges with these java interview questions, please
comment on your problems in the section below.
A Marker interface can be defined as the interface having no data member and
member functions. In simpler terms, an empty interface is called the Marker
interface. The most common examples of Marker interface in Java are
Serializable, Cloneable etc. The marker interface can be declared as follows.
1
2 public interface Serializable{
}
Q16. What is object cloning in Java?
the number of parameters and their types in the list to differentiate the
overloaded constructors.
1
2 class Demo
3 {
4
5 int i;
6
public Demo(int a)
7
8 {
9
10 i=k;
11
}
12
public Demo(int a, int b)
//body
}
In case you are facing any challenges with these java interview questions, please
comment on your problems in the section below. Apart from this Java Interview
Questions Blog, if you want to get trained from professionals on this technology,
you can opt for a structured training from edureka!
1.void forward()
2.void include()
Q4. What are the differences between forward() method and sendRedirect()
methods?
While exceptions are conditions that occur because of bad input or human error
etc. e.g. FileNotFoundException will be thrown if the specified file does not exist.
Or a NullPointerException will take place if you try using a null reference. In most
of the cases it is possible to recover from an exception (probably by giving the
user feedback for entering proper values etc.
1. try
2. catch
3. finally
4. throw
5. throws
Q3. What are the differences between Checked Exception and Unchecked
Exception?
Checked Exception
● The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions.
● Checked exceptions are checked at compile-time.
44
Unchecked Exception
● The classes that extend RuntimeException are known as unchecked
exceptions.
● Unchecked exceptions are not checked at compile-time.
● Example: ArithmeticException, NullPointerException etc.
This creates a thread by creating an instance of a new class that extends the
Thread class. The extending class must override the run() function, which is the
thread’s entry point.
This is the easiest way to create a thread, by creating a class that implements the
runnable interface. After implementing the runnable interface, the class must
implement the public void run() method ()
The run() method creates a parallel thread in your programme. When run()
returns, the thread will come to an end.
The run() method creates a parallel thread in your programme. When run()
returns, the thread will come to an end.
Within the run() method, you must specify the thread’s code.
Like any other method, the run() method can call other methods, use other
classes, and define variables.
Java is always pass-by-value. This means that it creates a copy of the contents of
the parameter in memory. In Java, object variables always refer to the memory
heap’s real object.
Q5. Will the finally block get executed when the return statement is written at
the end of try block and catch block as shown below?
The finally block always gets executed even hen the return statement is written
at the end of the try block and the catch block. It always executes , whether
there is an exception or not. There are only a few situations in which the finally
block does not execute, such as VM crash, power failure, software crash, etc. If
you don’t want to execute the finally block, you need to call the System.exit()
method explicitly in the finally block.
New-
When a thread is created, and before the program starts the thread, it is in the
new state. It is also referred to as a born thread.
Runnable
When a thread is started, it is in the Runnable state. In this state, the thread is
executing its task.
Waiting
46
Sometimes, a thread goes to the waiting state, where it remains idle because
another thread is executing. When the other thread has finished, the waiting
thread again comes into the running state.
Timed Waiting
In timed waiting, the thread goes to waiting state. But, it remains in waiting state
for only a specified interval of time after which it starts executing.It remains
waiting either till the time interval ends or till the other thread has finished.
Terminated
Q8. What purpose do the keywords final, finally, and finalize fulfill?
Final:
Final is used to apply restrictions on class, method, and variable. A final class
can’t be inherited, final method can’t be overridden and final variable value
can’t be changed. Let’s take a look at the example below to understand it better.
1
2 class FinalVarExample {
3 public static void main( String args[])
4
5 {
6
final int a=10; // Final variable
}
Finally
Finally is used to place important code, it will be executed whether the exception
is handled or not. Let’s take a look at the example below to understand it better.
47
1
2 class FinallyExample {
3 public static void main(String args[]){
4
5 try {
6
int x=100;
7
8 }
9
10 catch(Exception e) {
11
System.out.println(e);
12
}
finally {
}}
}
Finalize
Finalize is used to perform clean up processing just before the object is garbage
collected. Let’s take a look at the example below to understand it better.
1
2 class FinalizeExample {
3 public void finalize() {
4
5 System.out.println("Finalize is called");
6
}
7
8 public static void main(String args[])
9
10 {
11
FinalizeExample f1=new FinalizeExample();
48
12
13 FinalizeExample f2=new FinalizeExample();
f1= NULL;
f2=NULL;
System.gc();
}
Q9. What are the differences between throw and throws?
In case you are facing any challenges with these java interview questions, please
comment on your problems in the section below.
Q10. What is exception hierarchy in java?
The hierarchy is as follows:
Throwable is a parent class of all Exception classes. There are two types of
Exceptions: Checked exceptions and UncheckedExceptions or
RunTimeExceptions. Both type of exceptions extends Exception class whereas
errors are further classified into Virtual Machine error and Assertion error.
49
Q14. What is a finally block? Is there a case when finally will not execute?
Finally block is a block which always executes a set of statements. It is always
associated with a try block regardless of any exception that occurs or not.
Yes, finally will not be executed if the program exits either by calling
System.exit() or by causing a fatal error that causes the process to abort.
Q16. Can we write multiple catch blocks under single try block?
Yes we can have multiple catch blocks under single try block but the approach
should be from specific to general. Let’s understand this with a programmatic
example.
1
2 public class Example {
3 public static void main(String args[]) {
4
5 try {
6
int a[]= new int[10];
7
8 a[10]= 10/0;
9
10 }
11
catch(ArithmeticException e)
12
13 {
14
15 System.out.println("Arithmetic exception in first catch block");
52
16
17 }
18 catch(ArrayIndexOutOfBoundsException e)
19
{
catch(Exception e)
}
Q17. What are the important methods of Java Exception Class?
Methods are defined in the base class Throwable. Some of the important
methods of Java exception class are stated below.
1. String getMessage() – This method returns the message String about the
exception. The message can be provided through its constructor.
2. public StackTraceElement[] getStackTrace() – This method returns an
array containing each element on the stack trace. The element at index 0
represents the top of the call stack whereas the last element in the array
represents the method at the bottom of the call stack.
3. Synchronized Throwable getCause() – This method returns the cause of
the exception or null id as represented by a Throwable object.
4. String toString() – This method returns the information in String format.
The returned String contains the name of Throwable class and localized
message.
5. void printStackTrace() – This method prints the stack trace information to
the standard error stream.
Secured Feature: Java has a secured feature that helps develop a virus-free and
tamper-free system for the users.
OOP: OOP stands for Object-Oriented Programming language. OOP signifies that,
in Java, everything is considered an object.
In Java, when you declare primitive datatypes, then Wrapper classes are
responsible for converting them into objects(Reference types).
18. What is a singleton class in Java? And How to implement a singleton class?
A class that can possess only one object at a time is called a singleton class. To
implement a singleton class given steps are to be followed:
The package is a collective bundle of classes and interfaces and the necessary
libraries and JAR files. The use of packages helps in code reusability.
For instance, variables are declared inside a class, and the scope of variables in
javascript is limited to only a specific object.
The term final is a predefined word in Java that is used while declaring values to
variables. When a value is declared using the final keyword, then the variable's
value remains constant throughout the program's execution.
When the main method is not declared as static, then the program may be
compiled correctly but ends up with a severe ambiguity and throws a run time
error that reads "NoSuchMethodError."
One of the most well-known and widely used programming languages is Java. It
is a programming language that is independent of platforms. Java doesn't
demand that the complete programme be rewritten for every possible platform.
The Java Virtual Machine and Java Bytecode are used to support platform
independence. Any JVM operating system can run this platform-neutral byte
code. The application is run after JVM translates the byte code into machine
code. Because Java programmes can operate on numerous systems without
having to be individually rewritten for each platform, the language is referred to
as "Write Once, Run Anywhere" (WORA).
Java's main() function is static by default, allowing the compiler to call it either
before or after creating a class object. The main () function is where the compiler
begins programme execution in every Java programme. Thus, the main ()
method needs to be called by the compiler. If the main () method is permitted to
be non-static, the JVM must instantiate its class when calling the function.
28. What part of memory - Stack or Heap - is cleaned in the garbage collection
process?
57
29. What is the difference between the program and the process?
30. What are the differences between constructor and method of a class in Java?
31. Which among String or String Buffer should be preferred when there are a
lot of updates required to be done in the data?
32. What happens if the static modifier is not included in the main method
signature in Java?
The main function is called by the JVM even before the objects are created, thus
even if the code correctly compiles, there will still be an error at runtime.
58
34. What happens if there are multiple main methods inside one class in Java?
There is no limit to the number of major approaches you can use. Overloading is
the ability to have main methods with different signatures than main (String []),
and the JVM will disregard those main methods.
In the event that an exception is not caught, it is initially thrown from the top of
the stack and then moves down the call stack to the preceding method. The
runtime system looks for a way to handle an exception that a method throws.
The ordered list of methods that were called to get to the method where the
error occurred is the collection of potential "somethings" that can be used to
manage the exception. The call stack is the list of methods, and exception
propagation is the search technique.
If you don't deal with an exception once it occurs, the programme will end
abruptly and the code after the line where the exception occurred won't run.
Each attempt block does not necessarily have to be followed by a catch block.
Either a catch block or a final block ought to come after it. Additionally, any
59
Yes, a class may include any number of constructors, and each function Object ()
{[native code] } may call the others using the this() function Object() { [native
code] } call function [please do not mix the this() function Object() { [native
code] } call function with this keyword]. The constructor's first line should be
either this () or this(args). Overloading of constructors is what this is called.
39. Contiguous memory locations are usually used for storing actual values in an
array but not in ArrayList. Explain.
Primitive data types like int, float, and others are typically present in an array. In
such circumstances, the array immediately saves these elements at contiguous
memory regions. While an ArrayList does not contain primitive data types.
Instead of the actual object, an ArrayList includes the references to the objects'
many locations in memory. The objects are not kept in consecutive memory
regions because of this.
The distance from the array's beginning is just an offset. There is no distance
because the first element is at the beginning of the array. Consequently, the
offset is 0.
41. Why is the remove method faster in the linked list than in an array?
42. How many overloaded add() and addAll() methods are available in the List
interface? Describe the need and uses.
List is an interface in the Java Collections Framework. The add() and addAll()
methods are the main methods at the List interface. The add() method is used
to add an element to the list, while the addAll() method is used to add a
collection of elements to the list.
The List interface contains two overloaded versions of the add() method:
The first add() method accepts a single argument of type E, the element to be
added to the list.
The List interface also contains two overloaded versions of the addAll() method:
The first addAll() method accepts a single argument of type Collection<? Extends
E>, which is the collection of elements to be added to the list.
43. How does the size of ArrayList grow dynamically? And also state how it is
implemented internally?
Aggregation (HAS-A) and composition are its two forms (Belongs-to). In contrast
to composition, which has a significant correlation, the aggregation has a very
modest association. Aggregation can be thought of as a more confined version of
the composition. Since all compositions are aggregates but not all aggregates are
compositions, aggregate can be thought of as the superset of composition.
46. How is the creation of a String using new() different from that of a literal?
The new () operator always produces a new object in heap memory when
creating a String object. The String pool may return an existing object if we build
an object using the String literal syntax, such as "Baeldung," on the other hand.
47. How is the ‘new' operator different from the ‘newInstance()' operator in
java?
Both the new operator and the newInstance() method are used to create objects
in Java. If we already know the kind of object to create, we can use the new
62
Yes, even with a garbage collector in place, the programme could still run out of
memory. Garbage collection aids in identifying and removing programme objects
that are no longer needed in order to release the resources they use. When an
object in a programme cannot be reached, trash collection is executed with
respect to that object. If there is not enough memory available to create new
objects, a garbage collector is used to free up memory for things that have been
removed from the scope. When the amount of memory released is insufficient
for the creation of new objects, the program's memory limit is exceeded.
System.out.println() in Java outputs the argument that was supplied to it. On the
monitor, the println() method displays the findings. An objectname is typically
used to call a method.
A thread can be in any of the following states in Java. These are the states:
● New: A new thread is always in the new state when it is first formed.
The function hasn't been run yet, thus it hasn't started to execute for a
thread in the new state.
● Active: A thread switches from the new state to the active state when
it calls the start() method. The runnable state and the running state are
both contained within the active state.
● Blocked or Waiting: A thread is either in the blocked state or the
waiting state when it is inactive for a while (but not indefinitely).
● Timed waiting: When we use the sleep () method on a particular
thread, we are actually engaging in timed waiting. The thread enters
the timed wait state using the sleep () function. The thread awakens
when the allotted time has passed and resumes execution where it left
off.
● Termination: A thread that has been terminated means it is no longer
active in the system. In other words, the thread is inactive and cannot
be revived (made active again after being killed).
52. What could be the tradeoff between the usage of an unordered array versus
the usage of an ordered array?
53. Is it possible to import the same class or package twice in Java and what
happens to it during runtime?
The same package or class may be imported more than once. Neither the JVM
nor the compiler raise an objection. Even if you import the same class several
times, the JVM will only internally load it once.
54. In case a package has sub packages, will it suffice to import only the main
package? e.g. Does importing of com.myMainPackage.* also import
com.myMainPackage.mySubPackage.*?
55. Will the final block be executed if the code System.exit(0) is written at the
end of the try block?
The system is established as the last line to be run, after which nothing will
happen, therefore both the catch and finally blocks are essentially ignored.
57. Why is it said that the length() method of String class doesn't return accurate
results?
65
Since this char [] array is used by the Java String class internally, the length
variable cannot be made public.
58. What are the possible ways of making objects eligible for garbage collection
(GC) in Java?
59. In the below Java Program, how many objects are eligible for garbage
collection?
I don't know about the program, but generally, three objects are eligible for
garbage collection.
The first object is created when the program is started and is no longer needed
when the program ends.
The second object is created when the user inputs their name and is no longer
required when the program ends.
The third object is created when the user inputs their address and is no longer
needed when the program ends.
60. What is the best way to inject dependency? Also, state the reason.
61. How we can set the spring bean scope. And what supported scopes does it
have?
There are four ways to set the scope of a Spring bean: singleton, prototype,
request, and session.
The singleton scope creates a single instance of a bean, which is shared by all
objects that request it.
The prototype scope creates a new instance of a bean for each object that
requests it.
The request and session scopes are only available in a web-based context. The
request scope creates a new bean instance for each HTTP request, and the
session scope creates a single instance of a bean shared by all objects in a single
HTTP session.
The three categories of Java design patterns are creational, structural, and
behavioural design patterns.
64. Assume a thread has a lock on it, calling the sleep() method on that thread
will release the lock?
No, the thread might release the locks using notify, notifyAll(), and wait()
methods.
class FibonacciExample2{
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
int count=10;
66. Write a Java program to check if the two strings are anagrams.
import java.util.Arrays;
if (s1.length() != s2.length()) {
status = false;
} else {
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
if (status) {
} else {
isAnagram("Keep", "Peek");
}
70
Output
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120
Output: 5
69. Write a Java Program to check if any number is a magic number or not. A
number is said to be a magic number if after doing the sum of digits in each step
and in turn doing the sum of digits of that sum, the ultimate result (when there
is only one digit left) is 1.
class GFG
71
int sum = 0;
if (n == 0)
n = sum;
sum = 0;
sum += n % 10;
72
n /= 10;
// Driver code
int n = 1234;
if (isMagic(n))
System.out.println("Magic Number");
else
}
73
super(str);
else {
System.out.println("welcome to vote");
// main method
try
validate(13);
71. Write a Java program to rotate arrays 90 degree clockwise by taking matrices
from user input.
//matrix to rotate
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
System.out.print(" "+a[i][j]+"\t");
System.out.println("\n");
for(int i=0;i<3;i++)
for(int j=2;j>=0;j--)
77
System.out.print(""+a[j][i]+"\t");
System.out.println("\n");
72. Write a java program to check if any number given as input is the sum of 2
prime numbers.
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
// is prime or not
bool isPrime(int n)
if (n <= 1)
return false;
if (n % i == 0)
return false;
return true;
bool isPossible(int N)
79
return true;
else
return false;
// Driver code
int main()
int n = 13;
if (isPossible(n))
printf("%s", "Yes");
else
80
printf("%s", "No");
return 0;
73. Write a Java program for solving the Tower of Hanoi Problem.
class GFG
if (n == 1)
return;
}
81
// Driver method
import java.util.*;
// Main class
82
class GFG {
// Method 1
// overflow of indices
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
83
if (arr[mid] > x)
// in right subarray
// array
return -1;
// Method 2
// Length of array
int n = arr.length;
int x = 10;
// Element present
if (result == -1)
// Print statement
85
else
// Print statement
+ result);
No, these keywords do not exist in Java. Delete, Next, Exit are the operations
performed in the Java program, Main is the predefined method, and Null is the
default String type.
With this we are done with the first section that is Basic Java Interview Question,
Now, lets move on to our next section of Intermediate Java Interview Questions.
Now, let's have a look at some of the most asked Java technical interview
questions for intermediate experienced professionals.
86
JVM has a Just in Time (JIT) compiler tool that converts all the Java source code
into the low-level compatible machine language. Therefore, it runs faster than
the regular application.
JRE has class libraries and other JVM supporting files. But it doesn’t have any
tool for java development such as compiler or debugger.
JDK has tools that are required to write Java Programs and uses JRE to execute
them. It has a compiler, Java application launcher, and an applet viewer.
JIT compiler refers to Just in Time compiler. It is the simplest way of executing
the computer code that takes in compilation during the execution of a program
rather than before performance. It commonly uses bytecode translation to
machine code. It is then executed directly.
79. What are Brief Access Specifiers and Types of Access Specifiers?
Access Specifiers are predefined keywords used to help JVM understand the
scope of a variable, method, and class. We have four access specifiers.
87
Yes, A constructor can return a value. It replaces the class's current instance
implicitly; you cannot make a constructor return a value explicitly.
The process of creating multiple method signatures using one method name is
called Method Overloading in Java. Two ways to achieve method overloading
are:
No, Java does not support the Overloading of a static method. The process
would throw an error reading "static method cannot be referenced."
Binding is a process of unifying the method call with the method's code
segment. Late binding happens when the method's code segment is unknown
until it is called during the runtime.
The Dynamic method dispatch is a process where the method call is executed
during the runtime. A reference variable is used to call the super-class. This
process is also known as Run-Time Polymorphism.
88. Why is the delete function faster in the linked list than an array?
Delete Function is faster in linked lists in Java as the user needs to make a minor
update to the pointer value so that the node can point to the next successor in
the list
89
● >> operator does the job of right shifting the sign bits
● >>> operator is used in shifting out the zero-filled bits
1. Initialization
2. Start
3. Stop
4. Destroy
5. Paint
The Externalizable interface helps with control over the process of serialization.
An "externalisable" interface incorporates readExternal and writeExternal
methods.
The Daemon thread can be defined as a thread with the least priority. This
Daemon thread is designed to run in the background during the Garbage
Collection in Java.
97. Can you run a code before executing the main method?
Yes, we can execute any code, even before the main method. We will be using a
static block of code when creating the objects at the class's load time. Any
statements within this static block of code will get executed at once while
loading the class, even before creating objects in the main method.
91
The finalize method is called the Garbage collector. For every object, the
Garbage Collector calls the finalize() method just for one time.
Now, lets move on to our last section of Advanced Core Java Interview Questions
which is primarly useful for experienced and working professionals.
No, "this" and "super" keywords should be used in the first statement in the
class constructor. The following code gives you a brief idea.
baseClass() {
super();
this();
JSP is an abbreviation for Java Servlet Page. The JSP page consists of two types of
text.
● Static Data
● JSP elements
Directives are instructions processed by JSP Engine. After the JSP page is
compiled into a Servlet, Directives set page-level instructions, insert external
files, and define customized tag libraries. Directives are defined using the
symbols below:
start with "< %@" and then end with "% >"
● Include directive
93
It includes a file and combines the content of the whole file with the currently
active pages.
● Page directive
Page Directive defines specific attributes in the JSP page, like the buffer and
error page.
● Taglib
Objects that inherit the "Observable class" take care of a list of "observers."
When an Observable object gets upgraded, it calls the update() method of each
of its observers.
After that, it notifies all the observers that there is a change of state.
Q6) What are Loops in Java? What are three types of loops?
Ans: Looping is used in programming to execute a statement or a block of statement
repeatedly. There are three types of loops in Java:
1) For Loops
For loops are used in java to execute statements repeatedly for a given number of times.
For loops are used when number of times to execute the statements is known to
programmer.
2) While Loops
While loop is used when certain statements need to be executed repeatedly until a
condition is fulfilled. In while loops, condition is checked first before execution of
statements.
3) Do While Loops
Do While Loop is same as While loop with only difference that condition is checked after
execution of block of statements. Hence in case of do while loop, statements are
executed at least once.
95
if (counter == 4) {
break;
}
In the below example when counter reaches 4, loop jumps to next iteration and any
statements after the continue keyword are skipped for current iteration.
for (counter = 0; counter < 10; counter++)
system.out.println(counter);
if (counter == 4) {
96
continue;
}
system.out.println("This will not get printed when counter is 4");
}
Q9) What is the difference between double and float variables in Java?
Ans: In java, float takes 4 bytes in memory while Double takes 8 bytes in memory. Float
is single precision floating point decimal number while Double is double precision
decimal number.
Q14) What’s the base class in Java from which all classes are derived?
Ans: java.lang.object
Ans: In java, main() method can’t return any data and hence, it’s always declared with a
void return type.
Q17) Can we declare a class as Abstract without having any abstract method?
Ans: Yes we can create an abstract class by using abstract keyword before class name
even if it doesn’t have any abstract method. However, if a class has even one abstract
method, it must be declared as abstract otherwise it will give an error.
Q18) What’s the difference between an Abstract Class and Interface in Java?
Ans: The primary difference between an abstract class and interface is that an interface
can only possess declaration of public static methods with no concrete implementation
while an abstract class can have members with any access specifiers (public, private etc)
with or without concrete implementation.
Another key difference in the use of abstract classes and interfaces is that a class which
implements an interface must implement all the methods of the interface while a class
which inherits from an abstract class doesn’t require implementation of all the methods
of its super class.
A class can implement multiple interfaces but it can extend only one abstract class.
Q19) What are the performance implications of Interfaces over abstract classes?
Ans: Interfaces are slower in performance as compared to abstract classes as extra
indirections are required for interfaces. Another key factor for developers to take into
consideration is that any class can extend only one abstract class while a class can
implement many interfaces.
Use of interfaces also puts an extra burden on the developers as any time an interface is
implemented in a class; developer is forced to implement each and every method of
interface.
99
Q22) How can we pass argument to a function by reference instead of pass by value?
Ans: In java, we can pass argument to a function only by value and not by reference.
Q25) Is it compulsory for a Try Block to be followed by a Catch Block in Java for
Exception handling?
Ans: Try block needs to be followed by either Catch block or Finally block or both. Any
exception thrown from try block needs to be either caught in the catch block or else any
specific tasks to be performed before code abortion are put in the Finally block.
100
Q26) Is there any way to skip Finally block of exception even if some exception occurs
in the exception block?
Ans: If an exception is raised in Try block, control passes to catch block if it exists
otherwise to finally block. Finally block is always executed when an exception occurs and
the only way to avoid execution of any statements in Finally block is by aborting the code
forcibly by writing following line of code at the end of try block:
System.exit(0);
const_example() {
system.out.println("Inside constructor");
}
public static void main(String args[]) {
Ans: We cannot override static methods. Static methods belong to a class and not to
individual objects and are resolved at the time of compilation (not at runtime).Even if we
try to override static method, we will not get an complitaion error,nor the impact of
overriding when running the code.
super.displayResult();
obj.displayResult();
}
102
Q32) In the below example, how many String Objects are created?
String s1="I am Java Expert";
Q38) When a lot of changes are required in data, which one should be a preference to
be used? String or StringBuffer?
Ans: Since StringBuffers are dynamic in nature and we can change the values of
StringBuffer objects unlike String which is immutable, it’s always a good choice to use
StringBuffer when data is being changed too much. If we use String in such a case, for
every data change a new String object will be created which will be an extra overhead.
Q39) What’s the purpose of using Break in each case of Switch Statement?
Ans: Break is used after each case (except the last one) in a switch so that code breaks
after the valid case and doesn’t flow in the proceeding cases too.
If break isn’t used after each case, all cases after the valid case also get executed
resulting in wrong results.
Q41) How we can execute any code even before main method?
Ans: If we want to execute any statements before even creation of objects at load time
of class, we can use a static block of code in the class. Any statements inside this static
block of code will get executed once at the time of loading the class even before creation
of objects in the main method.
Q42) Can a class be a super class and a sub-class at the same time? Give example.
Ans: If there is a hierarchy of inheritance used, a class can be a super class for another
class and a sub-class for another one at the same time.
In the example below, continent class is sub-class of world class and it’s super class of
country class.
public class world {
..........
}
public class continenet extends world {
............
}
public class country extends continent {
......................
Q43) How objects of a class are created if no constructor is defined in the class?
Ans: Even if no explicit constructor is defined in a java class, objects get created
successfully as a default constructor is implicitly used for object creation. This
constructor has no parameters.
105
Q44) In multi-threading how can we ensure that a resource isn’t used by multiple
threads simultaneously?
Ans: In multi-threading, access to the resources which are shared among multiple
threads can be controlled by using the concept of synchronization. Using synchronized
keyword, we can ensure that only one thread can use shared resource at a time and
others can get control of the resource only once it has become free from the other one
using it.
Q45) Can we call the constructor of a class more than once for an object?
Ans: Constructor is called automatically when we create an object using new keyword.
It’s called only once for an object at the time of object creation and hence, we can’t
invoke the constructor again for an object after its creation.
Q46) There are two classes named classA and classB. Both classes are in the same
package. Can a private member of classA can be accessed by an object of classB?
Ans: Private members of a class aren’t accessible outside the scope of that class and any
other class even in the same package can’t access them.
Q47) Can we have two methods in a class with the same name?
Ans: We can define two methods in a class with the same name but with different
number/type of parameters. Which method is to get invoked will depend upon the
parameters passed.
For example in the class below we have two print methods with same name but
different parameters. Depending upon the parameters, appropriate one will be called:
public class methodExample {
obj1.print();
obj1.print("xx");
Q50) What’s the default access specifier for variables and methods of a class?
Ans: Default access specifier for variables and method is package protected i.e variables
and class is available to any other class but in the same package, not outside the
package.
107
Q52) How can we restrict inheritance for a class so that no class can be inherited from
it?
Ans: If we want a class not to be extended further by any class, we can use the keyword
Final with the class name.
In the following example, Stone class is Final and can’t be extend
public Final Class Stone {
// Class methods and Variables
}
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Ans: If we want certain variables of a class not to be serialized, we can use the keyword
transient while declaring them. For example, the variable trans_var below is a transient
variable and can’t be serialized:
public class transientExample {
private transient trans_var;
// rest of the code
}
Q60) Can we override a method by using same method name and arguments but
different return types?
Ans: The basic condition of method overriding is that method name, arguments as well
as return type must be exactly same as is that of the method being overridden. Hence
using a different return type doesn’t override a method.
int x = 4;
system.out.println(x++);
}
}
Ans: In this case postfix ++ operator is used which first returns the value and then
increments. Hence it’s output will be 4.
Q61) A person says that he compiled a java class successfully without even having a
main method in it? Is it possible?
Ans: main method is an entry point of Java class and is required for execution of the
program however; a class gets compiled successfully even if it doesn’t have a main
method. It can’t be run though.
Q63) What are the two environment variables that must be set in order to run any
Java programs?
110
Ans: Java programs can be executed in a machine only once following two environment
variables have been properly set:
1. PATH variable
2. CLASSPATH variable
Q65) Can a class in Java be inherited from more than one class?
Ans: In Java, a class can be derived from only one class and not from multiple classes.
Multiple inheritances is not supported by Java.
Q66) Can a constructor have different name than a Class name in Java?
Ans: Constructor in Java must have same name as the class name and if the name is
different, it doesn’t act as a constructor and compiler thinks of it as a normal method.
Ans: The above class declaration is incorrect as an abstract class can’t be declared as
Final.
Q72) What’s the difference between comparison done by equals method and ==
operator?
Ans: In Java, equals() method is used to compare the contents of two string objects and
returns true if the two have same value while == operator compares the references of
two string objects.
In the following example, equals() returns true as the two string objects have same
values. However == operator returns false as both string objects are referencing to
different objects:
public class equalsTest {
if (str1.equals(str2))
}
112
if (str1 == str2) {
} else
Q73) Is it possible to define a method in Java class but provide it’s implementation in
the code of another language like C?
Ans: Yes, we can do this by use of native methods. In case of native method based
development, we define public static methods in our Java class without its
implementation and then implementation is done in another language like C separately.
Ans: No a variable can’t be static as well as local at the same time. Defining a local
variable as static gives compilation error.
Q77) In a class implementing an interface, can we change the value of any variable
defined in the interface?
Ans: No, we can’t change the value of any variable of an interface in the implementing
class as all variables defined in the interface are by default public, static and Final and
final variables are like constants which can’t be changed later.
Q78) Is it correct to say that due to garbage collection feature in Java, a java program
never goes out of memory?
Ans: Even though automatic garbage collection is provided by Java, it doesn’t ensure
that a Java program will not go out of memory as there is a possibility that creation of
Java objects is being done at a faster pace compared to garbage collection resulting in
filling of all the available memory resources.
So, garbage collection helps in reducing the chances of a program going out of memory
but it doesn’t ensure that.
Q79) Can we have any other return type than void for main method?
Ans: No, Java class main method can have only void return type for the program to get
successfully executed.
Nonetheless , if you absolutely must return a value to at the completion of main method
, you can use System.exit(int status)
Q80) I want to re-reach and use an object once it has been garbage collected. How it’s
possible?
114
Ans: Once an object has been destroyed by garbage collector, it no longer exists on the
heap and it can’t be accessed again. There is no way to reference it again.
Q81) In Java thread programming, which method is a must implementation for all
threads?
Ans: Run() is a method of Runnable interface that must be implemented by all threads.
Q82) I want to control database connections in my program and want that only one
thread should be able to make database connection at a time. How can I implement
this logic?
Ans: This can be implemented by use of the concept of synchronization. Database
related code can be placed in a method which hs synchronized keyword so that only one
thread can access it at a time.
Q86) How can we find the actual size of an object on the heap?
Ans: In java, there is no way to find out the exact size of an object on the heap.
Q87) Which of the following classes will have more memory allocated?
Class A: Three methods, four variables, no object
Class B: Five methods, three variables, no object
Ans: Memory isn’t allocated before creation of objects. Since for both classes, there are
no objects created so no memory is allocated on heap for any class.
{
116
@Override
return false;
@Override
return null;
Q91) Is there a way to increase the size of an array after its declaration?
Ans: Arrays are static and once we have specified its size, we can’t change it. If we want
to use such collections where we may require a change of size (no of items), we should
prefer vector over array.
117
Q92) If an application has multiple classes in it, is it okay to have a main method in
more than one class?
Ans: If there is main method in more than one classes in a java application, it won’t
cause any issue as entry point for any application will be a specific class and code will
start from the main method of that particular class only.
Q93) I want to persist data of objects for later use. What’s the best approach to do so?
Ans: The best way to persist data for future use is to use the concept of serialization.
Q95) String and StringBuffer both represent String objects. Can we compare String and
StringBuffer in Java?
Ans: Although String and StringBuffer both represent String objects, we can’t compare
them with each other and if we try to compare them, we get an error.
Q97) Can we cast any other type to Boolean Type with type casting?
Ans: No, we can neither cast any other primitive type to Boolean data type nor can cast
Boolean data type to any other primitive data type.
Q98) Can we use different return types for methods when overridden?
Ans: The basic requirement of method overriding in Java is that the overridden method
should have same name, and parameters.But a method can be overridden with a
different return type as long as the new return type extends the original.
118
A method(int x) {
//original method
B method(int x) {
//overridden method
Some of the famous pre-defined functional interfaces from previous Java versions are
Runnable, Callable, Comparator, and Comparable. While Java 8 introduces functional
interfaces like Supplier, Consumer, Predicate, etc. Please refer to the java.util.function
doc for other predefined functional interfaces and its description introduced in Java 8.
Runnable: use to execute the instances of a class over another thread with no
arguments and no return value.
Callable: use to execute the instances of a class over another thread with no arguments
and it either returns a value or throws an exception.
Operator: Perform a reduction type operation that accepts the same input types.
11. What is the lambda expression in Java and How does a lambda expression relate to
a functional interface?
Lambda expression is a type of function without a name. It may or may not have results
and parameters. It is known as an anonymous function as it does not have type
information by itself. It is executed on-demand. It is beneficial in iterating, filtering, and
extracting data from a collection.
122
As lambda expressions are similar to anonymous functions, they can only be applied to
the single abstract method of Functional Interface. It will infer the return type, type, and
several arguments from the signature of the abstract method of functional interface.
1. List of Arguments/Params:
(String name)
A list of params is passed in () round brackets. It can have zero or more params.
Declaring the type of parameter is optional and can be inferred for the context.
2. Arrow Token:
->
Arrow token is known as the lambda arrow operator. It is used to separate the
parameters from the body, or it points the list of arguments to the body. 3.
Expression/Body:
{
System.out.println("Hello "+name);
return "Hello "+name;
}
123
A body can have expressions or statements. {} curly braces are only required when there
is more than one line. In one statement, the return type is the same as the return type
of the statement. In other cases, the return type is either inferred by the return keyword
or void if nothing is returned.
15. What are the types and common ways to use lambda expressions?
A lambda expression does not have any specific type by itself. A lambda expression
receives type once it is assigned to a functional interface. That same lambda expression
can be assigned to different functional interface types and can have a different type.
Can be passed as a parameter that has a functional type —> stream.filter(s ->
s.isEmpty())
For e.g.:
isPresent(), which returns true if the value is present or else false and the method get(),
which will return the value if it is present.
It encapsulates optional values, i.e., null or not-null values, which helps in avoiding null
checks, which results in better, readable, and robust code It acts as a wrapper around
the object and returns an object instead of a value, which can be used to avoid run-time
NullPointerExceptions.
A Stream, which represents a sequence of data objects & series of operations on that
data is a data pipeline that is not related to Java I/O Streams does not hold any data
permanently.
22. What are the sources of data objects a Stream can process?
A Stream can process the following data:
● A collection of an Array.
● An I/O channel or an input device.
● A reactive source (e.g., comments in social media or tweets/re-tweets)
● A stream generator function or a static factory.
distinct() - Only pass on elements to the next stage, not passed yet.
25. What is the stateful intermediate operation? Give some examples of stateful
intermediate operations.
To complete some of the intermediate operations, some state is to be maintained, and
such intermediate operations are called stateful intermediate operations. Parallel
execution of these types of operations is complex.
Sending data elements to further steps in the pipeline stops till all the data is sorted for
sorted() and stream data elements are stored in temporary data structures.
findFirst() findAny()
Returns the first element in the Return any element from the
Stream Stream
Collections Streams
129
Data structure holds all the No data is stored. Have the capacity to
data elements process an infinite number of elements on
demand
29. What is the feature of the new Date and Time API in Java 8?
130
30. What are the important packages for the new Data and Time API?
● java.time
○ dates
○ times
○ Instants
○ durations
○ time-zones
○ periods
● Java.time.format
● Java.time.temporal
● java.time.zone
JAVA>jjs
jjs> quit()
>>