0% found this document useful (0 votes)
6 views179 pages

Java 8 ForEach Method With Example-Combined

The document provides an overview of the Java 8 forEach method, demonstrating its usage for iterating over collections and streams with examples. It also explains the main() method in Java, its significance, syntax, and variations, along with access modifiers and garbage collection in Java. Additionally, it covers the differences between forEach and forEachOrdered methods, illustrating their behavior with parallel streams.

Uploaded by

nikhilhh2006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views179 pages

Java 8 ForEach Method With Example-Combined

The document provides an overview of the Java 8 forEach method, demonstrating its usage for iterating over collections and streams with examples. It also explains the main() method in Java, its significance, syntax, and variations, along with access modifiers and garbage collection in Java. Additionally, it covers the differences between forEach and forEachOrdered methods, illustrating their behavior with parallel streams.

Uploaded by

nikhilhh2006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java 8 forEach method with example

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);

Java 8 – forEach method to iterate a Stream


In this example we are iterating a Stream in Java using forEach() method.

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

Java – Stream forEachOrdered() Method Example


For sequential streams the order of elements is same as the order in the source, so the output
would be same whether you use forEach or forEachOrdered. However when working with parallel
streams, you would always want to use the forEachOrdered() method when the order matters to
you, as this method guarantees that the order of elements would be same as the source. Lets
take an example to understand the difference between forEach() and forEachOrdered().

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));

/* forEachOrdered - the output would always be in this order:


* Maggie, Michonne, Merle
*/
[Link]("Print using forEachOrdered");
[Link]()
.filter(f->[Link]("M"))
.parallel()
.forEachOrdered(n->[Link](n));
}
}

Output:

Print using forEach


Merle
Maggie
Michonne
Print using forEachOrdered
Maggie
Michonne
Merle

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.

What is a main() method in Java?


The main() method is the starting point of the program. JVM starts the execution of program
starting from the main() method.

Syntax of main() method:

public static void main(String args[])

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.

Can we have main() method defined without String args[] parameter?


If we have a main() method without String args[] in a program, the program will throw no
compilation error however we won’t be able to run the program as the JVM looks for the public
main method with the String args[] parameter and if it doesn’t find such method, it doesn’t run the
program.

Let’s try this:

1/4
public class JavaExample {

public static void main() {


[Link]("Hello!");
}
}

Output:

Error: Main method not found in class JavaExample, please define the main method as:
public static void main(String[] args)

As you can see that the program threw error at runtime.

Java – static block vs main method


As we learned in the previous article, static block is used to initialise the static data members.
Let’s run a program with static block and main method (static method) to see in which order they
run.

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.

What if a program doesn’t have a main method?


Let’s write a program without the main method to see whether it runs or not.

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]

Different ways to write main method in java


The following are the valid ways to write a main method in java:

public static void main(String[] args)

//We can interchange static and public


static public void main(String[] args)

//We can place the square brackets at the different locations


public static void main(String[] args)
public static void main(String []args)

Overloading of main() method in Java


We can overload the main method in Java. This allows us to have more than one main() method
in Java. However the signature of all the overloaded methods must be different. To learn more
about overloading, refer this guide: Method overloading in Java.

3/4
class JavaExample
{

public static void main(String args[])


{
[Link]("main method");
main(100);
main('A');
}
//Overloaded int main method
public static void main(int a)
{
[Link](a);
}
//Overloaded char main method
public static void main(char ch)
{
[Link](ch);
}
}

Output:

main method
100
A

Frequently Asked Questions


Why main method is used in Java?
The main method is used to specify the starting point of the program. This is the starting point of
our program from where the JVM starts execution of the program.

Can you have methods in main Java


No, you can’t declare a method inside main() method.

Can we have two main methods in Java


Yes we have can more than one main methods in java, however JVM will always calls String[]
argument main() method. Other main() methods will act as a Overloaded method. In order to
invoke these overloaded methods, we have to call them explicitly.

Can we override main method in Java?


No, we cannot override main method of java because it is a static method and we cannot
override a static method. The static method in java is associated with class which is why we don’t
need an object to call these. Therefore, it is not possible to override the main method in java.

Learn Java Programming: Java Tutorial

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

1. Default access modifier


When we do not mention any access modifier, it is called default access modifier. The scope of
this modifier is limited to the package only. This means that if we have a class with the default
access modifier in a package, only those classes that are in this package can access this class.
No other class outside this package can access this class. Similarly, if we have a default method
or data member in a class, it would not be visible in the class of another package. Lets see an
example to understand this:

Default Access Modifier Example in Java

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;

public class Addition {


/* Since we didn't mention any access modifier here, it would
* be considered as default.
*/
int addTwoNumbers(int a, int b){
return a+b;
}
}

[Link]

1/5
package xyzpackage;

/* We are importing the abcpackage


* but still we will get error because the
* class we are trying to use has default access
* modifier.
*/
import abcpackage.*;
public class Test {
public static void main(String args[]){
Addition obj = new Addition();
/* It will throw error because we are trying to access
* the default method in another package
*/
[Link](10, 21);
}
}

Output:

Exception in thread "main" [Link]: Unresolved compilation problem:


The method addTwoNumbers(int, int) from the type Addition is not visible
at [Link]([Link])

2. Private access modifier


The scope of private modifier is limited to the class only.

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.

Let’s see an example to understand this:

Private access modifier example in java


This example throws compilation error because we are trying to access the private data member
and method of class ABC in the class Example. The private data member and method are only
accessible within 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:

Compile - time error

3. Protected Access Modifier


Protected data member and method are only accessible by the classes of the same package and
the subclasses present in any package. You can also say that the protected access modifier is
similar to default access modifier with one exception that it has visibility in sub classes.
Classes cannot be declared protected. This access modifier is generally used in a parent child
relationship.

Protected access modifier example in Java


In this example the class Test which is present in another package is able to call the
addTwoNumbers() method, which is declared protected. This is because the Test class extends
class Addition and the protected modifier allows the access of protected members in subclasses
(in any packages).
[Link]

package abcpackage;
public class Addition {

protected int addTwoNumbers(int a, int b){


return a+b;
}
}

[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

4. Public access modifier


The members, methods and classes that are declared public can be accessed from anywhere.
This modifier doesn’t put any restriction on the access.

public access modifier example in java

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;

public class Addition {

public int addTwoNumbers(int a, int b){


return a+b;
}
}

[Link]

package xyzpackage;
import abcpackage.*;
class Test{
public static void main(String args[]){
Addition obj = new Addition();
[Link]([Link](100, 1));
}
}

Output:

101

Lets see the scope of these access modifiers in tabular form:

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.

When does java perform garbage collection?


1. When the object is no longer reachable:

BeginnersBook obj = new BeginnersBook();


obj = null;

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.

Another example is:

char[] sayhello = { 'h', 'e', 'l', 'l', 'o'};


String str = new String(sayhello);
str = null;

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.

2. When one reference is copied to another reference:

BeginnersBook obj1 = new BeginnersBook();


BeginnersBook obj2 = new BeginnersBook();
obj2 = obj1;

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).

Garbage Collection Example in Java


In this example we are demonstrating the garbage collection by calling [Link](). In this code
we have overridden a finalize() method. This method is invoked just before a object is destroyed
by java garbage collection process. This is the reason you would see in the output that this
method has been invoked twice.

public class JavaExample{


public static void main(String args[]){
/* Here we are intentionally assigning a null
* value to a reference so that the object becomes
* non reachable
*/
JavaExample obj=new JavaExample();
obj=null;

/* Here we are intentionally assigning reference a


* to the another reference b to make the object referenced
* by b unusable.
*/
JavaExample a = new JavaExample();
JavaExample b = new JavaExample();
b = a;
[Link]();
}
protected void finalize() throws Throwable
{
[Link]("Garbage collection is performed by JVM");
}
}

Output:

Garbage collection is performed by JVM


Garbage collection is performed by JVM

Phases of Garbage Collection


1. Marking: In this phase, the objects that are in use are marked. This is typically done by
traversing all the available objects in the heap memory.

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.

Syntax of Finally block


try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}

A Simple Example of finally block


Here you can see that the exception occurred in try block which has been handled in catch block,
after that finally block got executed.

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

Few Important points regarding finally block


1. A finally block must be associated with a try block, you cannot use finally without a try block.
You should place those statements in this block that must be executed always.

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:

Another example of finally block and return statement


You can see that even though we have return statement in the method, the finally block still runs.

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");
}
}
}

Output of above program:

This is Finally block


Finally block ran even after return statement
112

2/6
To see more examples of finally and return refer: Java finally block and return statement
.

Cases when the finally block doesn’t execute


The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.

Finally and Close()


close() statement is used to close all the open streams in a program. Its a good practice to use
close() inside finally block. Since finally block executes even if exception occurs so you can be
sure that all input and output streams are closed properly regardless of whether the exception
occurs or not.

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);
}
...

Finally block without catch


A try-finally block is possible without catch block. Which means a try block can be used with finally
without having a catch block.

3/6
...
InputStream input = null;
try {
input = new FileInputStream("[Link]");
}
finally {
if (input != null) {
try {
[Link]();
}catch (IOException exp) {
[Link](exp);
}
}
}
...

Finally block and [Link]()


[Link]() statement behaves differently than return statement. Unlike return statement
whenever [Link]() gets called in try block then Finally block doesn’t execute. Here is a code
snippet that demonstrate the same:

....
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
}

Examples of Try catch finally blocks

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:

