Java 8 ForEach Method With Example-Combined
Java 8 ForEach Method With Example-Combined
In Java 8, we have a newly introduced forEach method to iterate over collections and Streams in
Java. In this guide, we will learn how to use forEach() and forEachOrdered() methods to loop a
particular collection and stream.
1/5
Java 8 – forEach to iterate a Map
import [Link];
import [Link];
public class Example {
public static void main(String[] args) {
Map<Integer, String> hmap = new HashMap<Integer, String>();
[Link](1, "Monkey");
[Link](2, "Dog");
[Link](3, "Cat");
[Link](4, "Lion");
[Link](5, "Tiger");
[Link](6, "Bear");
/* forEach to iterate and display each key and value pair
* of HashMap.
*/
[Link]((key,value)->[Link](key+" - "+value));
/* forEach to iterate a Map and display the value of a particular
* key
*/
[Link]((key,value)->{
if(key == 4){
[Link]("Value associated with key 4 is: "+value);
}
});
/* forEach to iterate a Map and display the key associated with a
* particular value
*/
[Link]((key,value)->{
if("Cat".equals(value)){
[Link]("Key associated with Value Cat is: "+key);
}
});
}
}
Output:
2/5
Java 8 – forEach to iterate a List
In this example, we are iterating an ArrayList using forEach() method. Inside forEach we are using
a lambda expression to print each element of the list.
import [Link];
import [Link];
public class Example {
public static void main(String[] args) {
List<String> fruits = new ArrayList<String>();
[Link]("Apple");
[Link]("Orange");
[Link]("Banana");
[Link]("Pear");
[Link]("Mango");
//lambda expression in forEach Method
[Link](str->[Link](str));
}
}
Output:
Apple
Orange
Banana
Pear
Mango
We can also use method reference in the forEach() method like this:
3/5
[Link]([Link]::println);
import [Link];
import [Link];
public class Example {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
[Link]("Maggie");
[Link]("Michonne");
[Link]("Rick");
[Link]("Merle");
[Link]("Governor");
[Link]() //creating stream
.filter(f->[Link]("M")) //filtering names that starts with M
.forEach([Link]::println); //displaying the stream using forEach
}
}
Output:
Maggie
Michonne
Merle
4/5
import [Link];
import [Link];
public class Example {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
[Link]("Maggie");
[Link]("Michonne");
[Link]("Rick");
[Link]("Merle");
[Link]("Governor");
//forEach - the output would be in any order
[Link]("Print using forEach");
[Link]()
.filter(f->[Link]("M"))
.parallel()
.forEach(n->[Link](n));
Output:
5/5
Java main() method explained with examples
In this article, we will learn Java main() method in detail. As the name suggest this is the main
point of the program, without the main() method the program won’t execute.
public: We have already learned in the access specifier tutorial that public access specifier allows
the access of the method outside the program, since we want the JVM to identify the main method
and start the execution from it, we want it to be marked “public”. If we use other access modifier
like private, default or protected, the JVM wouldn’t recognise the main() method and the program
won’t start the execution.
static: The reason the main() method is marked static so that it can be invoked by JVM without
the need of creating an object. In order to invoke the normal method, we need to create the object
first. However, to invoke the static method we don’t need an object. Learn more about static
method here.
void: This is the return type. The void means that the main() method will not return anything.
main(): This the default signature which is predefined by JVM. When we try to execute a program,
the JVM first identifies the main() method and starts the execution from it. As stated above, the
name of this method suggests that it is the “main” part of the program.
String args[]: The main method can also accepts string inputs that can be provided at the
runtime. These string inputs are also known as command line arguments. These strings inputs are
stored in the array args[] of String type.
1/4
public class JavaExample {
Output:
Error: Main method not found in class JavaExample, please define the main method as:
public static void main(String[] args)
class JavaExample
{
//static block
static
{
[Link]("Static Block");
}
//static method
public static void main(String args[])
{
[Link]("Main Method");
}
}
Output:
Static Block
Main Method
As we can see, the static block executed before the main method.
2/4
class JavaExample
{
static
{
[Link]("Static Block");
}
}
Output:
Error: Main method not found in class JavaExample, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend [Link]
3/4
class JavaExample
{
Output:
main method
100
A
4/4
Java Access Modifiers – Public, Private, Protected & Default
You must have seen public, private and protected keywords while practising java programs, these
are called access modifiers. An access modifier restricts the access of a class, constructor, data
member and method in another class. In java we have four access modifiers:
1. default
2. private
3. protected
4. public
To understand this example, you must have the knowledge of packages in java.
In this example we have two classes, Test class is trying to access the default method of Addition
class, since class Test belongs to a different package, this program would throw compilation error,
because the scope of default modifier is limited to the same package in which it is declared.
[Link]
package abcpackage;
[Link]
1/5
package xyzpackage;
Output:
1. Private Data members and methods are only accessible within the class
2. Class and Interface cannot be declared as private
3. If a class has private constructor then you cannot create the object of that class from outside
of the class.
2/5
class ABC{
private double num = 100;
private int square(int a){
return a*a;
}
}
public class Example{
public static void main(String args[]){
ABC obj = new ABC();
[Link]([Link]);
[Link]([Link](10));
}
}
Output:
package abcpackage;
public class Addition {
[Link]
3/5
package xyzpackage;
import abcpackage.*;
class Test extends Addition{
public static void main(String args[]){
Test obj = new Test();
[Link]([Link](11, 22));
}
}
Output:
33
Lets take the same example that we have seen above but this time the method addTwoNumbers()
has public modifier and class Test is able to access this method without even extending the
Addition class. This is because public modifier has visibility everywhere.
[Link]
package abcpackage;
[Link]
package xyzpackage;
import abcpackage.*;
class Test{
public static void main(String args[]){
Addition obj = new Addition();
[Link]([Link](100, 1));
}
}
Output:
101
4/5
The scope of access modifiers in tabular form
------------+-------+---------+--------------+--------------+--------
| Class | Package | Subclass | Subclass |Outside|
| | |(same package)|(diff package)|Class |
————————————+———————+—————————+——————————----+—————————----—+————————
public | Yes | Yes | Yes | Yes | Yes |
————————————+———————+—————————+—————————----—+—————————----—+————————
protected | Yes | Yes | Yes | Yes | No |
————————————+———————+—————————+————————----——+————————----——+————————
default | Yes | Yes | Yes | No | No |
————————————+———————+—————————+————————----——+————————----——+————————
private | Yes | No | No | No | No |
------------+-------+---------+--------------+--------------+--------
5/5
Garbage Collection in Java
When JVM starts up, it creates a heap area which is known as runtime data area. This is where all
the objects (instances of class) are stored. Since this area is limited, it is required to manage this
area efficiently by removing the objects that are no longer in use. The process of removing unused
objects from heap memory is known as Garbage collection and this is a part of memory
management in Java.
Languages like C/C++ don’t support automatic garbage collection, however in java, the garbage
collection is automatic.
Now we know that the garbage collection in java is automatic. Lets see when does java performs
garbage collection.
Here the reference obj was pointing to the object of class BeginnersBook but since we have
assigned a null value to it, this is no longer pointing to that object, which makes the
BeginnersBook object unreachable and thus unusable. Such objects are automatically available
for garbage collection in Java.
Here the reference str of String class was pointing to a string “hello” in the heap memory but since
we have assigned the null value to str, the object “hello” present in the heap memory is unusable.
Here we have assigned the reference obj1 to obj2, which means the instance (object) pointed by
(referenced by) obj2 is not reachable and available for garbage collection.
1/3
How to request JVM for garbage collection
We now know that the unreachable and unusable objects are available for garbage collection but
the garbage collection process doesn’t happen instantly. Which means once the objects are ready
for garbage collection they must to have to wait for JVM to run the memory cleanup program that
performs garbage collection. However you can request to JVM for garbage collection by calling
[Link]() method (see the example below).
Output:
2/3
2. Deletion: Objects that are not marked are considered unreachable. These objects are
considered garbage and are deleted.
3. Compaction: In this phase, the memory occupied by the garbage objects are released. This
is done post second phase, once the objects (garbage) are deleted successfully.
3/3
Java Finally block – Exception handling
In the previous tutorials I have covered try-catch block and nested try block. In this guide, we will
see finally block which is used along with try-catch.
A finally block contains all the crucial statements that must be executed whether exception
occurs or not. The statements present in this block will always execute regardless of whether
exception occurs in try block or not such as closing a connection, stream etc.
class Example
{
public static void main(String args[]) {
try{
int num=121/0;
[Link](num);
}
catch(ArithmeticException e){
[Link]("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
[Link]("This is finally block");
}
[Link]("Out of try-catch-finally");
}
}
Output:
1/6
Number should not be divided by zero
This is finally block
Out of try-catch-finally
2. Finally block is optional, as we have seen in previous tutorials that a try-catch block is sufficient
for exception handling, however if you place a finally block then it will always run after the
execution of try block.
3. In normal case when there is no exception in try block then the finally block is executed after try
block. However if an exception occurs then the catch block is executed before finally block.
4. An exception in the finally block, behaves exactly like any other exception.
5. The statements present in the finally block execute even if the try block contains control
transfer statements like return, break or continue.
Lets see an example to see how finally works when return statement is present in try block:
class JavaFinally
{
public static void main(String args[])
{
[Link]([Link]());
}
public static int myMethod()
{
try {
return 112;
}
finally {
[Link]("This is Finally block");
[Link]("Finally block ran even after return statement");
}
}
}
2/6
To see more examples of finally and return refer: Java finally block and return statement
.
For example:
....
try{
OutputStream osf = new FileOutputStream( "filename" );
OutputStream osb = new BufferedOutputStream(opf);
ObjectOutput op = new ObjectOutputStream(osb);
try{
[Link](writableObject);
}
finally{
[Link]();
}
}
catch(IOException e1){
[Link](e1);
}
...
3/6
...
InputStream input = null;
try {
input = new FileInputStream("[Link]");
}
finally {
if (input != null) {
try {
[Link]();
}catch (IOException exp) {
[Link](exp);
}
}
}
...
....
try {
//try block
[Link]("Inside try block");
[Link](0)
}
catch (Exception exp) {
[Link](exp);
}
finally {
[Link]("Java finally block");
}
....
In the above example if the [Link](0) gets called without any exception then finally won’t
execute. However if any exception occurs while calling [Link](0) then finally block will be
executed.
try-catch-finally block
Either a try statement should be associated with a catch block or with finally.
Since catch performs exception handling and finally performs the cleanup, the best
approach is to use both of them.
Syntax:
4/6
try {
//statements that may cause an exception
}
catch (…){
//error handling code
}
finally {
//statements to be executed
}
Example 1: The following example demonstrate the working of finally block when no exception
occurs in try block
class Example1{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=45/3;
[Link](num);
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("ArrayIndexOutOfBoundsException");
}
finally{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}
Output:
Example 2: This example shows the working of finally block when an exception occurs in try block
but is not handled in the catch block:
5/6
class Example2{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=45/0;
[Link](num);
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("ArrayIndexOutOfBoundsException");
}
finally{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}
Output:
As you can see that the system generated exception message is shown but before that the finally
block successfully executed.
Example 3: When exception occurs in try block and handled properly in catch block
class Example3{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=45/0;
[Link](num);
}
catch(ArithmeticException e){
[Link]("ArithmeticException");
}
finally{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}
Output:
6/6
Basics: All about Java threads
When a thread is invoked, there will be two paths of execution. One path will execute the thread
and the other path will follow the statement after the thread invocation. There will be a separate
stack and memory space for each thread.
Risk Factor
Threads in Java
1/4
2. Implementing the [Link] Interface
Note: The Thread and Runnable are available in the [Link].* package
Example:
Example:
Extending the Thread class will make your class unable to extend other classes, because of
the single inheritance feature in JAVA. However, this will give you a simpler code structure.
If you implement Runnable, you can gain better object-oriented design and consistency and
also avoid the single inheritance problems.
2/4
If you just want to achieve basic functionality of a thread you can simply implement
Runnable interface and override run() method. But if you want to do something serious with
thread object as it has other methods like suspend(), resume(), ..etc which are not available
in Runnable interface then you may prefer to extend the Thread class.
Ending Thread
The thread ends when it comes when the run() method finishes its execution.
When the thread throws an Exception or Error that is not being caught in the program.
Java program completes or ends.
Another thread calls stop() methods.
Synchronization of Threads
In many cases concurrently running threads share data and two threads try to do operations
on the same variables at the same time. This often results in corrupt data as two threads try
to operate on the same data.
A popular solution is to provide some kind of lock primitive. Only one thread can acquire a
particular lock at any particular time. This can be achieved by using a keyword
“synchronized” .
By using the synchronize only one thread can access the method at a time and a second
call will be blocked until the first call returns or wait() is called inside the synchronized
method.
Deadlock
Whenever there is multiple processes contending for exclusive access to multiple locks, there is
the possibility of deadlock. A set of processes or threads is said to be deadlocked when each is
waiting for an action that only one of the others can perform.
In Order to avoid deadlock, one should ensure that when you acquire multiple locks, you always
acquire the locks in the same order in all threads.
Keep blocks short. Synchronized blocks should be short — as short as possible while still
protecting the integrity of related data operations.
Don’t block. Don’t ever call a method that might block, such as [Link](), inside a
synchronized block or method.
3/4
Don’t invoke methods on other objects while holding a lock. This may sound extreme, but it
eliminates the most common source of deadlock.
Target keywords: Java threads, javathread example, create thread java, java Runnable
4/4
Multithreading in java with examples
Multithreading is one of the most popular feature of Java programming language as it allows the
concurrent execution of two or more parts of a program. Concurrent execution means two or more
parts of the program are executing at the same time, this maximizes the CPU utilization and gives
you better performance. These parts of the program are called threads.
Threads are independent because they all have separate path of execution that’s the reason if an
exception occurs in one thread, it doesn’t affect the execution of other threads. All threads of a
process share the common memory. The process of executing multiple threads
simultaneously is known as multithreading.
Advantages of Multithreading
Efficient CPU Utilization: As more than one threads run independently, this allows the CPU
to perform multiple tasks simultaneously.
Improved Performance
Better Resource Sharing: As discussed earlier, threads share common memory, this
reduces overhead compared to processes.
1/5
class MyRunnable implements Runnable {
public void run() {
[Link]("Thread is running...");
}
} public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t1 = new Thread(runnable);
[Link](); // Starts the thread and executes the `run` method
}
}
Thread Methods
Thread Synchronization
Multithreading introduces asynchronous behaviour to the programs. If a thread is writing
some data another thread may be reading the same data at that time. This may bring
inconsistency.
When two or more threads need access to a shared resource there should be some way
that the resource will be used only by one resource at a time. The process to achieve this is
called synchronization.
To implement the synchronous behavior java has synchronous method. Once a thread is
inside a synchronized method, no other thread can call any other synchronized method on
the same object. All the other threads then wait until the first thread come out of the
synchronized block.
When multiple threads access shared resources, synchronization ensures data consistency:
2/5
class Counter {
private int count = 0; public synchronized void increment() {
count++;
} public int getCount() {
return count;
}
} public class Main {
public static void main(String[] args) {
Counter counter = new Counter(); Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
[Link]();
}
}); Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
[Link]();
}
}); [Link]();
[Link](); try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]();
} [Link]("Count: " + [Link]());
}
}
Thread Lifecycle
1. New: When a thread object is created. A thread that has not yet started is in this state.
2. Runnable: After calling start(), the thread is ready to run.
3. Running: The thread is executing its run() method. A thread executing in the Java virtual
machine is in this state.
4. Blocked/Waiting: The thread is waiting for a resource or signal. A thread that is waiting
indefinitely for another thread to perform a particular action is in this state.
5. Timed Waiting: A thread that is waiting for another thread to perform an action for up to a
specified waiting time is in this state.
6. Terminated: The thread finishes execution.
3/5
Example: Multithreading in Action
In this example, Task1 and Task2 run concurrently, and their outputs will interleave based on
thread scheduling.
Key Points
If you’d like, I can provide additional details on advanced multithreading concepts like thread
pools, Callable, Future, or synchronized blocks.
Multitasking: Ability to execute more than one task at the same time is known as multitasking.
Multiprocessing: It is same as multitasking, however in multiprocessing more than one CPUs are
involved. On the other hand one CPU is involved in multitasking.
Parallel Processing: It refers to the utilization of multiple CPUs in a single computer system.
4/5
Thread priorities
Thread priorities are the integers which decide how one thread should be treated with
respect to the others.
Thread priority decides when to switch from one running thread to another, process is called
context switching
A thread can voluntarily release control and the highest priority thread that is ready to run is
given the CPU.
A thread can be preempted by a higher priority thread no matter what the lower priority
thread is doing. Whenever a higher priority thread wants to run it does.
To set the priority of the thread setPriority() method is used which is a method of the
class Thread Class.
In place of defining the priority in integers, we can use MIN_PRIORITY, NORM_PRIORITY or
MAX_PRIORITY.
Inter-thread Communication
We have few methods through which java threads can communicate with each other. These
methods are wait(), notify(), notifyAll(). All these methods can only be called from within a
synchronized method.
1) To understand synchronization java has a concept of monitor. Monitor can be thought of as a
box which can hold only one thread. Once a thread enters the monitor all the other threads have
to wait until that thread exits the monitor.
2) wait() tells the calling thread to give up the monitor and go to sleep until some other thread
enters the same monitor and calls notify().
3) notify() wakes up the first thread that called wait() on the same object.
notifyAll() wakes up all the threads that called wait() on the same object. The highest priority
thread will run first.
5/5
Thread Life cycle in Java
In previous post I have covered almost all the terms related to Java threads. Here we will learn
Thread life cycle in java, we’ll also see thread scheduling.
Recommended Reads:
Multithreading in Java
The start method creates the system resources, necessary to run the thread, schedules the
thread to run, and calls the thread’s run method.
Below diagram clearly depicts the various phases of thread life cycle in java.
2. Thread Scheduling
Execution of multiple threads on a single CPU, in some order, is called scheduling.
In general, the runnable thread with the highest priority is active (running)
Java is priority-preemptive
If a high-priority thread wakes up, and a low-priority thread is running
Then the high-priority thread gets to run immediately
Allows on-demand processing
Efficient use of CPU
1/3
2.1 Types of scheduling
Waiting and Notifying
Waiting [wait()] and notifying [notify(), notifyAll()] provides means of communication
between threads that synchronize on the same object.
wait(): when wait() method is invoked on an object, the thread executing that code gives up
its lock on the object immediately and moves the thread to the wait state.
notify(): This wakes up threads that called wait() on the same object and moves the thread to
ready state.
notifyAll(): This wakes up all the threads that called wait() on the same object.
Running and Yielding
Yield() is used to give the other threads of the same priority a chance to execute i.e.
causes current running thread to move to runnable state.
Sleeping and Waking up
nSleep() is used to pause a thread for a specified period of time i.e. moves the current
running thread to Sleep state for a specified amount of time, before moving it to
runnable state. [Link](no. of milliseconds);
When a Java thread is created, it inherits its priority from the thread that created it.
You can modify a thread’s priority at any time after its creation using the setPriority method.
Thread priorities are integers ranging between MIN_PRIORITY (1) and MAX_PRIORITY
(10) . The higher the integer, the higher the [Link] the thread priority will be 5.
isAlive() method is used to determine if a thread is still alive. It is the best way to determine if
a thread has been started but has not yet completed its run() method. final boolean
isAlive();
The nonstatic join() method of class Thread lets one thread “join onto the end” of another
thread. This method waits until the thread on which it is called terminates. final void join();
3. Blocking Threads
When reading from a stream, if input is not available, the thread will block
Thread is suspended (“blocked”) until I/O is available
Allows other threads to automatically activate
When I/O available, thread wakes back up again
Becomes “runnable” i.e. gets into ready state
2/3
4. Grouping of threads
Thread groups provide a mechanism for collecting multiple threads into a single object and
manipulating those threads all at once, rather than individually.
To put a new thread in a thread group the group must
be explicitly specified when the thread is created
– public Thread(ThreadGroup group, Runnable runnable)
– public Thread(ThreadGroup group, String name)
– public Thread(ThreadGroup group, Runnable runnable, String name)
A thread can not be moved to a new group after the thread has been created.
When a Java application first starts up, the Java runtime system creates a ThreadGroup
named main.
Java thread groups are implemented by the [Link] class.
Target keywords: thread life cycle in java, java threading tutorial, using threads in
java, javathread run.
3/3
What is the difference between a process and a thread in
Java?
This is the most frequently asked question during interviews. In this post we will discuss the
differences between thread and process. You must have heard these terms while reading
multithreading in java, both of these terms are related to each other. Both processes and threads
are independent sequences of execution. The main difference is that threads (of the same
process) run in a shared memory space, while processes run in separate memory spaces. Lets
see the differences in detail:
Thread vs Process
1) A program in execution is often referred as process. A thread is a subset(part) of the process.
2) A process consists of multiple threads. A thread is a smallest part of the process that can
execute concurrently with other parts(threads) of the process.
4) A process has its own address space. A thread uses the process’s address space and share it
with the other threads of that process.
5)
6) A thread can communicate with other thread (of the same process) directly by using methods
like wait(), notify(), notifyAll(). A process can communicate with other process by using inter-
process communication.
7) New threads are easily created. However the creation of new processes require duplication of
the parent process.
8) Threads have control over the other threads of the same process. A process does not have
control over the sibling process, it has control over its child processes only.
1/1
Java Lambda Expressions Tutorial with examples
Lambda expression is a new feature which is introduced in Java 8. A lambda expression is an
anonymous function. A function that doesn’t have a name and doesn’t belong to any class. The
concept of lambda expression was first introduced in LISP programming language.
1/4
Java Lambda expression Example
Without using Lambda expression: Prior to java 8 we used the anonymous inner classe to
implement the only abstract method of functional interface.
import [Link].*;
import [Link].*;
public class ButtonListenerOldWay {
public static void main(String[] args) {
Frame frame=new Frame("ActionListener Before Java8");
[Link](new ActionListener(){
public void actionPerformed(ActionEvent e){
[Link]("Hello World!");
}
});
[Link](b);
[Link](200,200);
[Link](null);
[Link](true);
}
}
By using Lambda expression: Instead of creating anonymous inner class, we can create a
lambda expression like this:
import [Link].*;
public class ButtonListenerNewWay {
public static void main(String[] args) {
Frame frame=new Frame("ActionListener java8");
[Link](200,200);
[Link](null);
[Link](true);
}
}
Note:
1. As you can see that we used less code with lambda expression.
2. Backward compatibility: You can use the lambda expression with your old code. Lambdas are
2/4
backward compatible so you can use them in existing API when you migrate your project to java 8.
@FunctionalInterface
interface MyFunctionalInterface {
Output:
Hello
@FunctionalInterface
interface MyFunctionalInterface {
Output:
27
3/4
Example 3: Java Lambda Expression with Multiple Parameters
interface StringConcat {
Output:
import [Link].*;
public class Example{
public static void main(String[] args) {
List<String> list=new ArrayList<String>();
[Link]("Rick");
[Link]("Negan");
[Link]("Daryl");
[Link]("Glenn");
[Link]("Carl");
[Link](
// lambda expression
(names)->[Link](names)
);
}
}
4/4
Lambda Expression – Iterating Map and List in Java 8
I have already covered normal way of iterating Map and list in Java. In this tutorial, we will see
how to iterate (loop) Map and List in Java 8 using Lambda expression.
package [Link];
import [Link];
import [Link];
public class IterateMapUsingLambda {
public static void main(String[] args) {
Map<String, Integer> prices = new HashMap<>();
[Link]("Apple", 50);
[Link]("Orange", 20);
[Link]("Banana", 10);
[Link]("Grapes", 40);
[Link]("Papaya", 50);
}
}
Output:
1/2
Iterating List in Java 8 using Lambda expression
package [Link];
import [Link];
import [Link];
public class IterateListUsingLambda {
public static void main(String[] argv) {
List names = new ArrayList<>();
[Link]("Ajay");
[Link]("Ben");
[Link]("Cathy");
[Link]("Dinesh");
[Link]("Tom");
Output:
Ajay
Ben
Cathy
Dinesh
Tom
2/2
Wrapper class in Java
In the OOPs concepts guide, we learned that object oriented programming is all about objects.
The eight primitive data types byte, short, int, long, float, double, char and boolean are not objects,
Wrapper classes are used for converting primitive data types into objects, like int to Integer,
double to Double, float to Float and so on. Let’s take a simple example to understand why we
need wrapper class in java.
For example: While working with collections in Java, we use generics for type safety like this:
ArrayList<Integer> instead of this ArrayList<int>. The Integer is a wrapper class of int primitive
type. We use wrapper class in this case because generics needs objects not primitives. There are
several other reasons you would prefer a wrapper class instead of primitive type, we will discuss
them as well in this article.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
The primitive data types are not objects so they do not belong to any class. While storing in data
structures which support only objects, it is required to convert the primitive type to object first
which we can do by using wrapper classes.
Example:
1/3
So for type safety we use wrapper classes. This way we are ensuring that this HashMap keys
would be of integer type and values would be of string type.
2. Wrapper class objects allow null values while primitive data type doesn’t allow it.
Output:
100 100
As you can see both primitive data type and object have same values. You can use obj in place of
num wherever you need to pass the value of num as an object. The conversion of primitive data
type to object is known as autoboxing and the conversion from object to primitive type is known
as unboxing, this concept is covered in detail at: Autoboxing and Unboxing in Java.
Output:
100 100
2/3
Custom Wrapper Class
We can also create a custom wrapper class to wrap a primitive type to an object. Here, we have a
int data type that belongs to class XYZ. We can use this primitive data type as object using the
constructor and getter setter methods of XYZ class as shown below:
class XYZ{
private int num;
//default constructor
XYZ(){}
//parameterized constructor
XYZ(int num){
[Link]=num;
}
//getter and setter methods
public int getIntValue(){
return num;
}
public void setIntValue(int i){
[Link]=i;
}
@Override
public String toString() {
return [Link](num);
}
}
public class JavaExample{
public static void main(String[] args){
XYZ obj = new XYZ(10);
[Link](obj);
[Link](100);
[Link]([Link]());
}
}
Output:
10
100
Conclusion
In this guide, we learned what are the advantages of objects over primitive data types. How to
convert primitive types to objects using wrapper class. We also learned when to use primitive
types and when to use objects. If you want to learn more such topics related to Java then head
over to the Java Tutorial section.
3/3
Java Regular Expressions (java regex) Tutorial with
examples
Regular expressions are used for defining String patterns that can be used for searching,
manipulating and editing a text. These expressions are also known as Regex (short form of
Regular expressions).
In the below example, the regular expression .*book.* is used for searching the occurrence of
string “book” in the text.
import [Link].*;
class RegexExample1{
public static void main(String args[]){
String content = "This is Chaitanya " +
"from [Link].";
Output:
In this tutorial we will learn how to define patterns and how to use them. The [Link] API
(the package which we need to import while dealing with Regex) has two main classes:
[Link] class:
1) [Link]()
We have already seen the usage of this method in the above example where we performed the
search for string “book” in a given text. This is one of simplest and easiest way of searching a
String in a text using Regex.
1/8
As you can see we have used matches() method of Pattern class to search the pattern in the
given text. The pattern .*tutorial.* allows zero or more characters at the beginning and end of
the String “tutorial” (the expression .* is used for zero and more characters).
Limitations: This way we can search a single occurrence of a pattern in a text. For matching
multiple occurrences you should use the [Link]() method (discussed in the next section).
2) [Link]()
In the above example we searched a string “tutorial” in the text, that is a case sensitive search,
however if you want to do a CASE INSENSITIVE search or want to do search multiple
occurrences then you may need to first compile the pattern using [Link]() before
searching it in text. This is how this method can be used for this case.
Here we have used a flag Pattern.CASE_INSENSITIVE for case insensitive search, there are
several other flags that can be used for different-2 purposes. To read more about such flags refer
this document.
Now what: We have obtained a Pattern instance but how to match it? For that we would be
needing a Matcher instance, which we can get using [Link]() method. Lets discuss it.
3) [Link]() method
In the above section we learnt how to get a Pattern instance using compile() method. Here we will
learn How to get Matcher instance from Pattern instance by using matcher() method.
Output:
Is it a Match?true
4) [Link]()
To split a text into multiple strings based on a delimiter (Here delimiter would be specified using
regex), we can use [Link]() method. This is how it can be done.
2/8
import [Link].*;
class RegexExample2{
public static void main(String args[]){
String text = "[Link]";
// Pattern for delimiter
String patternString = "is";
Pattern pattern = [Link](patternString, Pattern.CASE_INSENSITIVE);
String[] myStrings = [Link](text);
for(String temp: myStrings){
[Link](temp);
}
[Link]("Number of split strings: "+[Link]);
}}
Output:
Th
[Link]
MyWebsite
Number of split strings: 4
[Link] Class
We already discussed little bit about Matcher class above. Lets recall few things:
Main methods
matches(): It matches the regular expression against the whole text passed to the
[Link]() method while creating Matcher instance.
...
Matcher matcher = [Link](content);
boolean isMatch = [Link]();
lookingAt(): Similar to matches() method except that it matches the regular expression only
against the beginning of the text, while matches() search in the whole text.
find(): Searches the occurrences of of the regular expressions in the text. Mainly used when we
are searching for multiple occurrences.
3/8
start() and end(): Both these methods are generally used along with the find() method. They are
used for getting the start and end indexes of a match that is being found using find() method.
Lets take an example to find out the multiple occurrences using Matcher methods:
package [Link];
import [Link].*;
class RegexExampleMatcher{
public static void main(String args[]){
String content = "ZZZ AA PP AA QQQ AAA ZZ";
while([Link]()) {
[Link]("Found at: "+ [Link]()
+
" - " + [Link]());
}
}
}
Output:
Found at: 4 - 6
Found at: 10 - 12
Found at: 17 - 19
Now we are familiar with Pattern and Matcher class and the process of matching a regular
expression against the text. Lets see what kind of various options we have to define a regular
expression:
1) String Literals
Lets say you just want to search a particular string in the text for e.g. “abc” then we can simply
write the code like this: Here text and regex both are same.
[Link]("abc", "abc")
2) Character Classes
A character class matches a single character in the input text against multiple allowed characters
in the character class. For example [Cc]haitanya would match all the occurrences of String
“chaitanya” with either lower case or upper case C”. Few more examples:
[Link]("[pqr]", "abcd"); It would give false as no p,q or r in the text
[Link]("[pqr]", "r"); Return true as r is found
[Link]("[pqr]", "pq"); Return false as any one of them can be in text not both.
4/8
Here is the complete list of various character classes constructs:
[abc]: It would match with text if the text is having either one of them(a,b or c) and only once.
[^abc]: Any single character except a, b, or c (^ denote negation)
[a-zA-Z]: a through z, or A through Z, inclusive (range)
[a-d[m-p]]: a through d, or m through p: [a-dm-p] (union)
[a-z&&[def]]: Any one of them (d, e, or f)
[a-z&&[^bc]]: a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]]: a through z, and not m through p: [a-lq-z] (subtraction)
These are like short codes which you can use while writing regex.
Construct Description
. -> Any character (may or may not match line terminators)
\d -> A digit: [0-9]
\D -> A non-digit: [^0-9]
\s -> A whitespace character: [ \t\n\x0B\f\r]
\S -> A non-whitespace character: [^\s]
\w -> A word character: [a-zA-Z_0-9]
\W -> A non-word character: [^\w]
For e.g.
[Link]("\\d", "1"); would return true
[Link]("\\D", "z"); return true
[Link](".p", "qp"); return true, dot(.) represent any character
Boundary Matchers
For e.g.
[Link]("^Hello$", "Hello"): return true, Begins and ends with Hello
[Link]("^Hello$", "Namaste! Hello"): return false, does not begin with Hello
[Link]("^Hello$", "Hello Namaste!"): return false, Does not end with Hello
5/8
Quantifiers
6/8
Few examples
import [Link].*;
class RegexExample{
public static void main(String args[]){
// It would return true if string matches exactly "tom"
[Link](
[Link]("tom", "Tom")); //False
7/8
/* Boundary Matchers example
* ^ denotes start of the line
* $ denotes end of the line
*/
[Link](
[Link]("^This$", "This is Chaitanya")); //False
[Link](
[Link]("^This$", "This")); //True
[Link](
[Link]("^This$", "Is This Chaitanya")); //False
}
}
8/8
Java Scanner class with examples
In this tutorial, you will learn Java Scanner class and how to use it in java programs to get the
user input. This is one of the important classes as it provides you various methods to capture
different types of user entered data. In this guide, we will discuss java Scanner class methods as
well as examples of some of the important methods of this class.
The Scanner class is present in the [Link] package so be sure import this package when you
are using this class.
1/6
import [Link];
public class JavaExample {
public static void main(String[] args) {
// creating a scanner
Scanner scan = new Scanner([Link]);
// close scanner
[Link]();
}
}
Output:
Method Description
2/6
next() This method reads a word entered by the user
import [Link];
public class JavaExample {
public static void main(String[] args) {
// creating a scanner
Scanner scan = new Scanner([Link]);
// close scanner
[Link]();
}
}
Output:
3/6
Example 3: Java Scanner next() method
The next() method is different from the nextLine() method. Where the nextLine() method is
used to read the line of text, the next() method reads the word entered by the user. The next()
method reads the input until a whitespace is encountered. It doesn’t read the user input after
whitespace.
In the following example, user is asked to enter the full name, however the next() method
captured only the first name as it stopped reading input as soon as it found a whitespace. We will
revisit the same example next with nextLine() method to get the desired output.
import [Link];
public class JavaExample {
public static void main(String[] args) {
// creating a scanner
Scanner scan = new Scanner([Link]);
// close scanner
[Link]();
}
}
Output:
4/6
Example 4: Java Scanner nextLine() method
Let’s revisit the same example. As you can see, using nextLine(), we can read the complete user
input. This is because this method reads a complete line.
import [Link];
public class JavaExample {
public static void main(String[] args) {
// creating a scanner
Scanner scan = new Scanner([Link]);
// close scanner
[Link]();
}
}
Output:
5/6
import [Link];
public class JavaExample {
public static void main(String args[]){
// Initializing a Scanner object
Scanner scan = new Scanner("BeginnersBook/Chaitanya/Website");
Output:
BeginnersBook
Chaitanya
Website
6/6
How to write to file in Java using BufferedWriter
Earlier we discussed how to write to a file using FileOutputStream. In this tutorial we will see how
to write to a file using BufferedWriter. We will be using write() method of BufferedWriter to
write the text into a file. The advantage of using BufferedWriter is that it writes text to a
character-output stream, buffering characters so as to provide for the efficient writing (better
performance) of single characters, arrays, and strings.
1/2
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Output:
2/2
Final Keyword In Java – Final variable, Method and Class
In this tutorial we will learn the usage of final keyword. The final keyword can be used for
variables, methods and classes. We will cover following topics in detail.
1) final variable
2) final method
3) final class
1) final variable
final variables are nothing but constants. We cannot change the value of a final variable once it is
initialized. Lets have a look at the below code:
class Demo{
Output:
at [Link]([Link])
at [Link]([Link])
We got a compilation error in the above program because we tried to change the value of a final
variable “MAX_VALUE”.
1/5
class Demo{
//Blank final variable
final int MAX_VALUE;
Demo(){
//It must be initialized in constructor
MAX_VALUE=100;
}
void myMethod(){
[Link](MAX_VALUE);
}
public static void main(String args[]){
Demo obj=new Demo();
[Link]();
}
}
Output:
100
class StudentData{
//Blank final variable
final int ROLL_NO;
StudentData(int rnum){
//It must be initialized in constructor
ROLL_NO=rnum;
}
void myMethod(){
[Link]("Roll no is:"+ROLL_NO);
}
public static void main(String args[]){
StudentData obj=new StudentData(1234);
[Link]();
}
}
Output:
Roll no is:1234
2/5
Uninitialized static final variable
A static final variable that is not initialized during declaration can only be initialized in static block.
Example:
class Example{
//static blank final variable
static final int ROLL_NO;
static{
ROLL_NO=1230;
}
public static void main(String args[]){
[Link](Example.ROLL_NO);
}
}
Output:
1230
2) final method
A final method cannot be overridden. Which means even though a sub class can call the final
method of parent class without any issues but it cannot override it.
Example:
class XYZ{
final void demo(){
[Link]("XYZ Class Method");
}
}
The above program would throw a compilation error, however we can use the parent class final
method in sub class without any issues. Lets have a look at this code: This program would run fine
as we are not overriding the final method. That shows that final methods are inherited but they are
not eligible for overriding.
3/5
class XYZ{
final void demo(){
[Link]("XYZ Class Method");
}
}
Output:
3) final class
We cannot extend a final class. Consider the following example:
Output:
Points to Remember:
1) A constructor cannot be declared as final.
2) Local final variable must be initializing during declaration.
3) All variables declared in an interface are by default final.
4) We cannot change the value of a final variable.
5) A final method cannot be overridden.
6) A final class not be inherited.
7) If method parameters are declared final then the value of these parameters cannot be changed.
8) It is a good practice to name final variable in all CAPS.
9) final, finally and finalize are three different terms. finally is used in exception handling and
finalize is a method that is called by JVM during garbage collection.
4/5
5/5
100+ Core Java Interview Questions
Hi Friends, In this article, we have shared 100+ java interview questions for both beginners and
experienced folks. If you are a java beginner, I highly recommend you to checkout my java tutorial.
Table of Contents
Yes. Java is a platform independent language. We can write java code on one platform and run it
on another platform. For e.g. we can write and compile the code on windows and can run the
generated bytecode on Linux or any other supported platform. This is one of the main features of
java.
Classloader, Class area, Heap, Stack, Program Counter Register and Native Method Stack
static – static keyword tells that this method can be accessed without creating the instance of the
class. Refer: Static keyword in java
1/16
String args[] – The args is an array of String type. This contains the command line arguments
that we can pass while running the program.
Q) What is javac ?
The javac is a compiler that compiles the source code of your program and generates bytecode.
In simple words javac produces the java byte code from the source code written *.java file. JVM
executes the bytecode to run the program.
Q) What is class?
A class is a blueprint or template or prototype from which you can create the object of that class. A
class has set of properties and methods that are common to its objects.
byte – 8 bit
short – 16 bit
char – 16 bit Unicode
int – 32 bit (whole number)
float – 32 bit (real number)
long – 64 bit (Single precision)
double – 64 bit (double precision)
Q) What is Unicode?
Java uses Unicode to represent the characters. Unicode defines a fully international character set
that can represent all of the characters found in human languages.
Any constant value that is assigned to a variable is called literal in Java. For example –
2/16
// Here 101 is a literal
int num = 101
Q) Dynamic Initialization?
Dynamic initialization is process in which initialization value of a variable isn’t known at compile-
time. It’s computed at runtime to initialize the variable.
For example:
Q) What is an Array?
An array is a collection (group) of fixed number of items. Array is a homogeneous data structure
which means we can store multiple values of same type in an array but it can’t contain multiple
values of different types. For example an array of int type can only hold integer values.
break statement is generally used with switch case data structure to come out of the
statement once a case is executed.
It can be used to come out of the loop in Java
int arr[];
int[] arr;
Inheritance
Polymorphism
3/16
Data Encapsulation
Abstraction
Q) What is inheritance?
The process by which one class acquires the properties and functionalities of another class is
called inheritance. Inheritance brings reusability of code in a java application. Refer: Guide to
Inheritance in Java.
When a class extends more than one classes then it is called multiple inheritance. Java doesn’t
support multiple inheritance whereas C++ supports it, this is one of the difference between java
and C++. Refer: Why java doesn’t support multiple inheritance?
Polymorphism is the ability of an object to take many forms. The most common use of
polymorphism in OOPs is to have more than one method with the same name in a single class.
There are two types of polymorphism: static polymorphism and dynamic polymorphism. Refer
these guides to understand the polymorphism concept in detail: 1) Java Polymorphism 2) Types of
Polymorphism
When a sub class (child class) overrides the method of super class(parent class) then it is called
overriding. To override a method, the signature of method in child class must match with the
method signature in parent class. Refer: Java – Method Overriding
When a class has more than one methods with the same name but different number, sequence or
types of arguments then it is known as method overloading. Refer: Java – Method Overloading
4/16
Q) Can we overload a method by just changing the return type and without
changing the signature of method?
No, We cannot do this. To overload a method, the method signature must be different, return type
doesn’t play any role in method overloading.
Binding refers to the linking of method call to its body. A binding that happens at compile time is
known as static binding while binding at runtime is known as dynamic binding. Refer: Static and
Dynamic binding in Java.
Q) What is Encapsulation?
Wrapping of the data and code together is known as encapsulation. Refer: Java Encapsulation.
An abstract class is a class which can’t be instantiated (we cannot create the object of abstract
class), we can only extend such classes. It provides the generalised form that will be shared by all
of its subclasses, leaving it to each subclass to fill in the details. We can achieve partial
abstraction using abstract classes, to achieve full abstraction we use interfaces.
1) abstract class can have abstract and non-abstract methods. An interface can only have abstract
methods.
2) An abstract class can have static methods but an interface cannot have static methods.
3) abstract class can have constructors but an interface cannot have constructors.
Q) Name the access modifiers that can be applied to the inner classes?
public ,private , abstract, final, protected.
5/16
Q) What is a constructor in Java?
Constructor is used for creating an instance of a class, they are invoked when an instance of class
gets created. Constructor name and class name should be same and it doesn’t have a return type.
Refer this guide: Java Constructor.
Default: Constructors with no arguments are known as default constructors, when you don’t
declare any constructor in a class, compiler creates a default one automatically.
Yes. A constructor can call the another constructor of same class using this keyword. For e.g.
this() calls the default constructor.
Note: this() must be the first statement in the calling constructor.
Yes. In fact it happens by default. A child class constructor always calls the parent class
constructor. However we can still call it using super keyword. For e.g. super() can be used for
calling super class default constructor.
Q)THIS keyword?
6/16
Q) Explain ways to pass the arguments in Java?
In java, arguments can be passed as call by value – Java only supports call by value, there is no
concept of call by reference in Java.
Static variables are also known as class level variables. A static variable is same for all the objects
of that particular class in which it is declared.
super keyword references to the parent class. There are several uses of super keyword:
objectClone () – to creates a new object that is same as the object being cloned.
boolean equals(Object obj) – determines whether one object is equal to another.
7/16
finalize() – Called by the garbage collector on an object when garbage collection determines
that there are no more references to the object. A subclass overrides the finalize method to
dispose of system resources or to perform other cleanup.
toString () – Returns a string representation of the object.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations). Refer: Package in Java.
Q) How many times does the garbage collector calls the finalize() method for an
object?
The garbage collector calls the finalize() method only once for an object.
No, its not possible. you cannot force garbage collection. you can call [Link]() methods for
garbage collection but it does not guarantee that garbage collection would be done.
8/16
Exception handling Interview Questions
Q) What is an exception?
Exceptions are abnormal conditions that arise during execution of the program. It may occur due
to wrong user input or wrong logic written by programmer.
If a method does not handle a checked exception, the method must declare it using the
throwskeyword. The throws keyword appears at the end of a method’s signature.
9/16
Q) Can static block throw exception?
Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime
exception (Unchecked exceptions), In order to throw checked exceptions you can use a try-catch
block inside it.
Q) ClassNotFoundException vs NoClassDefFoundError?
1) ClassNotFoundException occurs when loader could not find the required class in class path.
2) NoClassDefFoundError occurs when class is loaded in classpath, but one or more of the class
which are required by other class, are removed or failed to load by compiler.
Yes we can have multiple catch blocks in order to handle more than one exception.
The only time finally won’t be called is if you call [Link]() or if the JVM crashes first.
Yes we can do that using if-else statement but it is not considered as a good practice. We should
have one catch block for one exception.
10/16
Java Multithreading Interview Questions
Q) What is Multithreading?
It is a process of executing two or more part of a program simultaneously. Each of these parts is
known as threads. In short the process of executing multiple threads simultaneously is known as
multithreading.
Q) What are the main differences between Process and thread? Explain in brief.
1) One process can have multiple threads. A thread is a smaller part of a process.
2) Every process has its own memory space, executable code and a unique process identifier
(PID) while every thread has its own stack in Java but it uses process main memory and shares it
with other threads.
3) Threads of same process can communicate with each other using keyword like wait and notify
etc. This process is known as inter process communication.
sleep() – It causes the current thread to suspend execution for a specified period. When a thread
goes into sleep state it doesn’t release the lock.
sleep() – It causes the current thread to suspend execution for a specified period. When a thread
goes into sleep state it doesn’t release the lock
wait() – It causes current thread to wait until either another thread invokes the notify() method or
the notifyAll() method for this object, or a specified amount of time has elapsed.
11/16
Q) What is a daemon thread?
A daemon thread is a thread, that does not prevent the JVM from exiting when the program
finishes but the thread is still running. An example for a daemon thread is the garbage collection.
1) The preemptive scheduling is prioritized. The highest priority process should always be the
process that is currently utilized.
2) Time slicing means task executes for a defined slice/ period of time and then enter in the pool
of ready state. The scheduler then determines which task execute next based on priority or other
factor.
Yes, we can call run() method of a Thread class but then it will behave like a normal method. To
actually execute it in a Thread, you should call [Link]() method to start it.
Q) What is Starvation?
Starvation describes a situation where a thread is unable to gain regular access to shared
resources and is unable to make progress. This happens when shared resources are made
unavailable for long periods by “greedy” threads. For example, suppose an object provides a
synchronized method that often takes a long time to return. If one thread invokes this method
frequently, other threads that also need frequent synchronized access to the same object will often
be blocked.
Q) What is deadlock?
Deadlock describes a situation where two or more threads are blocked forever, waiting for each
other.
Serialization is a process of converting an object and its attributes to the stream of bytes. De-
serialization is recreating the object from stream of bytes; it is just a reverse process of
serialization. To know more about serialization with example program, refer this article.
12/16
Q) Do we need to implement any method of Serializable interface to make an
object serializable?
No. In order to make an object serializable we just need to implement the interface Serializable.
We don’t need to implement any methods.
String class is immutable that’s the reason once its object gets created, it cannot be changed
further.
Q) What is List?
Elements can be inserted or accessed by their position in the list, using a zero-based index.
A list may contain duplicate elements.
Q) What is Map?
Map interface maps unique keys to values. A key is an object that we use to retrieve a value later.
A map cannot contain duplicate keys: Each key can map to at most one value.
Q) What is Set?
13/16
Q) Why ArrayList is better than Arrays?
Array can hold fixed number of elements. ArrayList can grow dynamically.
1) LinkedList store elements within a doubly-linked list data structure. ArrayList store elements
within a dynamically resizing array.
2) LinkedList is preferred for add and update operations while ArrayList is a good choice for
search operations. Read more here.
14/16
Q) What is the difference between Iterator and Enumeration?
1) Iterator allows to remove elements from the underlying collection during the iteration using its
remove() method. We cannot add/remove elements from a collection when using enumerator.
2) Iterator has improved method names.
[Link]() -> [Link]()
[Link]() -> [Link]().
Unsigned applets can, however, read (but not write) non-class files bundled with your applet on
the server, called resource files
Q) What is container ?
A component capable of holding another component is called as container.
Container
Panel
Applet
Window
Frame
Dialog
ActionListerner – actionPerformed();
ItemListerner – itemStateChanged();
TextListener – textValueChanged();
FocusListener – focusLost(); & FocusGained();
WindowListener – windowActified(); windowDEactified(); windowIconified(); windowDeiconified();
windowClosed(); windowClosing(); windowOpened();
MouseMotionListener – mouseDragged(); & mouseMoved();
MouseListener – mousePressed(); mouseReleased(); mouseEntered(); mouseExited();
mouseClicked();
15/16
Q) Applet Life cycle?
Following stage of any applets life cycle, starts with init(), start(), paint(), stop() and destroy().
To display the message at the bottom of the browser when applet is started.
16/16
Difference between ArrayList and HashMap in Java
ArrayList and HashMap are two commonly used collection classes in Java. Even though both are
the part of collection framework, the way they store and process the data is entirely different. In
this post we will see the main differences between these two collections.
2) Memory consumption: ArrayList stores the element’s value alone and internally maintains the
indexes for each element.
HashMap stores key & value pair. For each value there must be a key associated in HashMap.
That clearly shows that memory consumption is high in HashMap compared to the ArrayList.
3) Order: ArrayList maintains the insertion order while HashMap doesn’t. Which means ArrayList
returns the list items in the same order in which they got inserted into the list. On the other side
HashMap doesn’t maintain any order, the returned key-values pairs are not sorted in any kind of
order.
4) Duplicates: ArrayList allows duplicate elements but HashMap doesn’t allow duplicate keys (It
does allow duplicate values).
5) Nulls: ArrayList can have any number of null elements. HashMap allows one null key and any
number of null values.
6) get method: In ArrayList we can get the element by specifying the index of it. In HashMap the
elements is being fetched by specifying the corresponding key.
1/1
Difference between ArrayList and LinkedList in Java
In this guide, you will learn difference between ArrayList and LinkedList in Java. ArrayList and
LinkedList both implements List interface and their methods and results are almost identical.
However there are few differences between them which make one better over another on case to
case basis.
ArrayList Vs LinkedList
ArrayList LinkedList
ArrayList class inherits the features of list LinkedList class has the features of list and queue
as it implements the List interface. both as it implements both List and Dequeue
interfaces.
ArrayList data structure is similar to array LinkedList elements are not stored in contagious
as the ArrayList elements are stored in locations. This is because LinkedList consists of
contiguous locations. nodes where each node has data field and
reference to the next node in the list.
ArrayList default capacity is 10. If more LinkedList default capacity is zero. When
than 10 elements are added to the LinkedList is created its an empty list without any
ArrayList, its capacity gets doubled to initial capacity.
accommodate new elements.
ArrayList uses dynamic array to store the LinkedList uses concept of doubly linked list to
elements. store the elements.
ArrayList gives better performance for add LinkedList gives better performance for data
and search operations. deletion.
Reason: ArrayList maintains index based system for its elements as it uses array data structure
implicitly which makes it faster for searching an element in the list. On the other side LinkedList
implements doubly linked list which requires the traversal through all the elements for searching
1/3
an element.
2) Deletion: LinkedList remove operation gives O(1) performance while ArrayList gives variable
performance: O(n) in worst case (while removing first element) and O(1) in best case (While
removing last element).
Reason: LinkedList’s each element maintains two pointers (addresses) which points to the both
neighbour elements in the list. Hence removal only requires change in the pointer location in the
two neighbour nodes (elements) of the node which is going to be removed. While In ArrayList all
the elements need to be shifted to fill out the space created by removed element.
3) Inserts Performance: LinkedList add method gives O(1) performance while ArrayList gives
O(n) in worst case. This is because every time you add an element, Java ensures that it can fit
the element so it grows the ArrayList. If the ArrayList grows faster, there will be a lot of array
copying taking place. In worst-case the array must be resized and copied.
There are few similarities between these classes which are as follows:
2) Search (get method) operations are fast in Arraylist (O(1)) but not in LinkedList (O(n)) so If
there are less add and remove operations and more search operations requirement, ArrayList
would be your best bet.
2/3
Example of ArrayList and LinkedList in Java
In this example, we are demonstrating the use of ArrayList and LinkedList in Java. Here we have
initialized an arraylist arrList and a linkedlist linkList. We have added few elements to both
arrList and linkList. In the end, elements of both the lists are printed.
import [Link].*;
class JavaExample{
public static void main(String args[]){
//ArrayList
ArrayList<String> arrList=new ArrayList<>();
[Link]("Apple");
[Link]("Orange");
[Link]("Banana");
[Link]("Mango");
//LinkedList
LinkedList<String> linkList=new LinkedList<>();
[Link]("Beans");
[Link]("Tomato");
[Link]("Lemon");
[Link]("Potato");
//printing elements
[Link]("ArrayList elements: "+ arrList);
[Link]("LinkedList elements: "+ linkList);
}
}
Output:
3/3
Difference between ArrayList and Vector In java
ArrayList and Vector both use Array as a data structure internally. However there are key
differences between these classes. In this guide, you will learn the differences between
ArrayList and Vector.
ArrayList Vector
ArrayList can grow and shrink dynamically, it grows Like ArrayList, Vector can grow and
by half of its size when resized. shrink dynamically, however it grows by
double of its size when resized.
ArrayList gives better performance (fast) for Vector is slow compared to ArrayList.
operations such as search, add, delete etc. This is Vector operations gives poor
because it is non-synchronized, which means performance as they are thread-safe, the
multiple threads can perform different operations on thread which works on Vector gets a lock
it at the same time. on it which makes other thread wait till
the lock is released.
ArrayList uses iterator to traverse the elements. Vector can use iterator as well as
Enumeration to traverse the elements.
1/4
Other key differences:
fail-fast: First let me explain what is fail-fast: If the collection (ArrayList, vector etc) gets
structurally modified by any means, except the add or remove methods of iterator, after creation
of iterator then the iterator will throw ConcurrentModificationException. Structural modification
refers to the addition or deletion of elements from the collection.
As per the Vector javadoc, the Enumeration returned by Vector is not fail-fast. On the other side
the iterator and listIterator returned by ArrayList are fail-fast.
Legacy?: The vector was not the part of collection framework, it has been included in collections
later. It can be considered as Legacy code. There is nothing about Vector which List collection
cannot do. Therefore Vector should be avoided. If there is a need of thread-safe operation make
ArrayList synchronized as discussed in the next section of this post or use
CopyOnWriteArrayList which is a thread-safe variant of ArrayList.
There are few similarities between these classes which are as follows:
Update: Even if you need to perform synchronized operations, you can still use ArrayList by
converting it to a Synchronized ArrayList.
2/4
//Use [Link] method
List list = [Link](new ArrayList());
...
import [Link].*;
class JavaExample{
public static void main(String args[]){
Output:
3/4
Example of Vector in Java
In this example, we have created a vector and added few elements to it. We are iterating this
vector using enumeration.
import [Link].*;
class JavaExample{
public static void main(String args[]){
Vector<String> names=new Vector<String>();
[Link]("Chaitanya");
[Link]("Ajeet");
[Link]("Hari");
Output:
4/4
Difference between HashMap and Hashtable
What is the Difference between HashMap and Hashtable? This is one of the frequently asked
interview questions for Java/J2EE professionals. HashMap and Hashtable both classes
implements [Link] interface, however there are differences in the way they work and their
usage. Here we will discuss the differences between these classes.
HashMap vs Hashtable
1) HashMap is non-synchronized. This means if it’s used in multithread environment then more
than one thread can access and process the HashMap simultaneously.
Hashtable is synchronized. It ensures that no more than one thread can access the Hashtable at a
given moment of time. The thread which works on Hashtable acquires a lock on it to make the
other threads wait till its work gets completed.
2) HashMap allows one null key and any number of null values.
3) HashMap implementation LinkedHashMap maintains the insertion order and TreeMap sorts the
mappings based on the ascending order of keys.
Hashtable doesn’t guarantee any kind of order. It doesn’t maintain the mappings in any particular
order.
4) Initially Hashtable was not the part of collection framework it has been made a collection
framework member later after being retrofitted to implement the Map interface.
HashMap implements Map interface and is a part of collection framework since the beginning.
5) Another difference between these classes is that the Iterator of the HashMap is a fail-fast and it
throws ConcurrentModificationException if any other Thread modifies the map structurally by
adding or removing any element except iterator’s own remove() method. In Simple words fail-fast
means: When calling [Link](), if any modification has been made between the moment the
iterator was created and the moment next() is called, a ConcurrentModificationException is
immediately thrown.
For e.g.
HashMap:
1/2
HashMap hm= new HashMap();
....
....
Set keys = [Link]();
for (Object key : keys) {
//it will throw the ConcurrentModificationException here
[Link](object & value pair here);
}
Hashtable:
2) Synchronized operation gives poor performance so it should be avoided until unless required.
Hence for non-thread environment HashMap should be used without any doubt.
2/2
Difference between Iterator and ListIterator in java
Here we will discuss the differences between Iterator and ListIterator. Both of these interfaces are
used for traversing but still there are few differences in the way they can be used for traversing a
collection. I would recommend you to go through the following tutorials to understand these
interfaces better before going through the differences.
Java – Iterator
Java – ListIterator
Iterator vs ListIterator
1) Iterator is used for traversing List and Set both.
We can use ListIterator to traverse List only, we cannot traverse Set using ListIterator.
Using ListIterator, we can traverse a List in both the directions (forward and Backward).
We can obtain indexes at any point of time while traversing a list using ListIterator. The methods
nextIndex() and previousIndex() are used for this purpose.
We can add element at any point of time while traversing a list using ListIterator.
By using set(E e) method of ListIterator we can replace the last element returned by next() or
previous() methods.
6) Methods of Iterator:
hasNext()
next()
remove()
Methods of ListIterator:
add(E e)
hasNext()
1/2
hasPrevious()
next()
nextIndex()
previous()
previousIndex()
remove()
set(E e)
References:
Iterator javadoc
ListIterator javadoc
2/2
Difference between list set and map in java?
List, Set and Map are the interfaces which implements Collection interface. Here we will discuss
difference between List Set and Map in Java.
3) Order: List and all of its implementation classes maintains the insertion order.
Set doesn’t maintain any order; still few of its classes sort the elements in an order such as
LinkedHashSet maintains the elements in insertion order.
Similar to Set Map also doesn’t stores the elements in an order, however few of its classes does
the same. For e.g. TreeMap sorts the map in the ascending order of keys and LinkedHashMap
sorts the elements in the insertion order, the order in which the elements got added to the
LinkedHashMap.
1/1
Difference between throw and throws in java
In this guide, we will discuss the difference between throw and throws keywords. Before going
though the difference, refer my previous tutorials about throw and throws.
2. If we see syntax wise than throw is followed by an instance of Exception class and throws is
followed by exception class names.
For example:
and
throws ArithmeticException;
3. Throw keyword is used in the method body to throw an exception, while throws is used in
method signature to declare the exceptions that can occur in the statements present in the
method.
For example:
Throw:
...
void myMethod() {
try {
//throwing arithmetic exception using throw
throw new ArithmeticException("Something went wrong!!");
}
catch (Exception exp) {
[Link]("Error: "+[Link]());
}
}
...
Throws:
...
//Declaring arithmetic exception using throws
void sample() throws ArithmeticException{
//Statements
}
...
1/3
4. You can throw one exception at a time but you can handle multiple exceptions by declaring
them using throws keyword.
For example:
Throw:
void myMethod() {
//Throwing single exception using throw
throw new ArithmeticException("An integer should not be divided by zero!!");
}
..
Throws:
These were the main differences between throw and throws in Java. Lets see complete
examples of throw and throws keywords.
Throw Example
To understand this example you should know what is throw keyword and how it works, refer this
guide: throw keyword in java.
Output:
2/3
Throws Example
To understand this example you should know what is throws clause and how it is used in method
declaration for exception handling, refer this guide: throws in java.
Output:
3/3
Does Java support Multiple inheritance?
When one class extends more than one classes then this is called multiple inheritance. For
example: Class C extends class A and B then this type of inheritance is known as multiple
inheritance. Java doesn’t allow multiple inheritance. In this article, we will discuss why java doesn’t
allow multiple inheritance and how we can use interfaces instead of classes to achieve the same
purpose.
To understand the basics of inheritance, refer this main guide: Inheritance in Java
1/2
Can we implement more than one interfaces in a class
Yes, we can implement more than one interfaces in our program because that doesn’t cause any
ambiguity(see the explanation below).
interface X
{
public void myMethod();
}
interface Y
{
public void myMethod();
}
class JavaExample implements X, Y
{
public void myMethod()
{
[Link]("Implementing more than one interfaces");
}
public static void main(String args[]){
JavaExample obj = new JavaExample();
[Link]();
}
}
Output:
As you can see that the class implemented two interfaces. A class can implement any number of
interfaces. In this case there is no ambiguity even though both the interfaces are having same
method. Why? Because methods in an interface are always abstract by default, which doesn’t let
them give their implementation (or method definition ) in interface itself.
2/2
How to convert an array to ArrayList in java
In the last tutorial, you learned how to convert an ArrayList to Array in Java. In this guide, you will
learn how to convert an array to ArrayList.
Example:
In this example, we are using [Link]() method to convert an Array to ArrayList.
Here, we have an array cityNames with four elements. We have converted this array to an
ArrayList cityList. After conversion, this arraylist has four elements, we have added two more
elements to it using add() method.
In the end of the program, we are printing the elements of the ArrayList, which displays 6
elements, four elements that were added to arraylist from array and 2 new elements that are
added using add() method.
import [Link].*;
public class JavaExample {
public static void main(String[] args) {
Output:
1/4
Agra
Mysore
Chandigarh
Bhopal
Chennai
Delhi
OR
Example:
import [Link].*;
public class JavaExample {
public static void main(String[] args) {
//ArrayList declaration
ArrayList<String> arraylist= new ArrayList<String>();
//print ArrayList
for (String str: arraylist)
{
[Link](str);
}
}
}
Output:
2/4
Hi
Hello
Howdy
Bye
String1
String2
To read the whole array, we are using [Link] property. The [Link] property returns the
number of elements in the array. In the following example, since the array contains four
elements, this will return 4. Thus we can say that the for loop runs from i=0 to i<4
In the end, we are displaying ArrayList elements using advanced for loop.
import [Link].*;
public class JavaExample {
public static void main(String[] args) {
//ArrayList declaration
ArrayList<String> arrayList= new ArrayList<String>();
//Initializing Array
String array[] = {"Text1","Text2","Text3","Text4"};
3/4
Output:
Text1
Text2
Text3
Text4
4/4
How to get current date and time in java
By using SimpleDateFormat and Date/Calendar class, we can easily get current date and time
in Java. In this tutorial we will see how to get the current date and time using Date and Calendar
class and how to get it in the desired format using SimpleDateFormat class.
Specify the desired pattern for the date and time. Similar to the step 1 of above method.
Create an object of Calendar class by calling getInstance() method of it.
Call the format() method of DateFormat and pass the [Link]() as a parameter
to the method.
1/4
Complete java code for getting current date and time
import [Link];
import [Link];
import [Link];
import [Link];
Output:
21/10/17 22:13:06
21/10/17 22:13:06
Every time I run the above code it would fetch the current date and time.
Note: In order to get the output in above format I have specified the date/time pattern in the
program (Note the first statement of the program DateFormat df = new
SimpleDateFormat("dd/MM/yy HH:mm:ss");.
However if you want the output in any other date format, just modify the pattern accordingly. For
e.g. To get the date only, the pattern would be dd-MM-yyyy: replace the statement with this one:
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
While specifying the pattern be careful with the case. For e.g. ‘s’ (small s) represents second while
‘S'(Capital s) represents Millisecond.
At the end of this guide, I have shared the complete chart of symbols that we can use in
patterns to get the date and time in desired format
2/4
import [Link];
import [Link];
import [Link];
public class Example {
public static void main(String[] args) {
//"hh" in pattern is for 12 hour time format and "aa" is for AM/PM
SimpleDateFormat dateTimeInGMT = new SimpleDateFormat("yyyy-MMM-dd hh:mm:ss aa");
//Setting the time zone
[Link]([Link]("GMT"));
[Link]([Link](new Date()));
}
}
Output:
2017-Oct-21 06:03:42 PM
Update: To get the current date and time in Java 8 refer this guide.
Here is the complete chart which will help you to define the pattern in SimpleDateFormat.
3/4
K Hour in am/pm (0-11) Number 0
4/4
How to loop LinkedList in Java
In the last tutorial we discussed LinkedList and it’s methods with example. Here we will see how to
loop/iterate a LinkedList. There are four ways in which a LinkedList can be iterated –
1. For loop
2. Advanced For loop
3. Iterator
4. While Loop
Example:
In this example we have a LinkedList of String Type and we are looping through it using all the
four mentioned methods.
1/3
package [Link];
import [Link].*;
/*for loop*/
[Link]("**For loop**");
for(int num=0; num<[Link](); num++)
{
[Link]([Link](num));
}
/*Using Iterator*/
[Link]("**Iterator**");
Iterator i = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}
}
Output:
2/3
**For loop**
Apple
Orange
Mango
**Advanced For loop**
Apple
Orange
Mango
**Iterator**
Apple
Orange
Mango
**While Loop**
Apple
Orange
Mango
3/3
How to sort Hashtable in java
Hashtable doesn’t preserve the insertion order, neither it sorts the inserted data based on keys or
values. Which means no matter what keys & values you insert into Hashtable, the result would not
be in any particular order.
For example: Lets have a look at the below program and its output:
import [Link].*;
public class HashtableDemo
{
public static void main(String args[])
{
Hashtable<Integer, String> ht= new Hashtable<Integer, String>();
[Link](10, "Chaitanya");
[Link](1, "Ajeet");
[Link](11, "Test");
[Link](9, "Demo");
[Link](3, "Anuj");
Output:
10: Chaitanya
9: Demo
3: Anuj
1: Ajeet
11: Test
As you can see that the output key-value pairs are in random order. Neither we got insertion order
nor the values are sorted based on keys or values.
The solution
The are ways to sort Hashtable using [Link] and [Link], however best
thing to do is use LinkedHashMap or TreeMap.
1/3
Use LinkedHashMap: When you want to preserve the insertion order.
Use TreeMap: When you want to sort the key-value pairs.
Using LinkedHashMap
import [Link].*;
public class LinkedHashMapDemo
{
public static void main(String args[])
{
LinkedHashMap<Integer, String> lhm= new LinkedHashMap<Integer, String>();
[Link](10, "Chaitanya");
[Link](1, "Ajeet");
[Link](11, "Test");
[Link](9, "Demo");
[Link](3, "Anuj");
Output:
10: Chaitanya
1: Ajeet
11: Test
9: Demo
3: Anuj
What if we want to get the result sorted? Use TreeMap. Refer below example:
Use TreeMap
2/3
import [Link].*;
public class TreeMapDemo
{
public static void main(String args[])
{
TreeMap<Integer, String> tm= new TreeMap<Integer, String>();
[Link](10, "Chaitanya");
[Link](1, "Ajeet");
[Link](11, "Test");
[Link](9, "Demo");
[Link](3, "Anuj");
// Get a set of the entries
Set set = [Link]();
// Get an iterator
Iterator i = [Link]();
// Display elements
while([Link]()) {
[Link] me = ([Link])[Link]();
[Link]([Link]() + ": ");
[Link]([Link]());
}
}
}
Output:
1: Ajeet
3: Anuj
9: Demo
10: Chaitanya
11: Test
As you can see, the output we got is sorted based on the keys.
3/3
How to synchronize HashMap in Java with example
HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on
it then we must need to synchronize it explicitly. In this tutorial we will see how to synchronize
HashMap.
Example:
In this example we have a HashMap<Integer, String> it is having integer keys and String type
values. In order to synchronize it we are using [Link](hashmap) it returns
a thread-safe map backed up by the specified HashMap.
Syntax:
Complete Code:
1/2
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class HashMapSyncExample {
public static void main(String args[]) {
HashMap<Integer, String> hmap= new HashMap<Integer, String>();
[Link](2, "Anil");
[Link](44, "Ajit");
[Link](1, "Brad");
[Link](4, "Sachin");
[Link](88, "XYZ");
Output:
1: Brad
2: Anil
4: Sachin
88: XYZ
44: Ajit
2/2
Java – Difference between HashSet and TreeSet
In this article we are gonna discuss the differences between HashSet and TreeSet.
HashSet vs TreeSet
1) HashSet gives better performance (faster) than TreeSet for the operations like add, remove,
contains, size etc. HashSet offers constant time cost while TreeSet offers log(n) time cost for such
operations.
2) HashSet does not maintain any order of elements while TreeSet elements are sorted in
ascending order by default.
Similarities:
1) Both HashSet and TreeSet does not hold duplicate elements, which means both of these are
duplicate free.
2) If you want a sorted Set then it is better to add elements to HashSet and then convert it into
TreeSet rather than creating a TreeSet and adding elements to it.
3) Both of these classes are non-synchronized that means they are not thread-safe and should be
synchronized explicitly when there is a need of thread-safe operations.
Examples:
1/3
HashSet example
import [Link];
class HashSetDemo{
public static void main(String[] args) {
// Create a HashSet
HashSet<String> hset = new HashSet<String>();
Output:
HashSet contains:
Rick
Singh
Ram
Kevin
Abhijeet
2/3
TreeSet example
import [Link];
class TreeSetDemo{
public static void main(String[] args) {
// Create a TreeSet
TreeSet<String> tset = new TreeSet<String>();
TreeSet contains:
Abhijeet
Kevin
Ram
Rick
Singh
3/3
Java 8 – Filter a Map by keys and values
In the previous tutorial we learned about Java Stream Filter. In this guide, we will see how to use
Stream filter() method to filter a Map by keys and Values.
import [Link];
import [Link];
import [Link];
public class Example {
public static void main(String[] args) {
Map<Integer, String> hmap = new HashMap<Integer, String>();
[Link](11, "Apple");
[Link](22, "Orange");
[Link](33, "Kiwi");
[Link](44, "Banana");
Output:
1/3
Java 8 – Filter Map by Values
import [Link];
import [Link];
import [Link];
public class Example {
public static void main(String[] args) {
Map<Integer, String> hmap = new HashMap<Integer, String>();
[Link](11, "Apple");
[Link](22, "Orange");
[Link](33, "Kiwi");
[Link](44, "Banana");
Output:
Result: {22=Orange}
2/3
import [Link];
import [Link];
import [Link];
public class Example {
public static void main(String[] args) {
Map<Integer, String> hmap = new HashMap<Integer, String>();
[Link](1, "ABC");
[Link](2, "XCB");
[Link](3, "ABB");
[Link](4, "ZIO");
Output:
Result: {1=ABC}
3/3
Java 8 – Get Current Date and Time
In the past we learned how to get current date and time in Java using Date and Calendar classes.
Here we will see how can we get current date & time in Java 8.
Java 8 introduces a new date and time API [Link].* which has several classes, but the ones
that we can use to get the date and time are: [Link], [Link] &
[Link].
Output:
1/1
Java 8 Interface Changes – default method and static
method
Prior to java 8, interface in java can only have abstract methods. All the methods of interfaces are
public & abstract by default. Java 8 allows the interfaces to have default and static methods. The
reason we have default methods in interfaces is to allow the developers to add new methods to
the interfaces without affecting the classes that implements these interfaces.
We can say that concept of default method is introduced in java 8 to add the new methods
in the existing interfaces in such a way so that they are backward compatible. Backward
compatibility is adding new features without breaking the old code.
Static methods in interfaces are similar to the default methods except that we cannot override
these methods in the classes that implements these interfaces.
1/6
interface MyInterface{
/* This is a default method so we need not
* to implement this method in the implementation
* classes
*/
default void newMethod(){
[Link]("Newly added default method");
}
/* Already existing public and abstract method
* We must need to implement this method in
* implementation classes.
*/
void existingMethod(String str);
}
public class Example implements MyInterface{
// implementing abstract method
public void existingMethod(String str){
[Link]("String is: "+str);
}
public static void main(String[] args) {
Example obj = new Example();
}
}
Output:
2/6
interface MyInterface{
/* This is a default method so we need not
* to implement this method in the implementation
* classes
*/
default void newMethod(){
[Link]("Newly added default method");
}
}
}
Output:
3/6
Java 8 – Abstract classes vs interfaces
With the introduction of default methods in interfaces, it seems that the abstract classes are same
as interface in java 8. However this is not entirely true, even though we can now have concrete
methods(methods with body) in interfaces just like abstract class, this doesn’t mean that they are
same. There are still few differences between them, one of them is that abstract class can have
constructor while in interfaces we can’t have constructors.
The purpose of interface is to provide full abstraction, while the purpose of abstract class is to
provide partial abstraction. This still holds true. The interface is like a blueprint for your class, with
the introduction of default methods you can simply say that we can add additional features in the
interfaces without affecting the end user classes.
4/6
interface MyInterface{
}
}
Output:
Error: Duplicate default methods named newMethod with the parameters () and () are
inherited from the types MyInterface2 and MyInterface
This is because we have the same method in both the interface and the compiler is not sure which
method to be invoked.
5/6
interface MyInterface{
}
}
Output:
6/6
Java Annotations tutorial with examples
Java Annotations allow us to add metadata information into our source code, although they are
not a part of the program itself. Annotations were added to the java from JDK 5. Annotation has no
direct effect on the operation of the code they annotate (i.e. it does not affect the execution of the
program).
In this tutorial we are going to cover following topics: Usage of annotations, how to apply
annotations, what predefined annotation types are available in the Java and how to create custom
annotations.
Annotations basics
An annotation always starts with the symbol @ followed by the annotation name. The symbol @
indicates to the compiler that this is an annotation.
@Override
void myMethod() {
//Do something
}
1/7
What this annotation is exactly doing here is explained in the next section but to be brief it is
instructing compiler that myMethod() is a overriding method which is overriding the method
(myMethod()) of super class.
@Override
@Deprecated
@SuppressWarnings
1) @Override:
While overriding a method in the child class, we should use this annotation to mark that method.
This makes code readable and avoid maintenance issues, such as: while changing the method
signature of parent class, you must change the signature in child classes (where this annotation is
being used) otherwise compiler would throw compilation error. This is difficult to trace when you
haven’t used this annotation.
Example:
@Override
public void justaMethod() {
[Link]("Child class method");
}
}
I believe the example is self explanatory. To read more about this annotation, refer this article:
@Override built-in annotation.
2) @Deprecated
@Deprecated annotation indicates that the marked element (class, method or field) is deprecated
and should no longer be used. The compiler generates a warning whenever a program uses a
method, class, or field that has already been marked with the @Deprecated annotation. When an
2/7
element is deprecated, it should also be documented using the Javadoc @deprecated tag, as
shown in the following example. Make a note of case difference with @Deprecated and
@deprecated. @deprecated is used for documentation purpose.
Example:
/**
* @deprecated
* reason for why it was deprecated
*/
@Deprecated
public void anyMethodHere(){
// Do something
}
Now, whenever any program would use this method, the compiler would generate a warning. To
read more about this annotation, refer this article: Java – @Deprecated annotation.
3) @SuppressWarnings
This annotation instructs compiler to ignore specific warnings. For example in the below code, I
am calling a deprecated method (lets assume that the method deprecatedMethod() is marked with
@Deprecated annotation) so the compiler should generate a warning, however I am using
@@SuppressWarnings annotation that would suppress that deprecation warning.
@SuppressWarnings("deprecation")
void myMethod() {
[Link]();
}
3/7
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Documented
@Target([Link])
@Inherited
@Retention([Link])
public @interface MyCustomAnnotation{
int studentAge() default 18;
String studentName();
String stuAddress();
String stuStream() default "CSE";
}
Note: All the elements that have default values set while creating annotations can be skipped
while using annotation. For example if I’m applying the above annotation to a class then I would
do it like this:
@MyCustomAnnotation(
studentName="Chaitanya",
stuAddress="Agra, India"
)
public class MyClass {
...
}
As you can see, we have not given any value to the studentAge and stuStream elements as it is
optional to set the values of these elements (default values already been set in Annotation
definition, but if you want you can assign new value while using annotation just the same way as
we did for other elements). However we have to provide the values of other elements (the
elements that do not have default values set) while using annotation.
Note: We can also have array elements in an annotation. This is how we can use them:
Annotation definition:
@interface MyCustomAnnotation {
int count();
String[] books();
}
Usage:
4/7
@MyCustomAnnotation(
count=3,
books={"C++", "Java"}
)
public class MyClass {
Lets back to the topic again: In the custom annotation example we have used these four
annotations: @Documented, @Target, @Inherited & @Retention. Lets discuss them in detail.
@Documented
@Documented annotation indicates that elements using this annotation should be documented by
JavaDoc. For example:
[Link]
@Documented
public @interface MyCustomAnnotation {
//Annotation body
}
@MyCustomAnnotation
public class MyClass {
//Class body
}
While generating the javadoc for class MyClass, the annotation @MyCustomAnnotation would be
included in that.
@Target
It specifies where we can use the annotation. For example: In the below code, we have defined
the target type as METHOD which means the below annotation can only be used on methods.
import [Link];
import [Link];
@Target({[Link]})
public @interface MyCustomAnnotation {
5/7
Note: 1) If you do not define any Target type that means annotation can be applied to any
element.
2) Apart from [Link], an annotation can have following possible Target values.
[Link]
[Link]
[Link]
[Link]
ElementType.ANNOTATION_TYPE
[Link]
ElementType.LOCAL_VARIABLE
[Link]
@Inherited
The @Inherited annotation signals that a custom annotation used in a class should be inherited by
all of its sub classes. For example:
[Link]
@Inherited
public @interface MyCustomAnnotation {
@MyCustomAnnotation
public class MyParentClass {
...
}
Here the class MyParentClass is using annotation @MyCustomAnnotation which is marked with
@inherited annotation. It means the sub class MyChildClass inherits the @MyCustomAnnotation.
@Retention
It indicates how long annotations with the annotated type are to be retained.
import [Link];
import [Link];
@Retention([Link])
@interface MyCustomAnnotation {
6/7
Here we have used [Link]. There are two other options as well. Lets see what
do they mean:
[Link]: The annotation should be available at runtime, for inspection via java
reflection.
[Link]: The annotation would be in the .class file but it would not be available at
runtime.
[Link]: The annotation would be available in the source code of the program,
it would neither be in the .class file nor be available at the runtime.
That’s all for this topic “Java Annotation”. Should you have any questions, feel free to drop a line
below.
7/7
Java AWT tutorial for beginners
AWT stands for Abstract Window Toolkit. It is a platform dependent API for creating Graphical
User Interface (GUI) for java programs.
Why AWT is platform dependent? Java AWT calls native platform (Operating systems)
subroutine for creating components such as textbox, checkbox, button etc. For example an AWT
GUI having a button would have a different look and feel across platforms like windows, Mac OS
& Unix, this is because these platforms have different look and feel for their native buttons and
AWT directly calls their native subroutine that creates the button. In simple, an application build on
AWT would look like a windows application when it runs on Windows, but the same application
would look like a Mac application when runs on Mac OS.
AWT is rarely used now days because of its platform dependent and heavy-weight nature. AWT
components are considered heavy weight because they are being generated by underlying
operating system (OS). For example if you are instantiating a text box in AWT that means you are
actually asking OS to create a text box for you.
1/6
Swing is a preferred API for window based applications because of its platform independent and
light-weight nature. Swing is built upon AWT API however it provides a look and feel unrelated to
the underlying platform. It has more powerful and flexible components than AWT. In addition to
familiar components such as buttons, check boxes and labels, Swing provides several advanced
components such as tabbed panel, scroll panes, trees, tables, and lists. We will discuss Swing in
detail in a separate tutorial.
AWT hierarchy
Types of containers:
As explained above, a container is a place wherein we add components like text field, button,
checkbox etc. There are four types of containers available in AWT: Window, Frame, Dialog and
2/6
Panel. As shown in the hierarchy diagram above, Frame and Dialog are subclasses of Window
class.
3/6
AWT Example 1: creating Frame by extending Frame class
import [Link].*;
/* We have extended the Frame class here,
* thus our class "SimpleExample" would behave
* like a Frame
*/
public class SimpleExample extends Frame{
SimpleExample(){
Button b=new Button("Button!!");
Output:
4/6
AWT Example 2: creating Frame by creating instance of Frame class
import [Link].*;
public class Example2 {
Example2()
{
//Creating Frame
Frame fr=new Frame();
//Creating a label
Label lb = new Label("UserId: ");
[Link](true);
}
public static void main(String args[])
{
Example2 ex = new Example2();
}
}
5/6
Output:
6/6
Java Enum Tutorial with examples
An enum is a special type of data type which is basically a collection (set) of constants. In this
tutorial we will learn how to use enums in Java and what are the possible scenarios where we can
use them.
Here we have a variable Directions of enum type, which is a collection of four constants EAST,
WEST, NORTH and SOUTH.
The variable dir is of type Directions (that is a enum type). This variable can take any value, out
of the possible four values (EAST, WEST, NORTH, SOUTH). In this case it is set to NORTH.
if(dir == [Link]) {
// Do something. Write your logic
} else if(dir == [Link]) {
// Do something else
} else if(dir == [Link]) {
// Do something
} else {
/* Do Something. Write logic for
* the remaining constant SOUTH
*/
}
1/5
Enum Example
This is just an example to demonstrate the use enums. If you understand the core part and basics,
you would be able to write your own logic based on the requirement.
Output:
Direction: North
2/5
public enum Directions{
EAST,
WEST,
NORTH,
SOUTH
}
public class EnumDemo
{
Directions dir;
public EnumDemo(Directions dir) {
[Link] = dir;
}
public void getMyDirection() {
switch (dir) {
case EAST:
[Link]("In East Direction");
break;
case WEST:
[Link]("In West Direction");
break;
case NORTH:
[Link]("In North Direction");
break;
default:
[Link]("In South Direction");
break;
}
}
Output:
In East Direction
In South Direction
3/5
How to iterate through an Enum variable
class EnumDemo
{
public static void main(String[] args) {
for (Directions dir : [Link]()) {
[Link](dir);
}
}
}
Directions(String code) {
[Link] = code;
}
Output:
S
E
4/5
As you can see in this example we have a field shortCode for each of the constant, along with a
method getDirectionCode() which is basically a getter method for this field. When we define a
constant like this EAST ("E"), it calls the enum constructor (Refer the constructor Directions in
the above example) with the passed argument. This way the passed value is set as an value for
the field of the corresponding enum’s constant [EAST(“E”) => Would call constructor
Directions(“E”) => [Link] = code => [Link] = “E” => shortCode field of constant
EAST is set to “E”].
1) While defining Enums, the constants should be declared first, prior to any fields or methods.
2) When there are fields and methods declared inside Enum, the list of enum constants must end
with a semicolon(;).
5/5
Java Functional Interfaces
An interface with only single abstract method is called functional interface. You can either use
the predefined functional interface provided by Java or create your own functional interface and
use it. You can check the predefined functional interfaces here: predefined functional interfaces
they all have only one abstract method. That is the reason,they are also known as Single Abstract
Method interfaces (SAM Interfaces).
To use lambda expression in Java, you need to either create your own functional interface or use
the pre defined functional interface provided by Java. While creating your own functional interface,
mark it with @FunctionalInterface annotation, this annotation is introduced in Java 8. Although
its optional, you should use it so that you get a compilation error if the interface you marked with
this annotation is not following the rules of functional interfaces.
@FunctionalInterface
interface MyFunctionalInterface {
Output:
Result: 112
1/4
Example 2: Using predefined functional interface
import [Link];
}
}
Output:
Result: 112
2/4
import [Link].*;
import [Link].*;
import [Link].*;
class Example extends JFrame
{
JButton button;
public Example()
{
setTitle("Button Action Example without Lambda Expression");
setSize(400,300);
setVisible(true);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
});
add(button);
}
public static void main(String args[])
{
new Example();
}
}
3/4
import [Link].*;
import [Link].*;
class Example extends JFrame
{
JButton button;
public Example()
{
setTitle("Button Action Example using Lambda Expression");
setSize(400,300);
setVisible(true);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(button);
}
public static void main(String args[])
{
new Example();
}
}
4/4
Java Iterator with examples
Iterator is used for iterating (looping) various collection classes such as HashMap, ArrayList,
LinkedList etc. In this tutorial, we will learn what is iterator, how to use it and what are the issues
that can come up while using it. Iterator took place of Enumeration, which was used to iterate
legacy classes such as Vector. We will also see the differences between Iterator and Enumeration
in this tutorial.
import [Link];
import [Link];
Iterator it = [Link]();
while([Link]()) {
String obj = (String)[Link]();
[Link](obj);
}
}
Output:
1/6
Chaitanya
Steve
Jack
In the above example we have iterated ArrayList without using Generics. Program ran fine without
any issues, however there may be a possibility of ClassCastException if you don’t use Generics
(we will see this in next section).
import [Link];
import [Link];
Iterator it = [Link]();
while([Link]()) {
String obj = (String)[Link]();
[Link](obj);
}
}
}
Output:
In the above program we tried to add Integer value to the ArrayList of String but we didn’t get any
compile time error because we didn’t use Generics. However since we type casted the integer
value to String in the while loop, we got ClassCastException.
2/6
Use Generics:
Here we are using Generics so we didn’t type caste the output. If you try to add a integer value to
ArrayList in the below program, you would get compile time error. This way we can avoid
ClassCastException.
import [Link];
import [Link];
Iterator<String> it = [Link]();
while([Link]()) {
String obj = [Link]();
[Link](obj);
}
}
}
Note: We did not type cast iterator returned value[[Link]()] as it is not required when using
Generics.
boolean hasNext()
It returns true, if there is an element available to be read. In other words, if iteration has remaining
elements.
2. next():
E next()
It returns the next element in the iteration. It throws NoSuchElementException, if there is no next
element available in iteration. This is why we use along with hasNext() method, which checks if
there are remaining elements in the iteration, this make sure that we don’t encounter
NoSuchElementException.
3. remove():
3/6
It removes the last element returned by the Iterator, however this can only be called once per
next() call.
4. forEachRemaining():
import [Link].*;
class JavaExample {
public static void main(String[] args)
{
HashMap<String, Integer> hm
= new HashMap<String, Integer>();
[Link]("Apple", 100);
[Link]("Orange", 75);
[Link]("Banana", 30);
[Link]("HashMap elements: " + hm);
// Getting an iterator
Iterator hmIterator = [Link]().iterator();
while ([Link]()) {
[Link] mapElement
= ([Link])[Link]();
int price = (int)[Link]();
[Link]([Link]() + " , "
+ price);
}
}
}
Output:
4/6
Difference between Iterator and Enumeration
An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections
Framework. Iterators differ from enumerations in two ways:
1) Iterators allow the caller to remove elements from the underlying collection during the iteration
with well-defined semantics.
2) Method names have been improved. hashNext() method of iterator replaced
hasMoreElements() method of enumeration, similarly next() replaced nextElement().
Advantages of Iterator
While iterating a collection class using loops, it is not possible to update the collection.
However, if you are iterating a collection using iterator, you can modify the collection using
remove() method, which removes the last element returned by iterator.
The iterator is specifically designed for collection classes so it works well for all the classes
in collection framework.
Java iterator has some very useful methods, which are easy to remember and use.
Disadvantages of Iterator
It is unidirectional, which means you cant iterate a collection backwards.
You can remove the element using iterator, however you cannot add an element during
iteration.
Unlike ListIterator which is used only for the classes extending List Interface, the iterator
class works for all the collection classes.
import [Link];
public class ExceptionDemo {
public static void main(String args[]){
ArrayList<String> books = new ArrayList<String>();
[Link]("C");
[Link]("Java");
[Link]("Cobol");
Output:
5/6
C
Exception in thread "main" [Link]
at [Link]$[Link](Unknown Source)
at [Link]$[Link](Unknown Source)
at [Link]([Link])
We cannot add or remove elements to the collection while using iterator over it.
6/6
Java Serialization
Here we are gonna discuss how to serialize and de-serialize an object and what is the use of it.
Example
This class implements Serializable interface which means it can be serialized. All the fields of this
class can be written to a file after being converted to stream of bytes, except those fields that are
declared transient. In the below example we have two transient fields, these fields will not take
part in serialization.
[Link]
1/4
public class Student implements [Link]{
private int stuRollNum;
private int stuAge;
private String stuName;
private transient String stuAddress;
private transient int stuHeight;
2/4
Serialization of Object
This class is writing an object of Student class to the [Link] file. We are using
FileOutputStream and ObjectOutputStream to write the object to File.
Note: As per the best practices of Java Serialization, the file name should have .ser extension.
import [Link];
import [Link];
import [Link];
public class SendClass
{
public static void main(String args[])
{
Student obj = new Student(101, 25, "Chaitanya", "Agra", 6);
try{
FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos);
[Link](obj);
[Link]();
[Link]();
[Link]("Serialzation Done!!");
}catch(IOException ioe){
[Link](ioe);
}
}
}
Output:
Serialzation Done!!
De-serialization of Object
This class would rebuilt the object of Student class after reading the stream of bytes from the file.
Observe the output of this class, student address and student height fields are having null & 0
values consecutively. This is because these fields were declared transient in the Student class.
3/4
import [Link];
import [Link];
import [Link];
public class AcceptClass {
Output:
Student Name:Chaitanya
Student Age:25
Student Roll No:101
Student Address:null
Student Height:0
4/4
Java static constructor – Is it really Possible to have them in
Java?
Have you heard of static constructor in Java? I guess yes but the fact is that they are not
allowed in Java. A constructor can not be marked as static in Java. Before I explain the reason
let’s have a look at the following piece of code:
1/5
Output: You would get the following error message when you try to run the above java code.
“modifier static not allowed here”
2/5
public class StaticDemo
{
public StaticDemo()
{
/*Constructor of this class*/
[Link]("StaticDemo");
}
}
public class StaticDemoChild extends StaticDemo
{
public StaticDemoChild()
{
/*By default super() is hidden here */
[Link]("StaticDemoChild");
}
public void display()
{
[Link]("Just a method of child class");
}
public static void main(String args[])
{
StaticDemoChild obj = new StaticDemoChild();
[Link]();
}
}
Output:
StaticDemo
StaticDemoChild
Just a method of child class
Did you notice? When we created the object of child class, it first invoked the constructor of
parent class and then the constructor of it’s own class. It happened because the new keyword
creates the object and then invokes the constructor for initialization, since every child class
constructor by default has super() as first statement which calls it’s parent class’s constructor.
The statement super() is used to call the parent class(base class) constructor.
This is the reason why constructor cannot be static – Because if we make them static they cannot
be called from child class thus object of child class cannot be created.
Another good point mentioned by Prashanth in the comment section: Constructor definition
should not be static because constructor will be called each and every time when object is
created. If you made constructor as static then the constructor will be called before object
creation same like main method.
3/5
Static Constructor Alternative – Static Blocks
Java has static blocks which can be treated as static constructor. Let’s consider the below
program –
4/5
public class StaticDemo{
static{
[Link]("static block of parent class");
}
}
public class StaticDemoChild extends StaticDemo{
static{
[Link]("static block of child class");
}
public void display()
{
[Link]("Just a method of child class");
}
public static void main(String args[])
{
StaticDemoChild obj = new StaticDemoChild();
[Link]();
}
}
Output:
static block of parent class
static block of child class
Just a method of child class
In the above example we have used static blocks in both the classes which worked perfectly. We
cannot use static constructor so it’s a good alternative if we want to perform a static task during
object creation.
5/5
Java static import with example
Static import allows you to access the static member of a class directly without using the fully
qualified name.
To understand this topic, you should have the knowledge of packages in Java. Static imports are
used for saving your time by making you type less. If you hate to type same thing again and again
then you may find such imports interesting.
class Demo1{
public static void main(String args[])
{
double var1= [Link](5.0);
double var2= [Link](30);
[Link]("Square of 5 is:"+ var1);
[Link]("Tan of 30 is:"+ var2);
}
}
Output:
Square of 5 is:2.23606797749979
Tan of 30 is:-6.405331196646276
Output:
1/2
Square of 5 is:2.23606797749979
Tan of 30 is:-6.405331196646276
Points to note:
1) Package import syntax:
If you are going to use static variables and methods a lot then it’s fine to use static imports. for
example if you wanna write a code with lot of mathematical calculations then you may want to use
static import.
Drawbacks
It makes the code confusing and less readable so if you are going to use static members very few
times in your code then probably you should avoid using it. You can also use wildcard(*) imports.
2/2
Java String to int Conversion
In this tutorial, you will learn how to convert a String to int in Java. If a String is made up of
digits like 1,2,3 etc, any arithmetic operation cannot be performed on it until it gets converted into
an integer value. In this tutorial we will see the following two ways to convert String to int:
Using [Link]()
Using [Link]()
1. Using [Link]()
The [Link]() method converts a String to a primitive int. I have covered this
method in detail here: [Link]() Method
2. Using [Link]()
The [Link]() method converts a String to an Integer object, which can then be
unboxed to a primitive int.
3. Handling Exceptions
Both of these methods throw NumberFormatException, if the string cannot be parsed as an int. It
is always a good practice to place the conversion code inside try block and handle this exception
in catch block to avoid unintentional termination of the program.
1/2
public class StringToIntExample {
public static void main(String[] args) {
String validNumber = "123";
String invalidNumber = "123a"; // Using [Link]() method
try {
int result = [Link](validNumber);
[Link]("Using [Link](): " + result);
} catch (NumberFormatException e) {
[Link]("Invalid number format: " + validNumber);
} // Using [Link]() method
try {
int result = [Link](validNumber);
[Link]("Using [Link](): " + result);
} catch (NumberFormatException e) {
[Link]("Invalid number format: " + validNumber);
} // Handling NumberFormatException for invalid input
try {
int result = [Link](invalidNumber);
[Link]("Using [Link](): " + result);
} catch (NumberFormatException e) {
[Link]("Invalid number format: " + invalidNumber);
}
}
}
Output:
2/2
Java Swing Tutorial for beginners
Swing is a part of Java Foundation classes (JFC), the other parts of JFC are java2D and Abstract
window toolkit (AWT). AWT, Swing & Java 2D are used for building graphical user interfaces
(GUIs) in java. In this tutorial we will mainly discuss about Swing API which is used for building
GUIs on the top of AWT and are much more light-weight compared to AWT.
1/4
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class SwingFirstExample {
// Creating JLabel
JLabel userLabel = new JLabel("User");
/* This method specifies the location and size
* of component. setBounds(x, y, width, height)
* here (x,y) are cordinates from the top left
* corner and remaining two arguments are the width
* and height of the component.
*/
[Link](10,20,80,25);
[Link](userLabel);
2/4
* enter user name.
*/
JTextField userText = new JTextField(20);
[Link](100,20,165,25);
[Link](userText);
Output:
In the above example we have used several components. Let’s discuss a bit about them first then
we will discuss them in detail in the next tutorials.
JFrame – A frame is an instance of JFrame. Frame is a window that can have title, border, menu,
buttons, text fields and several other components. A Swing application must have a frame to have
the components added to it.
JPanel – A panel is an instance of JPanel. A frame can have more than one panels and each
panel can have several components. You can also call them parts of Frame. Panels are useful for
grouping components and placing them to appropriate locations in a frame.
3/4
JLabel – A label is an instance of JLabel class. A label is unselectable text and images. If you
want to display a string or an image on a frame, you can do so by using labels. In the above
example we wanted to display texts “User” & “Password” just before the text fields , we did this by
creating and adding labels to the appropriate positions.
JTextField – Used for capturing user inputs, these are the text boxes where user enters the data.
JPasswordField – Similar to text fields but the entered data gets hidden and displayed as dots on
GUI.
JButton – A button is an instance of JButton class. In the above example we have a button
“Login”.
4/4
ListIterator in Java with examples
In the last tutorial, we discussed Iterator in Java using which we can traverse a List or Set in
forward direction. Here we will discuss ListIterator that allows us to traverse the list in both
directions (forward and backward).
ListIterator Example
In this example we are traversing an ArrayList in both the directions.
import [Link];
import [Link];
import [Link];
Output:
1/2
Traversing the list in forward direction:
Shyam
Rajat
Paul
Tom
Kate
Note: We can use Iterator to traverse List and Set both but using ListIterator we can only traverse
list. There are several other differences between Iterator and ListIterator, we will discuss them in
next post.
Methods of ListIterator
1) void add(E e): Inserts the specified element into the list (optional operation).
2) boolean hasNext(): Returns true if this list iterator has more elements when traversing the list in
the forward direction.
3) boolean hasPrevious(): Returns true if this list iterator has more elements when traversing the
list in the reverse direction.
4) E next(): Returns the next element in the list and advances the cursor position.
5) int nextIndex(): Returns the index of the element that would be returned by a subsequent call to
next().
6) E previous(): Returns the previous element in the list and moves the cursor position backwards.
7) int previousIndex(): Returns the index of the element that would be returned by a subsequent
call to previous().
8) void remove(): Removes from the list the last element that was returned by next() or previous()
(optional operation).
9) void set(E e): Replaces the last element returned by next() or previous() with the specified
element (optional operation).
2/2
Method References in Java 8
In the previous tutorial we learned lambda expressions in Java 8. Here we will discuss another
new feature of java 8, method reference. Method reference is a shorthand notation of a lambda
expression to call a method. For example:
If your lambda expression is like this:
[Link]::println
The :: operator is used in method reference to separate the class or object from the method
name(we will learn this with the help of examples).
@FunctionalInterface
interface MyInterface{
void display();
}
public class Example {
public void myMethod(){
[Link]("Instance Method");
}
public static void main(String[] args) {
Example obj = new Example();
// Method reference using the object of the class
MyInterface ref = obj::myMethod;
// Calling the method of functional interface
[Link]();
}
}
Output:
Instance Method
1/3
2. Method reference to a static method of a class
import [Link];
class Multiplication{
public static int multiply(int a, int b){
return a*b;
}
}
public class Example {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> product = Multiplication::multiply;
int pr = [Link](11, 5);
[Link]("Product of given number is: "+pr);
}
}
Output:
Output:
Aditya
Jon
Lucy
Negan
Rick
Sansa
Steve
2/3
4. Method reference to a constructor
@FunctionalInterface
interface MyInterface{
Hello display(String say);
}
class Hello{
public Hello(String say){
[Link](say);
}
}
public class Example {
public static void main(String[] args) {
//Method reference to a constructor
MyInterface ref = Hello::new;
[Link]("Hello World!");
}
}
Output:
Hello World!
3/3