First statement of try block


15
finally block
Out of try-catch-finally block

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:

First statement of try block


finally block
Exception in thread "main" [Link]: / by zero
at [Link]([Link])

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:

First statement of try block


ArithmeticException
finally block
Out of try-catch-finally block

6/6
Basics: All about Java threads

What are Java Threads?


A thread is a:

Facility to allow multiple activities within a single process


Referred as lightweight process
A thread is a series of executed statements
Each thread has its own program counter, stack and local variables
A thread is a nested sequence of method calls
Its shares memory, files and per-process state

Read: Multithreading in Java

Whats the need of a thread or why we use Threads?

To perform asynchronous or background processing


Increases the responsiveness of GUI applications
Take advantage of multiprocessor systems
Simplify program logic when there are multiple independent entities

What happens when a thread is invoked?

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

Proper co-ordination is required between threads accessing common variables [use of


synchronized and volatile] for consistence view of data
overuse of java threads can be hazardous to program’s performance and its maintainability.

Threads in Java

Java threads facility and API is deceptively simple:


Every java program creates at least one thread [ main() thread ]. Additional threads are created
through the Thread constructor or by instantiating classes that extend the Thread class.

Thread creation in Java

Thread implementation in java can be achieved in two ways:

1. Extending the [Link] class

1/4
2. Implementing the [Link] Interface

Note: The Thread and Runnable are available in the [Link].* package

1) By extending thread class

The class should extend Java Thread class.


The class should override the run() method.
The functionality that is expected by the Thread to be executed is written in the run()
method.

void start(): Creates a new thread and makes it runnable.


void run(): The new thread begins its life inside this method.

Example:

public class MyThread extends Thread {


public void run(){
[Link]("thread is running...");
}
public static void main(String[] args) {
MyThread obj = new MyThread();
[Link]();
}

2) By Implementing Runnable interface

The class should implement the Runnable interface


The class should implement the run() method in the Runnable interface
The functionality that is expected by the Thread to be executed is put in the run() method

Example:

public class MyThread implements Runnable {


public void run(){
[Link]("thread is running..");
}
public static void main(String[] args) {
Thread t = new Thread(new MyThread());
[Link]();
}

Extends Thread class vs Implements Runnable Interface?

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.

Thread life cycle in java

Read full article at: Thread life cycle in java

Ending Thread

A Thread ends due to the following reasons:

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.

Guidelines for synchronization

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.

Creating Threads in Java


There are two primary ways to create threads:

1. By Extending the Thread Class

class MyThread extends Thread {


public void run() {
[Link]("Thread is running...");
}
} public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link](); // Starts the thread and executes the `run` method
}
}

2. By Implementing the Runnable Interface

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

start(): Starts the thread, calling its run() method.


run(): Defines the code executed by the thread.
sleep(milliseconds): Pauses the thread for a specified duration.
join(): Waits for a thread to finish before continuing.
isAlive(): Checks if the thread is still running.
getName() and setName(String name): To retrieve or set a thread’s name.

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

A thread in Java goes through the following states:

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

class Task1 extends Thread {


public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Task 1 - Count: " + i);
}
}
} class Task2 extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Task 2 - Count: " + i);
}
}
} public class Main {
public static void main(String[] args) {
Task1 t1 = new Task1();
Task2 t2 = new Task2(); [Link]();
[Link]();
}
}

In this example, Task1 and Task2 run concurrently, and their outputs will interleave based on
thread scheduling.

Key Points

Multithreading is not deterministic; thread execution order may vary.


Proper synchronization is crucial for handling shared resources to avoid race conditions.
Java provides the Executor framework for managing thread pools and improving scalability.

If you’d like, I can provide additional details on advanced multithreading concepts like thread
pools, Callable, Future, or synchronized blocks.

Multitasking vs Multithreading vs Multiprocessing vs parallel processing


If you are new to java you may get confused among these terms as they are used quite frequently
when we discuss multithreading. Let’s talk about them in brief.

Multitasking: Ability to execute more than one task at the same time is known as multitasking.

Multithreading: We already discussed about it. It is a process of executing multiple threads


simultaneously. Multithreading is also known as Thread-based 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.

Methods: isAlive() and join()


In all the practical situations main thread should finish last else other threads which have
spawned from the main thread will also finish.
To know whether the thread has finished we can call isAlive() on the thread which returns
true if the thread is not finished.
Another way to achieve this by using join() method, this method when called from the
parent thread makes parent thread wait till child thread terminates.
These methods are defined in the Thread class.
We have used isAlive() method in the above examples too.

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.

A thread becomes “Not Runnable” when one of these events occurs:


If sleep method is invoked.
The thread calls the wait method.
The thread is blocking on I/O.

A thread dies naturally when the run method exits.

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);

2.2 Thread Priority

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.

2.3 isAlive() and join() methods

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.

3) A process is sometime referred as task. A thread is often referred as lightweight 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)

Per process items | Per thread items


------------------------------|-----------------
Address space | Program counter
Global variables | Registers
Open files | Stack
Child processes | State
Pending alarms |
Signals and signal handlers |
Accounting information |

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.

Java Lambda Expression Syntax


To create a lambda expression, we specify input parameters (if there are any) on the left side of
the lambda operator ->, and place the expression or block of statements on the right side of
lambda operator. For example, the lambda expression (x, y) -> x + y specifies that lambda
expression takes two arguments x and y and returns the sum of these.

//Syntax of lambda expression


(parameter_list) -> {function_body}

Lambda expression vs method in Java


A method (or function) in Java has these main parts:
1. Name
2. Parameter list
3. Body
4. return type.

A lambda expression in Java has these main parts:


Lambda expression only has body and parameter list.
1. No name – function is anonymous so we don’t care about the name
2. Parameter list
3. Body – This is the main part of the function.
4. No return type – The java 8 compiler is able to infer the return type by checking the code. you
need not to mention it explicitly.

Where to use the Lambdas in Java


To use lambda expression, you need to either create your own functional interface or use the pre
defined functional interface provided by Java. An interface with only single abstract method is
called functional interface(or Single Abstract method interface), for example: Runnable, callable,
ActionListener etc.

To use function interface:


Pre Java 8: We create anonymous inner classes.
Post Java 8: You can use lambda expression instead of anonymous inner classes.

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");

Button b=new Button("Click Here");


[Link](50,100,80,50);

[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");

Button b=new Button("Click Here");


[Link](50,100,80,50);

[Link](e -> [Link]("Hello World!"));


[Link](b);

[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.

Lets see few more examples of Lambda expressions.

Example 1: Java Lambda Expression with no parameter

@FunctionalInterface
interface MyFunctionalInterface {

//A method with no parameter


public String sayHello();
}
public class Example {

public static void main(String args[]) {


// lambda expression
MyFunctionalInterface msg = () -> {
return "Hello";
};
[Link]([Link]());
}
}

Output:

Hello

Example 2: Java Lambda Expression with single parameter

@FunctionalInterface
interface MyFunctionalInterface {

//A method with single parameter


public int incrementByFive(int a);
}
public class Example {

public static void main(String args[]) {


// lambda expression with single parameter num
MyFunctionalInterface f = (num) -> num+5;
[Link]([Link](22));
}
}

Output:

27

3/4
Example 3: Java Lambda Expression with Multiple Parameters

interface StringConcat {

public String sconcat(String a, String b);


}
public class Example {

public static void main(String args[]) {


// lambda expression with multiple arguments
StringConcat s = (str1, str2) -> str1 + str2;
[Link]("Result: "+[Link]("Hello ", "World"));
}
}

Output:

Result: Hello World

Example 4: Iterating collections using foreach loop

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.

Iterating Map 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);

/* Iterate without using Lambda


for ([Link]<String, Integer> entry : [Link]()) {
[Link]("Fruit: " + [Link]() + ", Price: " +
[Link]());
}
*/

[Link]((k,v)->[Link]("Fruit: " + k + ", Price: " +


v));

}
}

Output:

Fruit: Apple, Price: 50


Fruit: Grapes, Price: 40
Fruit: Papaya, Price: 50
Fruit: Orange, Price: 20
Fruit: Banana, Price: 10

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");

/* Iterate without using Lambda


Iterator iterator = [Link]();
while ([Link]()) {
[Link]([Link]());
}
*/
[Link](name->[Link](name));
}
}

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.

Primitive Data Type Corresponding Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Why we need wrapper class in Java


1. As I mentioned above, one of the reason why we need wrapper is to use them in collections
API. On the other hand, the wrapper objects hold much more memory compared to primitive
types. So use primitive types when you need efficiency and use wrapper class when you need
objects instead of primitive types.

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:

HashMap<Integer, String> hm = new HashMap<Integer, String>();

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.

Lets take few examples to understand how the conversion works:

Wrapper Class Example 1: Converting a primitive type to Wrapper object

public class JavaExample{


public static void main(String args[]){
//Converting int primitive into Integer object
int num=100;
Integer obj=[Link](num);

[Link](num+ " "+ obj);


}
}

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.

Wrapper Class Example 2: Converting Wrapper class object to Primitive

public class JavaExample{


public static void main(String args[]){
//Creating Wrapper class object
Integer obj = new Integer(100);

//Converting the wrapper object to primitive


int num = [Link]();

[Link](num+ " "+ obj);


}
}

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).

Lets take an example to understand it better:

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].";

String pattern = ".*book.*";

boolean isMatch = [Link](pattern, content);


[Link]("The text contains 'book'? " + isMatch);
}
}

Output:

The text contains 'book'? true

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:

1) [Link] – Used for defining patterns


2) [Link] – Used for performing match operations on text using patterns

[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.

String content = "This is a tutorial Website!";


String patternString = ".*tutorial.*";
boolean isMatch = [Link](patternString, content);
[Link]("The text contains 'tutorial'? " + isMatch);

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.

String content = "This is a tutorial Website!";


String patternString = ".*tuToRiAl.";
Pattern pattern = [Link](patternString, Pattern.CASE_INSENSITIVE);

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.

String content = "This is a tutorial Website!";


String patternString = ".*tuToRiAl.*";
Pattern pattern = [Link](patternString, Pattern.CASE_INSENSITIVE);
Matcher matcher = [Link](content);
boolean isMatched = [Link]();
[Link]("Is it a Match?" + isMatched);

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

The second split String is null in the output.

[Link] Class
We already discussed little bit about Matcher class above. Lets recall few things:

Creating a Matcher instance

String content = "Some text";


String patternString = ".*somestring.*";
Pattern pattern = [Link](patternString);
Matcher matcher = [Link](content);

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";

String string = "AA";


Pattern pattern = [Link](string);
Matcher matcher = [Link](content);

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)

Predefined Character Classes – Metacharacters

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

^ Matches the beginning of a line.


$ Matches then end of a line.
\b Matches a word boundary.
\B Matches a non-word boundary.
\A Matches the beginning of the input text.
\G Matches the end of the previous match
\Z Matches the end of the input text except the final terminator if any.
\z Matches the end of the input text.

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

Greedy Reluctant Possessive Matches


X? X?? X?+ Matches X once, or not at all (0 or 1 time).
X* X*? X*+ Matches X zero or more times.
X+ X+? X++ Matches X one or more times.
X{n} X{n}? X{n}+ Matches X exactly n times.
X{n,} X{n,}? X{n,}+ Matches X at least n times.
X{n, m) X{n, m)? X{n, m)+ Matches X at least n time, but at most m times.

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

/* returns true if the string matches exactly


* "tom" or "Tom"
*/
[Link](
[Link]("[Tt]om", "Tom")); //True
[Link](
[Link]("[Tt]om", "Tom")); //True

/* Returns true if the string matches exactly "tim"


* or "Tim" or "jin" or "Jin"
*/
[Link](
[Link]("[tT]im|[jJ]in", "Tim"));//True
[Link](
[Link]("[tT]im|[jJ]in", "jin"));//True

/* returns true if the string contains "abc" at


* any place
*/
[Link](
[Link](".*abc.*", "deabcpq"));//True

/* returns true if the string does not have a


* number at the beginning
*/
[Link](
[Link]("^[^\\d].*", "123abc")); //False
[Link](
[Link]("^[^\\d].*", "abc123")); //True

// returns true if the string contains of three letters


[Link](
[Link]("[a-zA-Z][a-zA-Z][a-zA-Z]", "aPz"));//True
[Link](
[Link]("[a-zA-Z][a-zA-Z][a-zA-Z]", "aAA"));//True
[Link](
[Link]("[a-zA-Z][a-zA-Z][a-zA-Z]", "apZx"));//False

// returns true if the string contains 0 or more non-digits


[Link](
[Link]("\\D*", "abcde")); //True
[Link](
[Link]("\\D*", "abcde123")); //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.

Example 1: Read user input text using Scanner


This is the first example of Scanner class, let’s discuss everything in detail.
1. The first statement import [Link]; is mandatory when using Scanner class.
Alternatively, You can also import Scanner like this: [Link].*, this will import all the classes
present in the [Link] package.
2. While creating an object of Scanner class, we passed the [Link] in the Scanner class
constructor. This is to read the data from standard input.
3. We have used the nextLine() method of Scanner as this method is used to read the line of
text entered by the user.

1/6
import [Link];
public class JavaExample {
public static void main(String[] args) {

// creating a scanner
Scanner scan = new Scanner([Link]);

[Link]("Enter your first name: ");

// read user input and store it in a string variable


String firstName = [Link]();

[Link]("Enter your last name: ");

// read second input


String lastName = [Link]();

// prints the user entered data


[Link]("Your Name is: "+firstName+" "+lastName);

// close scanner
[Link]();
}
}

Output:

Java Scanner class methods


In the above example, we have seen the use of nextLine() method. There are several methods
available in this class. Let’s list down some of the frequently used methods of Scanner class.

Method Description

nextInt() It reads an int value entered by the user

nextFloat() It reads a float value entered by the user

nextBoolean() It reads a boolean value entered by the user

nextLine() It reads a line of text entered by the user

2/6
next() This method reads a word entered by the user

hasNextLine() Checks if there is another line of text entered by the user

hasNextInt() Checks if there is another int value input by the user

reset() It resets the scanner

toString() It is used to get string representation of user input

nextByte() This method reads a byte value entered by the user

nextDouble() This method reads a double value entered by the user

nextShort() It reads a short value entered by the user

nextLong() It reads a long value entered by the user

Example 2: Java Scanner nextInt() method


Here, we are demonstrating the use of nextInt() method. This method reads the integer value
entered by the user. We are using the nextInt() method twice to get two numbers from user and
then we are printing the sum of entered numbers.

import [Link];
public class JavaExample {
public static void main(String[] args) {

// creating a scanner
Scanner scan = new Scanner([Link]);

[Link]("Enter first number: ");

// read user input and store it in an int variable


int num1 = [Link]();

[Link]("Enter second number: ");

// read second input


int num2 = [Link]();

// prints the sum of entered numbers


[Link]("Sum of entered numbers: "+(num1+num2));

// 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]);

[Link]("Enter your full name: ");

// read the user input using next() method


// This method only reads a word, which means
// if there is a whitespace between words, the
// first word is scanned and second skipped
String name = [Link]();

[Link]("You name: "+name);

// 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]);

[Link]("Enter your full name: ");

// The nextLine() method works different from


// the next() method, unlike next(), it reads the
// complete line
String name = [Link]();

[Link]("You name: "+name);

// close scanner
[Link]();
}
}

Output:

Example 5: Java Scanner useDelimiter() Method


The userDelimiter() method is used to specify a delimiter character in the input. In the following
example, we have specified ‘/’ as a delimiter. We are also using hasNext() method of Scanner
class to read the input separated by the delimiter.

5/6
import [Link];
public class JavaExample {
public static void main(String args[]){
// Initializing a Scanner object
Scanner scan = new Scanner("BeginnersBook/Chaitanya/Website");

//Initialize the delimiter in useDelimiter() method


[Link]("/");

//printing the strings separated by delimiter


while([Link]()){
[Link]([Link]());
}
[Link]();
}
}

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.

Complete example: Write to file using BufferedWriter


In this example we have a String mycontent and a file [Link] in C drive. We are writing the
String to the File with the help of FileWriter and BufferedWriter.

1/2
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class WriteFileDemo {


public static void main(String[] args) {
BufferedWriter bw = null;
try {
String mycontent = "This String would be written" +
" to the specified File";
//Specify the file name and path here
File file = new File("C:/[Link]");

/* This logic will make sure that the file


* gets created if it is not present at the
* specified location*/
if (![Link]()) {
[Link]();
}

FileWriter fw = new FileWriter(file);


bw = new BufferedWriter(fw);
[Link](mycontent);
[Link]("File written Successfully");

} catch (IOException ioe) {


[Link]();
}
finally
{
try{
if(bw!=null)
[Link]();
}catch(Exception ex){
[Link]("Error in closing the BufferedWriter"+ex);
}
}
}
}

Output:

File written Successfully

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{

final int MAX_VALUE=99;


void myMethod(){
MAX_VALUE=101;
}
public static void main(String args[]){
Demo obj=new Demo();
[Link]();
}
}

Output:

Exception in thread "main" [Link]: Unresolved compilation problem:


The final field Demo.MAX_VALUE cannot be assigned

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”.

Note: It is considered as a good practice to have constant names in UPPER CASE(CAPS).

Blank final variable


A final variable that is not initialized at the time of declaration is known as blank final variable.
We must initialize the blank final variable in constructor of the class otherwise it will throw a
compilation error (Error: variable MAX_VALUE might not have been initialized).

This is how a blank final variable is used in a class:

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

Whats the use of blank final variable?


Lets say we have a Student class which is having a field called Roll No. Since Roll No should not
be changed once the student is registered, we can declare it as a final variable in a class but we
cannot initialize roll no in advance for all the students(otherwise all students would be having
same roll no). In such case we can declare roll no variable as blank final and we initialize this
value during object creation like this:

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

More about blank final variable at StackOverflow and Wiki.

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");
}
}

class ABC extends XYZ{


void demo(){
[Link]("ABC Class Method");
}

public static void main(String args[]){


ABC obj= new ABC();
[Link]();
}
}

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");
}
}

class ABC extends XYZ{


public static void main(String args[]){
ABC obj= new ABC();
[Link]();
}
}

Output:

XYZ Class Method

3) final class
We cannot extend a final class. Consider the following example:

final class XYZ{


}

class ABC extends XYZ{


void demo(){
[Link]("My Method");
}
public static void main(String args[]){
ABC obj= new ABC();
[Link]();
}
}

Output:

The type ABC cannot subclass the final class XYZ

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

Basic Java Interview Questions

Q) Is Java platform independent?

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.

Q) What all memory areas are allocated by JVM?

Classloader, Class area, Heap, Stack, Program Counter Register and Native Method Stack

Q) Java vs. C ++?

Here are the few differences between Java and C++:

Platform dependency – C++ is platform dependent while java is platform independent


No goto support – Java doesn’t support goto statement while C++ does.
Multiple inheritance – C++ supports multiple inheritance while java does not.
Multithreading – C++ does not have in-build thread support, on the other hand java supports
multithreading
Virtual keyword – C++ has virtual keyword, it determines if a member function of a class can
be overridden in its child class. In java there is no concept of virtual keyword.

Q) Explain public static void main(String args[])


Here public is an access modifier, which means that this method is accessible by any class.

static – static keyword tells that this method can be accessed without creating the instance of the
class. Refer: Static keyword in java

void – this main method returns no value.

main – It is the name of the method.

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.

Q) What is the base class of all classes?

[Link] is the base class (super class) of all classes in java.

Q) What is a wrapper class in Java?


A wrapper class converts the primitive data type such as int, byte, char, boolean etc. to the objects
of their respective classes such as Integer, Byte, Character, Boolean etc. Refer: Wrapper class in
Java

Q) What is a path and classPath in Java?


Path specifies the location of .exe files. Classpath specifies the location of bytecode (.class files).

Q) Different Data types in Java.

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.

Q) What are Literals?

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.

Q) What is Type casting in Java?


When we assign a value of one data type to the different data type then these two data types may
not be compatible and needs a conversion. If the data types are compatible (for example
assigning int value to long) then java does automatic conversion and does not require casting.
However if the data types are not compatible then they need to be casted for conversion.

For example:

//here in the brackets we have mentioned long keyword, this is casting


double num = 10001.99;
long num2 = (long)num;

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.

Q) What is BREAK statement in java?

The break statement is used to break the flow sequence in Java.

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

Q) Arrays can be defined in different ways. Write them down.

int arr[];
int[] arr;

OOPs Interview Questions

Q) Four main principles of OOPS Concepts?

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.

Q) Does Java support Multiple Inheritance?

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?

Q) What is Polymorphism and what are the types of it?

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

Q) What is method overriding in Java?

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

Q) Can we override a static method?

No, we cannot override a static method in Java.

Q) What is method overloading?

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

Q) Does Java support operator overloading?

Operator overloading is not supported in Java.

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.

Q) Is it possible to overload main() method of a class?

Yes, we can overload main() method in Java.

Q) What is the difference between method overloading and method overriding?

Refer this guide: Overloading vs overriding in Java

Q) What is static and dynamic binding in Java?

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.

Q) What is an abstract class in Java?

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.

Q) What is Interface in java?


An interface is used for achieving full abstraction. A class implements an interface, thereby
inheriting the abstract methods of the interface. Refer: Java Interface

Q) What is the difference between abstract class and interface?

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.

Q) Can we inherit the constructors?

No, we cannot inherit constructors.

Q) Can we mark constructors final?

No, Constructor cannot be declared final.

Q) What is default and parameterized constructors?

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.

Parameterized: Constructor with arguments are known as parameterized constructors.

Q) Can a constructor call another constructor?

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.

Q) Can a constructor call the constructor of parent class?

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.

Note: super() must be the first statement in a constructor.

Q)THIS keyword?

The this keyword is a reference to the current object.

Q) Can this keyword be assigned null value?


No, this keyword cannot have null values assigned to it.

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.

Q) What is static variable 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.

Q) What is static block?


A static block gets executed at the time of class loading. They are used for initializing static
variables.

Q) What is a static method?


Static methods can be called directly without creating the instance (Object) of the class. A static
method can access all the static variables of a class directly but it cannot access non-static
variables without creating instance of class.

Q) Explain super keyword in Java?

super keyword references to the parent class. There are several uses of super keyword:

It can be used to call the superclass(Parent class) constructor.


It can be used to access a method of the superclass that has been hidden by subclass
(Calling parent class version, In case of method overriding).
To call the constructor of parent class.

Q) Use of final keyword in Java?


Final methods – These methods cannot be overridden by any other method.
Final variable – Constants, the value of these variable can’t be changed, its fixed.
Final class – Such classes cannot be inherited by other classes. These type of classes will be
used when application required security or someone don’t want that particular class. Final
Keyword in Java.

Q) What is a Object class?


This is a special class defined by java; all other classes are subclasses of object class. Object
class is superclass of all other classes. Object class has the following methods

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.

Q) What are Packages in Java?

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations). Refer: Package in Java.

Q)What is the difference between import [Link] and [Link].* ?


The star form ([Link].* ) includes all the classes of that package and that may increase the
compilation time – especially if you import several packages. However it doesn’t have any effect
run-time performance.

Q) What is static import?


Refer: Static Import in Java.

Q) Garbage collection in java?


Since objects are dynamically allocated by using the new operator, java handles the de-allocation
of the memory automatically, when no references to an object exist for a long time. This whole
process is called garbage collection. The whole purpose of Garbage collection is efficient memory
management.

Q) Use of finalize() method in java?


finalize() method is used to free the allocated resource.

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.

Q) What are two different ways to call garbage collector?


[Link]() OR [Link]().gc().

Q) Can the Garbage Collection be forced by any means?

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.

Q) Exceptions are defined in which java package? OR which package has


definitions for all the exception classes?
[Link]
This package contains definitions for Exceptions.

Q) What are the types of exceptions?


There are two types of exceptions: checked and unchecked exceptions.
Checked exceptions: These exceptions must be handled by programmer otherwise the program
would throw a compilation error.
Unchecked exceptions: It is up to the programmer to write the code in such a way to avoid
unchecked exceptions. You would not get a compilation error if you do not handle these
exceptions. These exceptions occur at runtime.

Q) What is the difference between Error and Exception?


Error: Mostly a system issue. It always occur at run time and must be resolved in order to proceed
further.
Exception: Mostly an input data issue or wrong logic in code. Can occur at compile time or run
time.

Q) What is throw keyword in exception handling?


The throw keyword is used for throwing user defined or pre-defined exception.

Q) What is throws keyword?

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.

Q) Difference between throw and throws in Java


Read the difference here: Java – throw vs throws.

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) What is finally block?


Finally block is a block of code that always executes, whether an exception occurs or not. Finally
block follows try block or try-catch block.

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.

Q) Can we have a try block without catch or finally block?


No, we cannot have a try block without catch or finally block. We must have either one of them or
both.

Q) Can we have multiple catch blocks following a single try block?

Yes we can have multiple catch blocks in order to handle more than one exception.

Q) Is it possible to have finally block without catch block?


Yes, we can have try block followed by finally block without even using catch blocks in between.

When a finally block does not get executed?

The only time finally won’t be called is if you call [Link]() or if the JVM crashes first.

Q) Can we handle more than one exception in a single catch block?

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.

Q) What is a Java Bean?


A JavaBean is a Java class that follows some simple conventions including conventions on the
names of certain methods to get and set state called Introspection. Because it follows
conventions, it can easily be processed by a software tool that connects Beans together at
runtime. JavaBeans are reusable software components.

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 is the main purpose of having multithread environment?

Maximizing CPU usage and reducing CPU idle time

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.

Q) How can we create a thread in java?


There are following two ways of creating a thread:
1) By Implementing Runnable interface.
2) By Extending Thread class.

Q) Explain yield and sleep?


yield() – It causes the currently executing thread object to temporarily pause and allow other
threads to execute.

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.

Q) What is the difference between sleep() and wait()?

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.

Q) What does join( ) method do?


if you use join() ,it makes sure that as soon as a thread calls join,the current thread(yes,currently
running thread) will not execute unless the thread you have called join is finished.

Q) Preemptive scheduling vs. time slicing?

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.

Q) Can we call run() method of a Thread class?

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 interview Questions

Q: What is Serialization and de-serialization?

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.

Q) What is a transient variable?


1) transient variables are not included in the process of serialization.
2) They are not the part of the object’s serialized state.
3) Variables which we don’t want to include in serialization are declared as transient.

String interview questions

Q) A string class is immutable or mutable?

String class is immutable that’s the reason once its object gets created, it cannot be changed
further.

Q) Difference between StringBuffer and StringBuilder class?

1) StringBuffer is thread-safe but StringBuilder is not thread safe.


2) StringBuilder is faster than StringBuffer.
3) StringBuffer is synchronized whereas StringBuilder is not synchronized.

Q) What is toString() method in Java?

The toString() method returns the string representation of any object.

Java collections interview questions

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?

A Set is a Collection that cannot contain duplicate elements.

13/16
Q) Why ArrayList is better than Arrays?

Array can hold fixed number of elements. ArrayList can grow dynamically.

Q) What is the difference between ArrayList and LinkedList?

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.

Q) For addition and deletion. Which one is most preferred: ArrayList or


LinkedList?

LinkedList. Because deleting or adding a node in LinkedList is faster than ArrayList.

Q) For searches. Which one is most preferred: ArrayList or LinkedList?


ArrayList. Searching an element is faster in ArrayList compared to LinkedList.

Q) What is the difference between ArrayList and Vector?

1) Vector is synchronized while ArrayList is not synchronized.


2) By default, Vector doubles the size of its array when it is re-sized internally. ArrayList increases
by half of its size when it is re-sized. More details.

Q) What is the difference between Iterator and ListIterator?

Following are the major differences between them:


1) Iterator can be used for traversing Set, List and Map. ListIterator can only be used for traversing
a List.
2) We can traverse only in forward direction using Iterator. ListIterator can be used for traversing
in both the directions(forward and backward). Read more at: ListIterator vs Iterator.

Q) Difference between TreeSet and SortedSet?

TreeSet implements SortedSet interface.

Q) What is the difference between HashMap and Hashtable?

1) Hashtable is synchronized. HashMap is not synchronized.


2) Hashtable does not allow null keys or values. HashMap allows one null key and any number of
null values. 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]().

Applet Interview Questions

Q) How do you do file I/O from an applet?


Unsigned applets are simply not allowed to read or write files on the local file system .

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

Q) On Windows, generally frames are invisible, how to make it visible?

Frame f = new Frame();


[Link](300,200); //height and width
[Link](true) ; // Frames appears

Q) Listeners and corresponding Methods?

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().

Q) Use of showStatus() method in Java

To display the message at the bottom of the browser when applet is started.

Q) What is Event handling in Java?


Is irrespective of any component, if any action performed/done on Frame, Panel or on window,
handling those actions are called Event Handling.

Q) What is Adapter class?


Adapter class is an abstract class.
Advantage of adapter: To perform any window listener, we need to include all the methods used
by the window listener whether we use those methods are not in our class like Interfaces whereas
with adapter class, its sufficient to include only the methods required to override. Straight opposite
to Interface.

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.

ArrayList vs HashMap in Java


1) Implementation: ArrayList implements List Interface while HashMap is an implementation of
Map interface. List and Map are two entirely different collection interfaces.

2) Memory consumption: ArrayList stores the element’s value alone and internally maintains the
indexes for each element.

ArrayList<String> arraylist = new ArrayList<String>();


//String value is stored in array list
[Link]("Test String");

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.

HashMap<Integer, String> hmap= new HashMap<Integer, String>();


//String value stored along with the key value in hash map
[Link](123, "Test String");

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.

Memory consumption is low in ArrayList as Memory consumption is high in LinkedList as it


it stores only the elements data in maintains element data and two pointers for
contiguous locations. neighbour nodes, hence the memory consumption
is high in LinkedList.

Performance difference between ArrayList and LinkedList for various


operations
1) Search: ArrayList search operation is pretty fast compared to the LinkedList search
operation. get(int index) in ArrayList gives the performance of O(1) while LinkedList
performance is O(n).

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).

Conclusion: LinkedList element deletion is faster compared to ArrayList.

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:

1. Both ArrayList and LinkedList are implementation of List interface.


2. They both maintain the elements insertion order which means while displaying ArrayList and
LinkedList elements the result set would be having the same order in which the elements got
inserted into the List.
3. Both of these classes are non-synchronized and can be made synchronized explicitly by
using [Link] method.
4. The iterator and listIterator returned by these classes are fail-fast (if list is structurally
modified at any time after the iterator is created, in any way except through the iterator’s
own remove or add methods, the iterator will throw a ConcurrentModificationException).

When to use LinkedList and when to use ArrayList?


1) As explained above the insert and remove operations give good performance (O(1)) in
LinkedList compared to ArrayList(O(n)). Hence if there are frequent addition and deletion in
application then LinkedList is a best choice.

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 Vs Vector: Differences between them

ArrayList Vector

ArrayList is non-synchronized, which means Vector is synchronized. This means if


multiple threads can work on ArrayList at the same one thread is working on Vector, no
time. For example: if one thread is performing an other thread can get a hold of it. Unlike
add operation on ArrayList, there can be an another ArrayList, only one thread can perform
thread performing remove operation on ArrayList at an operation on vector at a time.
the same time in a multithreaded environment.

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 is not a legacy class. Vector is a legacy class.

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:

1. Both Vector and ArrayList use growable array data structure.


2. The iterator and listIterator returned by these classes (Vector and ArrayList) are fail-fast.
3. They both are ordered collection classes as they maintain the elements insertion order.
4. Vector & ArrayList both allows duplicate and null values.
5. They both grows and shrinks automatically when overflow and deletion happens.

When to use ArrayList and when to use vector?


It totally depends on the requirement. If there is a need to perform “thread-safe” operation the
vector is your best bet as it ensures that only one thread access the collection at a time.

Update: Even if you need to perform synchronized operations, you can still use ArrayList by
converting it to a Synchronized ArrayList.

Performance: Synchronized operations consumes more time compared to non-synchronized


ones so if there is no need for thread safe operation, ArrayList is a better choice as performance
will be improved because of the concurrent processes.

How to make ArrayList synchronized?


As I stated above ArrayList methods are non-synchronized but still if there is a need you can make
them synchronized like this:

2/4
//Use [Link] method
List list = [Link](new ArrayList());
...

//If you wanna use iterator on the synchronized list, use it


//like this. It should be in synchronized block.
synchronized (list) {
Iterator iterator = [Link]();
while ([Link]())
...
[Link]();
...
}

Example of ArrayList in Java


In this example, we have an ArrayList that contains fruit names. We are iterating the arraylist using
iterator.

import [Link].*;
class JavaExample{
public static void main(String args[]){

List<String> fruits=new ArrayList<String>();


[Link]("Apple");
[Link]("Mango");
[Link]("Orange");
[Link]("Banana");
//Iterating the array list using iterator
[Link]("ArrayList elements: ");
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}

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");

[Link]("Vector elements: ");


//Iterating vector using Enumeration
Enumeration e=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}

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.

Hashtable doesn’t allow null keys and 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.

Enumerator for the Hashtable is not fail-fast.

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:

Hashtable ht= new Hashtable();


....
.....
Enumeration keys = [Link]();
for (Enumeration en = [Link]() ; [Link]() ; [Link]()) {
//No exception would be thrown here
[Link](key & value pair here);
}

When to use HashMap and Hashtable?


1) As stated above the main difference between HashMap & Hashtable is synchronization. If there
is a need of thread-safe operation then Hashtable can be used as all its methods are
synchronized but it’s a legacy class and should be avoided as there is nothing about it, which
cannot be done by HashMap. For multi-thread environment I would recommend you to use
ConcurrentHashMap (Almost similar to Hashtable) or even you can make the HashMap
synchronized explicitly (Read here..).

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.

2) We can traverse in only forward direction using Iterator.

Using ListIterator, we can traverse a List in both the directions (forward and Backward).

3) We cannot obtain indexes while using Iterator

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.

4) We cannot add element to collection while traversing it using Iterator, it throws


ConcurrentModificationException when you try to do it.

We can add element at any point of time while traversing a list using ListIterator.

5) We cannot replace the existing element value when using Iterator.

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.

List Vs Set Vs Map


1) Duplicity: List allows duplicate elements. Any number of duplicate elements can be inserted
into the list without affecting the same existing values and their indexes.
Set doesn’t allow duplicates. Set and all of the classes which implements Set interface should
have unique elements.
Map stored the elements as key & value pair. Map doesn’t allow duplicate keys while it allows
duplicate values.

2) Null values: List allows any number of null values.


Set allows single null value at most.
Map can have single null key at most and any number of null values.

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.

4) Commonly used classes:


List: ArrayList, LinkedList etc.
Set: HashSet, LinkedHashSet, TreeSet, SortedSet etc.
Map: HashMap, TreeMap, WeakHashMap, LinkedHashMap, IdentityHashMap etc.

When to use List, Set and Map in Java?


1) If you do not want to have duplicate values in the database then Set should be your first choice
as all of its classes do not allow duplicates.
2) If there is a need of frequent search operations based on the index values then List (ArrayList)
is a better choice.
3) If there is a need of maintaining the insertion order then also the List is a preferred collection
interface.
4) If the requirement is to have the key & value mappings in the database then Map is your best
bet.

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.

Throw vs Throws in java


1. Throws clause is used to declare an exception, which means it works similar to the try-catch
block. On the other hand throw keyword is used to throw an exception explicitly.

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:

throw new ArithmeticException("Arithmetic Exception");

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:

//Declaring multiple exceptions using throws


void myMethod() throws ArithmeticException, NullPointerException{
//Statements where exception might occur
}

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.

public class Example1{


void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
[Link]("Eligible for voting");
}
public static void main(String args[]){
Example1 obj = new Example1();
[Link](13);
[Link]("End Of Program");
}
}

Output:

Exception in thread "main" [Link]:


Not Eligible for voting
at [Link]([Link])
at [Link]([Link])

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.

public class Example1{


int division(int a, int b) throws ArithmeticException{
int t = a/b;
return t;
}
public static void main(String args[]){
Example1 obj = new Example1();
try{
[Link]([Link](15,0));
}
catch(ArithmeticException e){
[Link]("You shouldn't divide number by zero");
}
}
}

Output:

You shouldn't divide number by zero

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.

Why Java doesn’t support multiple inheritance?


C++ , Common lisp and few other languages supports multiple inheritance while java doesn’t
support it. Java doesn’t allow multiple inheritance to avoid the ambiguity caused by it. One of the
example of such problem is the diamond problem that occurs in multiple inheritance.

To understand the basics of inheritance, refer this main guide: Inheritance in Java

What is diamond problem?


We will discuss this problem with the help of the diagram below: which shows multiple inheritance
as Class D extends both classes B & C. Now lets assume we have a method in class A and
class B & C overrides that method in their own way. Wait!! here the problem comes – Because
D is extending both B & C so if D wants to use the same method which method would be called
(the overridden method of B or the overridden method of C). Ambiguity. That’s the main reason
why Java doesn’t support multiple inheritance.

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:

Implementing more than one interfaces

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.

Method 1: Conversion using [Link]()


Syntax:

ArrayList<T> arraylist= new ArrayList<T>([Link](arrayname));

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) {

// Array declaration and initialization


String cityNames[]={"Agra", "Mysore", "Chandigarh", "Bhopal"};

// Array to ArrayList conversion


ArrayList<String> cityList= new ArrayList<String>([Link](cityNames));

// Adding new elements to the list after conversion


[Link]("Chennai");
[Link]("Delhi");

//print ArrayList elements using advanced for loop


for (String str: cityList)
{
[Link](str);
}
}
}

Output:

1/4
Agra
Mysore
Chandigarh
Bhopal
Chennai
Delhi

Method 2: Conversion using [Link]() method


[Link]() method adds all the array elements to the specified collection. We can
call the [Link] method as shown below. It works just like [Link]() method
however, it is much faster. Conversion using [Link]() method gives better performance
compared to asList() method.

String array[]={new Item(1), new Item(2), new Item(3), new Item(4)};


ArrayList<T> arraylist = new ArrayList<T>();
[Link](arraylist, array);

OR

[Link](arraylist, new Item(1), new Item(2), new Item(3), new Item(4));

Example:

import [Link].*;
public class JavaExample {
public static void main(String[] args) {

// Array declaration and initialization*/


String array[]={"Hi", "Hello", "Howdy", "Bye"};

//ArrayList declaration
ArrayList<String> arraylist= new ArrayList<String>();

// conversion using addAll()


[Link](arraylist, array);

//Adding new elements to the converted List


[Link]("String1");
[Link]("String2");

//print ArrayList
for (String str: arraylist)
{
[Link](str);
}
}
}

Output:

2/4
Hi
Hello
Howdy
Bye
String1
String2

Method 3: Convert Array to ArrayList manually


This program demonstrates how to convert an Array to ArrayList without using any
predefined method such as asList() and addAll().
The logic of this program is pretty simple, we are iterating the array using for loop and adding the
element to the ArrayList on every iteration of the loop. This means, in the first iteration, the first
element of the array is added to the ArrayList, in the second iteration second element gets added
and so on.

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"};

/* [Link] returns the number of


* elements present in array*/
for(int i =0;i<[Link];i++)
{

//Adding array elements to the ArrayList


[Link](array[i]);
}

//print ArrayList content


for(String str: arrayList)
{
[Link](str);
}
}
}

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.

Current date and time in Java – Two ways to get it

1) Using Date class

Specify the desired pattern while creating the instance of SimpleDateFormat.


Create an object of Date class.
Call the format() method of DateFormat class and pass the date object as a parameter to the
method.

/* This will display the date and time in the format of


* 12/09/2017 24:12:35. See the complete program below
*/
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date dateobj = new Date();
[Link]([Link](dateobj));

2) Using Calendar 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.

DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");


Calendar calobj = [Link]();
[Link]([Link]([Link]()));

1/4
Complete java code for getting current date and time

import [Link];
import [Link];
import [Link];
import [Link];

public class GettingCurrentDate {


public static void main(String[] args) {
//getting current date and time using Date class
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date dateobj = new Date();
[Link]([Link](dateobj));

/*getting current date time using calendar class


* An Alternative of above*/
Calendar calobj = [Link]();
[Link]([Link]([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

Java – Getting current date and time in other timezone


The example we have seen above shows the date and time in local timezone. However we can
get the date and time in different time zone as well such as UTC/GMT etc. In the following
example we are displaying the time in GMT time zone.

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.

Letter Date or Time Component Presentation Examples

G Era designator Text

y Year Year 1996; 96

Y Week year Year 2009; 09

M Month in year Month July; Jul; 07

w Week in year Number 27

W Week in month Number 2

D Day in year Number 189

d Day in month Number 10

F Day of week in month Number 2

E Day name in week Text Tuesday; Tue

u Day number of week (1 = Number 1


Monday, …, 7 = Sunday)

a Am/pm marker Text PM

H Hour in day (0-23) Number 0

k Hour in day (1-24) Number 24

3/4
K Hour in am/pm (0-11) Number 0

h Hour in am/pm (1-12) Number 12

m Minute in hour Number 30

s Second in minute Number 55

S Millisecond Number 978

z Time zone General time Pacific Standard


zone Time; PST; GMT-08:00

Z Time zone RFC 822 time -0800


zone

X Time zone ISO 8601 time -08; -0800; -08:00


zone

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].*;

public class LinkedListExample {

public static void main(String args[]) {


/*LinkedList declaration*/
LinkedList<String> linkedlist=new LinkedList<String>();
[Link]("Apple");
[Link]("Orange");
[Link]("Mango");

/*for loop*/
[Link]("**For loop**");
for(int num=0; num<[Link](); num++)
{
[Link]([Link](num));
}

/*Advanced for loop*/


[Link]("**Advanced For loop**");
for(String str: linkedlist)
{
[Link](str);
}

/*Using Iterator*/
[Link]("**Iterator**");
Iterator i = [Link]();
while ([Link]()) {
[Link]([Link]());
}

/* Using While Loop*/


[Link]("**While Loop**");
int num = 0;
while ([Link]() > num) {
[Link]([Link](num));
num++;
}

}
}

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");

// 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:

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.

Lets take the same example using LinkedHashMap and TreeMap:

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");

// 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:

10: Chaitanya
1: Ajeet
11: Test
9: Demo
3: Anuj

Voila!! We got the result in the insertion order.

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.

Important point to note in the below example:


Iterator should be used in a synchronized block even if we have synchronized the HashMap
explicitly (As we did in the below code).

Syntax:

Map map = [Link](new HashMap());


...
//This doesn't need to be in synchronized block
Set set = [Link]();
// Synchronizing on map, not on set
synchronized (map) {
// Iterator must be in synchronized block
Iterator iterator = [Link]();
while ([Link]()){
...
}
}

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");

Map map= [Link](hmap);


Set set = [Link]();
synchronized(map){
Iterator i = [Link]();
// Display elements
while([Link]()) {
[Link] me = ([Link])[Link]();
[Link]([Link]() + ": ");
[Link]([Link]());
}
}
}
}

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>();

//add elements to HashSet


[Link]("Abhijeet");
[Link]("Ram");
[Link]("Kevin");
[Link]("Singh");
[Link]("Rick");
// Duplicate removed
[Link]("Ram");

// Displaying HashSet elements


[Link]("HashSet contains: ");
for(String temp : hset){
[Link](temp);
}
}
}

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>();

//add elements to TreeSet


[Link]("Abhijeet");
[Link]("Ram");
[Link]("Kevin");
[Link]("Singh");
[Link]("Rick");
// Duplicate removed
[Link]("Ram");

// Displaying TreeSet elements


[Link]("TreeSet contains: ");
for(String temp : tset){
[Link](temp);
}
}
}

Output: Elements are sorted in ascending order.

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.

Java 8 – Filter Map by Keys

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");

Map<Integer, String> result = [Link]()


.stream()
.filter(map -> [Link]().intValue() <= 22)
.collect([Link](map -> [Link](), map -> [Link]()));

[Link]("Result: " + result);


}
}

Output:

Result: {22=Orange, 11=Apple}

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");

Map<Integer, String> result = [Link]()


.stream()
.filter(map -> "Orange".equals([Link]()))
.collect([Link](map -> [Link](), map -> [Link]()));

[Link]("Result: " + result);


}
}

Output:

Result: {22=Orange}

Java 8 – Filter Map by both Keys and Values


In this example we are filtering a Map by keys and values both. When we filter a Map like this we
are joining both the conditions by AND (&&) logical operator. You can also place both the
conditions in the single filter() method and join them using any logical operator such as OR (||),
AND(&&) or NOT(!).

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");

Map<Integer, String> result = [Link]()


.stream()
.filter(p -> [Link]().intValue() <= 2) //filter by key
.filter(map -> [Link]().startsWith("A")) //filter by value
.collect([Link](map -> [Link](), map -> [Link]()));

[Link]("Result: " + result);


}
}

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].

Example: Program to get current date and time in Java 8


class DateExample {
public static void main(String[] args) {
/* Obtains the current date from the system clock in the
* default time-zone.
*/
[Link]("Current Date: "+[Link]());

/* Obtains the current time from the system clock in the


* default time-zone.
*/
[Link]("Current Time: "+[Link]());

//current date and time


[Link]("Current Date & Time: "+[Link]());
}
}

Output:

Current Date: 2017-09-27


Current Time: 13:12:04.103
Current Date & Time: 2017-09-27T13:12:04.103

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.

Why default method?


For example, if several classes such as A, B, C and D implements an interface XYZInterface then
if we add a new method to the XYZInterface, we have to change the code in all the classes(A, B,
C and D) that implements this interface. In this example we have only four classes that
implements the interface which we want to change but imagine if there are hundreds of classes
implementing an interface then it would be almost impossible to change the code in all those
classes. This is why in java 8, we have a new concept “default methods”. These methods can be
added to any existing interface and we do not need to implement these methods in the
implementation classes mandatorily, thus we can add these default methods to existing interfaces
without breaking the code.

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.

Java 8 Example: Default method in Interface


The method newMethod() in MyInterface is a default method, which means we need not to
implement this method in the implementation class Example. This way we can add the default
methods to existing interfaces without bothering about 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();

//calling the default method of interface


[Link]();
//calling the abstract method of interface
[Link]("Java 8 is easy to learn");

}
}

Output:

Newly added default method


String is: Java 8 is easy to learn

Java 8 Example: Static method in Interface


As mentioned above, the static methods in interface are similar to default method so we need not
to implement them in the implementation classes. We can safely add them to the existing
interfaces without changing the code in the implementation classes. Since these methods are
static, we cannot override them in the implementation classes.

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");
}

/* This is a static method. Static method in interface is


* similar to default method except that we cannot override
* them in the implementation classes.
* Similar to default methods, we need to implement these methods
* in implementation classes so we can safely add them to the
* existing interfaces.
*/
static void anotherNewMethod(){
[Link]("Newly added static 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();

//calling the default method of interface


[Link]();
//calling the static method of interface
[Link]();
//calling the abstract method of interface
[Link]("Java 8 is easy to learn");

}
}

Output:

Newly added default method


Newly added static method
String is: Java 8 is easy to learn

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.

Default Method and Multiple Inheritance


The multiple inheritance problem can occur, when we have two interfaces with the default
methods of same signature. Lets take an example.

4/6
interface MyInterface{

default void newMethod(){


[Link]("Newly added default method");
}
void existingMethod(String str);
}
interface MyInterface2{

default void newMethod(){


[Link]("Newly added default method");
}
void disp(String str);
}
public class Example implements MyInterface, MyInterface2{
// implementing abstract methods
public void existingMethod(String str){
[Link]("String is: "+str);
}
public void disp(String str){
[Link]("String is: "+str);
}

public static void main(String[] args) {


Example obj = new Example();

//calling the default method of interface


[Link]();

}
}

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.

How to solve this issue?


To solve this problem, we can implement this method in the implementation class like this:

5/6
interface MyInterface{

default void newMethod(){


[Link]("Newly added default method");
}
void existingMethod(String str);
}
interface MyInterface2{

default void newMethod(){


[Link]("Newly added default method");
}
void disp(String str);
}
public class Example implements MyInterface, MyInterface2{
// implementing abstract methods
public void existingMethod(String str){
[Link]("String is: "+str);
}
public void disp(String str){
[Link]("String is: "+str);
}
//Implementation of duplicate default method
public void newMethod(){
[Link]("Implementation of default method");
}
public static void main(String[] args) {
Example obj = new Example();

//calling the default method of interface


[Link]();

}
}

Output:

Implementation of default method

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.

What’s the use of Annotations?


1) Instructions to the compiler: There are three built-in annotations available in Java
(@Deprecated, @Override & @SuppressWarnings) that can be used for giving certain instructions
to the compiler. For example the @override annotation is used for instructing compiler that the
annotated method is overriding the method. More about these built-in annotations with example is
discussed in the next sections of this article.

2) Compile-time instructors: Annotations can provide compile-time instructions to the compiler


that can be further used by sofware build tools for generating code, XML files etc.

3) Runtime instructions: We can define annotations to be available at runtime which we can


access using java reflection and can be used to give instructions to the program at runtime. We
will discuss this with the help of an example, later in this same post.

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.

For e.g. @Override


Here @ symbol represents that this is an annotation and the Override is the name of this
annotation.

Where we can use annotations?


Annotations can be applied to the classes, interfaces, methods and fields. For example the below
annotation is being applied to the method.

@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.

Built-in Annotations in Java


Java has three built-in annotations:

@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:

public class MyParentClass {

public void justaMethod() {


[Link]("Parent class method");
}
}

public class MyChildClass extends MyParentClass {

@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]();
}

Creating Custom Annotations


Annotations are created by using @interface, followed by annotation name as shown in the
below example.
An annotation can have elements as well. They look like methods. For example in the below
code, we have four elements. We should not provide implementation for these elements.
All annotations extends [Link] interface. Annotations cannot
include any extends clause.

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 {

public class MyClass {


@MyCustomAnnotation
public void myMethod()
{
//Doing something
}
}

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 {
...
}

public class MyChildClass extends 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

Components and containers


All the elements like buttons, text fields, scrollbars etc are known as components. In AWT we have
classes for each component as shown in the above diagram. To have everything placed on a
screen to a particular position, we have to add them to a container. A container is like a screen
wherein we are placing components like buttons, text fields, checkbox etc. In short a container
contains and controls the layout of components. A container itself is a component (shown in the
above hierarchy diagram) thus we can add a container inside container.

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.

Window: An instance of the Window class has no border and no title


Dialog: Dialog class has border and title. An instance of the Dialog class cannot exist without an
associated instance of the Frame class.
Panel: Panel does not contain title bar, menu bar or border. It is a generic container for holding
components. An instance of the Panel class provides a container to which to add components.
Frame: A frame has title, border and menu bars. It can contain several components like buttons,
text fields, scrollbars etc. This is most widely used container while developing an application in
AWT.

Java AWT Example


We can create a GUI using Frame in two ways:
1) By extending Frame class
2) By creating the instance of Frame class
Lets have a look at the example of each one.

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!!");

// setting button position on screen


[Link](50,50,50,50);

//adding button into frame


add(b);

//Setting Frame width and height


setSize(500,300);

//Setting the title of Frame


setTitle("This is my First AWT example");

//Setting the layout for the Frame


setLayout(new FlowLayout());

/* By default frame is not visible so


* we are setting the visibility to true
* to make it visible.
*/
setVisible(true);
}
public static void main(String args[]){
// Creating the instance of Frame
SimpleExample fr=new SimpleExample();
}
}

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: ");

//adding label to the frame


[Link](lb);

//Creating Text Field


TextField t = new TextField();

//adding text field to the frame


[Link](t);

//setting frame size


[Link](500, 300);

//Setting the layout for the Frame


[Link](new FlowLayout());

[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.

This is how we define Enum

public enum Directions{


EAST,
WEST,
NORTH,
SOUTH
}

Here we have a variable Directions of enum type, which is a collection of four constants EAST,
WEST, NORTH and SOUTH.

How to assign value to a enum type?

Directions dir = [Link];

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.

Use of Enum types in if-else statements

This is how we can use an enum variable in a if-else logic.

/* You can assign any value here out of


* EAST, WEST, NORTH, SOUTH. Just for the
* sake of example, I'm assigning to NORTH
*/
Directions dir = [Link];

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.

public enum Directions{


EAST,
WEST,
NORTH,
SOUTH
}
public class EnumDemo
{
public static void main(String args[]){
Directions dir = [Link];
if(dir == [Link]) {
[Link]("Direction: East");
} else if(dir == [Link]) {
[Link]("Direction: West");
} else if(dir == [Link]) {
[Link]("Direction: North");
} else {
[Link]("Direction: South");
}
}
}

Output:

Direction: North

Use of Enum in Switch-Case Statements

Here is the example to demonstrate the use of enums in switch-case statements.

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;
}
}

public static void main(String[] args) {


EnumDemo obj1 = new EnumDemo([Link]);
[Link]();
EnumDemo obj2 = new EnumDemo([Link]);
[Link]();
}
}

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);
}
}
}

This code would display all the four constants.

Enum Fields and Methods


Lets take an example first then we will discuss it in detail:

public enum Directions{


EAST ("E"),
WEST ("W"),
NORTH ("N"),
SOUTH ("S")
;
/* Important Note: Must have semicolon at
* the end when there is a enum field or method
*/
private final String shortCode;

Directions(String code) {
[Link] = code;
}

public String getDirectionCode() {


return [Link];
}
}
public class EnumDemo
{
public static void main(String[] args) {
Directions dir = [Link];
[Link]([Link]());
Directions dir2 = [Link];
[Link]([Link]());
}
}

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”].

Important points to Note:

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.

What are the rules of defining a functional interface?


The functional interface should have Only one abstract method. Along with the one abstract
method, they can have any number of default and static methods.

Example 1: Creating your own functional interface

@FunctionalInterface
interface MyFunctionalInterface {

public int addMethod(int a, int b);


}
public class BeginnersBookClass {

public static void main(String args[]) {


// lambda expression
MyFunctionalInterface sum = (a, b) -> a + b;
[Link]("Result: "+[Link](12, 100));
}
}

Output:

Result: 112

1/4
Example 2: Using predefined functional interface

import [Link];

public class BeginnersBookClass {

public static void main(String args[]) {


// lambda expression
IntBinaryOperator sum = (a, b) -> a + b;
[Link]("Result: " + [Link](12, 100));

}
}

Output:

Result: 112

Functional interface example: using anonymous inner class vs using


lambda expression
We have been using functional interfaces even prior to java8, they were used by creating
anonymous inner classes using these interfaces. You must have seen functional interfaces such
as Runnable, ActionListener, Comparator etc. They all have single abstract method. Lets see an
example of ActionListener to see how it was used with Anonymous inner class and how it can be
implemented using lambda expression.
ActionListener Example: Before Java 8: Using anonymous inner class

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);

button = new JButton("Button");


[Link](100,100,90,40);
[Link](new ActionListener(){
public void actionPerformed(ActionEvent e){
[Link]("You clicked the button.");
}

});
add(button);
}
public static void main(String args[])
{
new Example();
}
}

ActionListener Example: Lambda Expression

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);

button = new JButton("Button");


[Link](100,100,90,40);
//Lambda expression
[Link](e->
[Link]("You clicked the button."));

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.

Iterator without Generics Example


Generics got introduced in Java 5. Before that there were no concept of Generics. Refer this guide
to learn more about generics: Java Generics Tutorial.

import [Link];
import [Link];

public class IteratorDemo1 {

public static void main(String args[]){


ArrayList names = new ArrayList();
[Link]("Chaitanya");
[Link]("Steve");
[Link]("Jack");

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).

Iterator with Generics Example


In the above section we discussed about ClassCastException. Lets see what is it and why it
occurs when we don’t use Generics.

import [Link];
import [Link];

public class IteratorDemo2 {

public static void main(String args[]){


ArrayList names = new ArrayList();
[Link]("Chaitanya");
[Link]("Steve");
[Link]("Jack");

//Adding Integer value to String ArrayList


[Link](new Integer(10));

Iterator it = [Link]();

while([Link]()) {
String obj = (String)[Link]();
[Link](obj);
}
}
}

Output:

ChaitanyaException in thread "main"


Steve
Jack
[Link]: [Link] cannot be cast to [Link]
at [Link]([Link])

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];

public class IteratorDemo3 {


public static void main(String args[]){
ArrayList<String> names = new ArrayList<String>();
[Link]("Chaitanya");
[Link]("Steve");
[Link]("Jack");

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.

Java Iterator Methods


1. hasNext():

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():

default void remove()

3/6
It removes the last element returned by the Iterator, however this can only be called once per
next() call.

4. forEachRemaining():

default void forEachRemaining(Consumer<? super E> action)

Performs the specified action on all the remaining elements.

Iterating HashMap using Iterator

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.

ConcurrentModificationException while using Iterator

import [Link];
public class ExceptionDemo {
public static void main(String args[]){
ArrayList<String> books = new ArrayList<String>();
[Link]("C");
[Link]("Java");
[Link]("Cobol");

for(String obj : books) {


[Link](obj);
//We are adding element while iterating list
[Link]("C++");
}
}
}

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.

Explanation From Javadoc:


This exception may be thrown by methods that have detected concurrent modification of an object
when such modification is not permissible.
For example, it is not generally permissible for one thread to modify a Collection while another
thread is iterating over it. In general, the results of the iteration are undefined under these
circumstances. Some Iterator implementations (including those of all the general purpose
collection implementations provided by the JRE) may choose to throw this exception if this
behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and
cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the
future.

6/6
Java Serialization
Here we are gonna discuss how to serialize and de-serialize an object and what is the use of it.

What is Java Serialization?


Serialization is a mechanism to convert an object into stream of bytes so that it can be written into
a file, transported through a network or stored into database. De-serialization is just a vice versa.
In simple words serialization is converting an object to stream of bytes and de-serialization is
rebuilding the object from stream of bytes. Java Serialiation API provides the features to perform
seralization & de-serialization. A class must implement [Link] interface to be eligible
for serialization.

Lets take an example to understand the concepts better:

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;

public Student(int roll, int age, String name,


String address, int height) {
[Link] = roll;
[Link] = age;
[Link] = name;
[Link] = address;
[Link] = height;
}

public int getStuRollNum() {


return stuRollNum;
}
public void setStuRollNum(int stuRollNum) {
[Link] = stuRollNum;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
[Link] = stuAge;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
[Link] = stuName;
}
public String getStuAddress() {
return stuAddress;
}
public void setStuAddress(String stuAddress) {
[Link] = stuAddress;
}
public int getStuHeight() {
return stuHeight;
}
public void setStuHeight(int stuHeight) {
[Link] = 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 {

public static void main(String args[])


{
Student o=null;
try{
FileInputStream fis = new FileInputStream("[Link]");
ObjectInputStream ois = new ObjectInputStream(fis);
o = (Student)[Link]();
[Link]();
[Link]();
}
catch(IOException ioe)
{
[Link]();
return;
}catch(ClassNotFoundException cnfe)
{
[Link]("Student Class is not found.");
[Link]();
return;
}
[Link]("Student Name:"+[Link]());
[Link]("Student Age:"+[Link]());
[Link]("Student Roll No:"+[Link]());
[Link]("Student Address:"+[Link]());
[Link]("Student Height:"+[Link]());
}
}

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:

public class StaticTest


{
/* See below - I have marked the constructor as static */
public static StaticTest()
{
[Link]("Static Constructor of the class");
}
public static void main(String args[])
{
/*Below: I'm trying to create an object of the class
*that should invoke the constructor
*/
StaticTest obj = new StaticTest();
}
}

1/5
Output: You would get the following error message when you try to run the above java code.
“modifier static not allowed here”

Why java doesn’t support static constructor?


It’s actually pretty simple to understand – Everything that is marked static belongs to the class
only, for example static method cannot be inherited in the sub class because they belong to
the class in which they have been declared. Refer static keyword.
Lets back to the point, since each constructor is being called by its subclass during creation of the
object of its subclass, so if you mark constructor as static the subclass will not be able to access
the constructor of its parent class because it is marked static and thus belong to the class only.
This will violate the whole purpose of inheritance concept and that is reason why a constructor
cannot be static.

Let’s understand this with the help of an example –

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.

Lets understand this with the help of examples:

Example 1: Without Static Imports

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

Example 2: Using Static Imports

import static [Link];


import static [Link].*;
class Demo2{
public static void main(String args[])
{
//instead of [Link] need to use only sqrt
double var1= sqrt(5.0);
//instead of [Link] need to use only tan
double var2= tan(30);
//need not to use System in both the below statements
[Link]("Square of 5 is:"+var1);
[Link]("Tan of 30 is:"+var2);
}
}

Output:

1/2
Square of 5 is:2.23606797749979
Tan of 30 is:-6.405331196646276

Points to note:
1) Package import syntax:

import static [Link];


import static [Link].*;

2) Note comments given in the above code.

When to use static imports?

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

String number = "123";


int result = [Link](number);
[Link](result); // Output: 123

2. Using [Link]()
The [Link]() method converts a String to an Integer object, which can then be
unboxed to a primitive int.

String number = "123";


int result = [Link](number);
[Link](result); // Output: 123

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.

String number = "123abc"; // This will cause an exception


try {
int result = [Link](number);
[Link](result);
} catch (NumberFormatException e) {
[Link]("This value cannot be parsed as an integer");
}

String to int Conversion Example


Let’s write a complete program for string to int conversion using both the methods that we
discussed above. We are also handling exception, if in case the string cannot be parsed as an
integer.

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:

Using [Link](): 123


Using [Link](): 123
Invalid number format: 123a

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.

A Simple swing example


In the below example we would be using several swing components that you have not learnt so
far in this tutorial. We will be discussing each and everything in detail in the coming swing
tutorials.
The below swing program would create a login screen.

1/4
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class SwingFirstExample {

public static void main(String[] args) {


// Creating instance of JFrame
JFrame frame = new JFrame("My First Swing Example");
// Setting the width and height of frame
[Link](350, 200);
[Link](JFrame.EXIT_ON_CLOSE);

/* Creating panel. This is same as a div tag in HTML


* We can create several panels and add them to specific
* positions in a JFrame. Inside panels we can add text
* fields, buttons and other components.
*/
JPanel panel = new JPanel();
// adding panel to frame
[Link](panel);
/* calling user defined method for adding components
* to the panel.
*/
placeComponents(panel);

// Setting the frame visibility to true


[Link](true);
}

private static void placeComponents(JPanel panel) {

/* We will discuss about layouts in the later sections


* of this tutorial. For now we are setting the layout
* to null
*/
[Link](null);

// 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);

/* Creating text field where user is supposed to

2/4
* enter user name.
*/
JTextField userText = new JTextField(20);
[Link](100,20,165,25);
[Link](userText);

// Same process for password label and text field.


JLabel passwordLabel = new JLabel("Password");
[Link](10,50,80,25);
[Link](passwordLabel);

/*This is similar to text field but it hides the user


* entered data and displays dots instead to protect
* the password like we normally see on login screens.
*/
JPasswordField passwordText = new JPasswordField(20);
[Link](100,50,165,25);
[Link](passwordText);

// Creating login button


JButton loginButton = new JButton("login");
[Link](10, 80, 80, 25);
[Link](loginButton);
}

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];

public class ListIteratorExample {


public static void main(String a[]){
ListIterator<String> litr = null;
List<String> names = new ArrayList<String>();
[Link]("Shyam");
[Link]("Rajat");
[Link]("Paul");
[Link]("Tom");
[Link]("Kate");
//Obtaining list iterator
litr=[Link]();

[Link]("Traversing the list in forward direction:");


while([Link]()){
[Link]([Link]());
}
[Link]("\nTraversing the list in backward direction:");
while([Link]()){
[Link]([Link]());
}
}
}

Output:

1/2
Traversing the list in forward direction:
Shyam
Rajat
Paul
Tom
Kate

Traversing the list in backward direction:


Kate
Tom
Paul
Rajat
Shyam

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:

str -> [Link](str)

then you can replace it with a method reference 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).

Four types of method references


1. Method reference to an instance method of an object – object::instanceMethod
2. Method reference to a static method of a class – Class::staticMethod
3. Method reference to an instance method of an arbitrary object of a particular type –
Class::instanceMethod
4. Method reference to a constructor – Class::new

1. Method reference to an instance method of an object

@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:

Product of given number is: 55

3. Method reference to an instance method of an arbitrary object of a


particular type
import [Link];
public class Example {

public static void main(String[] args) {


String[] stringArray = { "Steve", "Rick", "Aditya", "Negan", "Lucy", "Sansa",
"Jon"};
/* Method reference to an instance method of an arbitrary
* object of a particular type
*/
[Link](stringArray, String::compareToIgnoreCase);
for(String str: stringArray){
[Link](str);
}
}
}

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

You might also like