Java Multithreading

Multithreading in Java

Multithreading in Java

Multithreading in java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory area. They don’t allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.


Advantages of Java Multithreading

1) It doesn’t block the user because threads are independent and you can perform multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn’t affect other threads if an exception occurs in a single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways:

  • Process-based Multitasking (Multiprocessing)
  • Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

  • Each process has an address in memory. In other words, each process allocates a separate memory area.
  • A process is heavyweight.
  • Cost of communication between the process is high.
  • Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)

  • Threads share the same address space.
  • A thread is lightweight.
  • Cost of communication between the thread is low.

Note: At least one process is required for each thread.

1). What is Thread in java

A thread is a lightweight sub-process, the smallest unit of processing. It is a separate path of execution.

Threads are independent. If there occurs exception in one thread, it doesn’t affect other threads. It uses a shared memory area.

Java Multithreading

As shown in the above figure, a thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS, and one process can have multiple threads.

Note: At a time one thread is executed only.

Java Thread class

Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.

Java Thread Methods

S.N.Modifier and TypeMethodDescription
1)voidstart()It is used to start the execution of the thread.
2)voidrun()It is used to do an action for a thread.
3)static voidsleep()It sleeps a thread for the specified amount of time.
4)static ThreadcurrentThread()It returns a reference to the currently executing thread object.
5)voidjoin()It waits for a thread to die.
6)intgetPriority()It returns the priority of the thread.
7)voidsetPriority()It changes the priority of the thread.
8)StringgetName()It returns the name of the thread.
9)voidsetName()It changes the name of the thread.
10)longgetId()It returns the id of the thread.
11)booleanisAlive()It tests if the thread is alive.
12)static voidyield()It causes the currently executing thread object to pause and allow other threads to execute temporarily.
13)voidsuspend()It is used to suspend the thread.
14)voidresume()It is used to resume the suspended thread.
15)voidstop()It is used to stop the thread.
16)voiddestroy()It is used to destroy the thread group and all of its subgroups.
17)booleanisDaemon()It tests if the thread is a daemon thread.
18)voidsetDaemon()It marks the thread as daemon or user thread.
19)voidinterrupt()It interrupts the thread.
20)booleanisinterrupted()It tests whether the thread has been interrupted.
21)static booleaninterrupted()It tests whether the current thread has been interrupted.
22)static intactiveCount()It returns the number of active threads in the current thread’s thread group.
23)voidcheckAccess()It determines if the currently running thread has permission to modify the thread.
24)static booleanholdLock()It returns true if and only if the current thread holds the monitor lock on the specified object.
25)static voiddumpStack()It is used to print a stack trace of the current thread to the standard error stream.
26)StackTraceElement[]getStackTrace()It returns an array of stack trace elements representing the stack dump of the thread.
27)static intenumerate()It is used to copy every active thread’s thread group and its subgroup into the specified array.
28)Thread.StategetState()It is used to return the state of the thread.
29)ThreadGroupgetThreadGroup()It is used to return the thread group to which this thread belongs
30)StringtoString()It is used to return a string representation of this thread, including the thread’s name, priority, and thread group.
31)voidnotify()It is used to give the notification for only one thread which is waiting for a particular object.
32)voidnotifyAll()It is used to give the notification to all waiting threads of a particular object.
33)voidsetContextClassLoader()It sets the context ClassLoader for the Thread.
34)ClassLoadergetContextClassLoader()It returns the context ClassLoader for the thread.
35)static Thread.UncaughtExceptionHandlergetDefaultUncaughtExceptionHandler()It returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.
36)static voidsetDefaultUncaughtExceptionHandler()It sets the default handler invoked when a thread abruptly terminates due to an uncaught exception.

2).Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

  1. New
  2. Runnable
  3. Running
  4. Non-Runnable (Blocked)
  5. Terminated

1) New

The thread is in new state if you create an instance of Thread class but before the invocation of start() method

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

3).How to create thread

There are two ways to create a thread:

  1. By extending Thread class
  2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

  • Thread()
  • Thread(String name)
  • Thread(Runnable r)
  • Thread(Runnable r,String name)

Commonly used methods of Thread class:

  1. public void run(): is used to perform action for a thread.
  2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
  3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
  4. public void join(): waits for a thread to die.
  5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
  6. public int getPriority(): returns the priority of the thread.
  7. public int setPriority(int priority): changes the priority of the thread.
  8. public String getName(): returns the name of the thread.
  9. public void setName(String name): changes the name of the thread.
  10. public Thread currentThread(): returns the reference of currently executing thread.
  11. public int getId(): returns the id of the thread.
  12. public Thread.State getState(): returns the state of the thread.
  13. public boolean isAlive(): tests if the thread is alive.
  14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
  15. public void suspend(): is used to suspend the thread(depricated).
  16. public void resume(): is used to resume the suspended thread(depricated).
  17. public void stop(): is used to stop the thread(depricated).
  18. public boolean isDaemon(): tests if the thread is a daemon thread.
  19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
  20. public void interrupt(): interrupts the thread.
  21. public boolean isInterrupted(): tests if the thread has been interrupted.
  22. public static boolean interrupted(): tests if the current thread has been interrupted.

Example 1:-Java Thread Example by extending Thread class

class Multithreading1st extends Thread
{
public void run()
{
System.out.println(“thread is running…”);
}
public static void main(String args[])
{
Multithreading1st t1=new Multithreading1st();
t1.start();
}
}

Example 2:-Java Thread Example by implementing Runnable interface

class Multithreading2nd implements Runnable
{
public void run()
{
System.out.println(“thread is running…”);
}

public static void main(String args[])
{
Multithreading2nd m1=new Multithreading2nd();
Thread t1 =new Thread(m1);
t1.start();
}
}

4).Sleep method in java

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

  • public static void sleep(long miliseconds)throws InterruptedException
  • public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example 1

class Multithreadingsleep extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
Multithreadingsleep t1=new Multithreadingsleep();
Multithreadingsleep t2=new Multithreadingsleep();
t1.start();
t2.start();
}
}

5).What if we call run() method directly instead start() method?

  • Each thread starts in a separate call stack.
  • Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.

Example 1:-

class Multithreadingrun extends Thread
{
public void run()
{
System.out.println(“running…”);
}
public static void main(String args[])
{
Multithreadingrun t1=new Multithreadingrun();
t1.run();//fine, but does not start a separate call stack
}
}   

Example 2:-Problem if you direct call run() method

class Multithreadingrun1st extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
Multithreadingrun1st t1=new Multithreadingrun1st();
Multithreadingrun1st t2=new Multithreadingrun1st();
t1.run();
t2.run();

6).The join() method

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

Syntax:

public void join()throws InterruptedException

public void join(long milliseconds)throws InterruptedException

Example 1:-

class Multithreadingjoin extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
Multithreadingjoin t1=new Multithreadingjoin();
Multithreadingjoin t2=new Multithreadingjoin();
Multithreadingjoin t3=new Multithreadingjoin();
t1.start();
try
{
t1.join();
}
catch(Exception e)
{
System.out.println(e);
}
t2.start();
t3.start();
}
}

Example 2:-

class Multithreadingjoin1st extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
Multithreadingjoin1st t1=new Multithreadingjoin1st ();
Multithreadingjoin1st t2=new Multithreadingjoin1st ();
Multithreadingjoin1st t3=new Multithreadingjoin1st ();
t1.start();
try
{
t1.join(1500);
}
catch(Exception e)
{
System.out.println(e);
}
t2.start();
t3.start();
}
}

7).Naming Thread and Current Thread

Naming Thread

The Thread class provides methods to change and get the name of a thread. By default, each thread has a name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using setName() method. The syntax of setName() and getName() methods are given below:

  1. public String getName(): is used to return the name of a thread.
  2. public void setName(String name): is used to change the name of a thread.

Example 1:-

class Multithreadingname extends Thread
{
public void run()
{
System.out.println(“running…”);
}
public static void main(String args[])
{
Multithreadingname t1=new Multithreadingname();
Multithreadingname t2=new Multithreadingname();
System.out.println(“Name of t1:”+t1.getName());
System.out.println(“Name of t2:”+t2.getName());
t1.start();
t2.start();
t1.setName(“Sonoo Jaiswal”);
System.out.println(“After changing name of t1:”+t1.getName());
}
}

Example 2:-

Current Thread

The currentThread() method returns a reference of currently executing thread.

class Multithreadingname1st extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[])
{
Multithreadingname1st t1=new Multithreadingname1st();
Multithreadingname1st t2=new Multithreadingname1st();
t1.start();
t2.start();
}
}

8).Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

3 constants defined in Thread class:

  • public static int MIN_PRIORITY
  • public static int NORM_PRIORITY
  • public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Example 1:-

class Multithreadingpriority extends Thread
{
public void run()
{
System.out.println(“running thread name is:”+Thread.currentThread().getName());
System.out.println(“running thread priority is:”+Thread.currentThread().getPriority());

}
public static void main(String args[])
{
Multithreadingpriority m1=new Multithreadingpriority();
Multithreadingpriority m2=new Multithreadingpriority();
m1.setPriority(Thread.MAX_PRIORITY);
m2.setPriority(Thread.MIN_PRIORITY);
m1.start(); 
m2.start();

}
}

Hits: 35

hierarchy of exception handling

Exception Handling in Java

Exception Handling in Java

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.

Java Exception are two types checked and unchecked

What is Exception in Java

Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.


What is Exception Handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application that is why we use exception handling. 

  1. statement 1;  
  2. statement 2;  
  3. statement 3;  
  4. statement 4;  
  5. statement 5;//exception occurs  
  6. statement 6;  
  7. statement 7;  
  8. statement 8;  
  9. statement 9;  
  10. statement 10;  

Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling, the rest of the statement will be executed. That is why we use exception handling in Java.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:

hierarchy of exception handling

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are three types of exceptions:

  1. Checked Exception
  2. Unchecked Exception
  3. Error
Types of Java Exceptions

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

KeywordDescription
tryThe “try” keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can’t use try block alone.
catchThe “catch” block is used to handle the exception. It must be preceded by try block which means we can’t use catch block alone. It can be followed by finally block later.
finallyThe “finally” block is used to execute the important code of the program. It is executed whether an exception is handled or not.
throwThe “throw” keyword is used to throw an exception.
throwsThe “throws” keyword is used to declare exceptions. It doesn’t throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

  1. int a=50/0;//ArithmeticException  

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.

  1. String s=null;  
  2. System.out.println(s.length());//NullPointerException  

3) A scenario where NumberFormatException occurs

The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that has characters, converting this variable into digit will occur NumberFormatException.

  1. String s=“abc”;  
  2. int i=Integer.parseInt(s);//NumberFormatException  

4) A scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as shown below:

  1. int a[]=new int[5];  
  2. a[10]=50; //ArrayIndexOutOfBoundsException  

Java Exceptions Index

  1. Java Try-Catch Block
  2. Java Multiple Catch Block
  3. Java Nested Try
  4. Java Finally Block
  5. Java Throw Keyword
  6. Java Throws Keyword
  7. Java Throw vs Throws
  8. Java Final vs Finally vs Finalize
  9. Java Custom Exceptions

1). Java Try-Catch Block

Java try block

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.

Java try block must be followed by either catch or finally block.

Java catch block

Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch block with a single try block.

Example 1:- To use single Catch to solve Arithmetic Exception

public class Exception1st
{

public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println(“Can’t divided by zero”);
}
}
}

Example 2:- To use single Catch to solve Array out of Bound of Exception

public class Exception2nd
{

public static void main(String[] args)
{
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println(“Array out of Bound Exception”);
}
}

Example 3:In this example show how to handle exception

public class Exceptionhandle
{

public static void main(String[] args)
{
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}

2).Java Multiple Catch Block

A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.

Points to remember

  • At a time only one exception occurs and at a time only one catch block is executed.
  • All catch blocks must be ordered from most specific to most general, i.e. catch for Arithmetic Exception must come before catch for Exception.

Example 1:

In this Example we check for arithmetic exception.

public class Exception3rd
{
public static void main(String[] args)
{

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println(“Arithmetic Exception occurs”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“ArrayIndexOutOfBounds Exception occurs”);
}
catch(Exception e)
{
System.out.println(“Parent Exception occurs”);
}
System.out.println(“rest of the code”);
}
}

Example 2:

In this Example we check for ArrayIndexOutOfBoundsException

public class Exception4th
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];

System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println(“Arithmetic Exception occurs”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“ArrayIndexOutOfBounds Exception occurs”);
}
catch(Exception e)
{
System.out.println(“Parent Exception occurs”);
}
System.out.println(“rest of the code”);
}
}

3).Java Nested try block

The try block within a try block is known as nested try block in java.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

Example 1:

public class Exception5th
{
public static void main(String args[])
{
try{
try
{
System.out.println(“going to divide”);
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

System.out.println(“other statement”);
}
catch(Exception e)
{
System.out.println(“handeled”);
}
System.out.println(“normal flow..”);
}
}

4).Java finally block

Java finally block is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

java finally


Example 1:

public class Exceptionfinally
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println(“finally block is always executed”);
}
System.out.println(“rest of the code…”);
}
}

5).Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. 

The syntax of java throw keyword is given below.

Example 1:
public class Exceptionthrow
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException(“not valid”);
else
System.out.println(“welcome to vote”);
}
public static void main(String args[])
{
validate(13);
System.out.println(“rest of the code…”);
}
}

6).Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception

Example 1:

import java.io.IOException;
public class Exceptionthrows
{
void m()throws IOException
{
throw new IOException(“device error”);//checked exception
}
void p()
{
try
{
m();
}
catch(Exception e)
{
System.out.println(“exception handled”);
}
}
public static void main(String args[])
{
Exceptionthrows obj=new Exceptionthrows ();
obj.p();
System.out.println(“normal flow…”);
}
}

Example 2:-

import java.io.*;
class Exceptionthrows1st
{
void method()throws IOException
{
System.out.println(“device operation performed”);
}
}
class Testthrows3
{
public static void main(String args[])throws IOException{//declare exception
Exceptionthrows1st m=new Exceptionthrows1st();
m.method();

System.out.println(“normal flow…”);
}
}

Example 3:-

import java.io.*;
class Exceptionthrows2nd
{
void method()throws IOException
{
throw new IOException(“device error”);
}
}
class Testthrows4
{
public static void main(String args[])throws IOException
{//declare exception
Exceptionthrows2nd m=new Exceptionthrows2nd();
m.method();

System.out.println(“normal flow…”);
}
}

7).Difference between throw and throws in Java

There are many differences between throw and throws keywords. A list of differences between throw and throws are given below:

No.throwthrows
1)Java throw keyword is used to explicitly throw an exception.Java throws keyword is used to declare an exception.
2)Checked exception cannot be propagated using throw only.Checked exception can be propagated with throws.
3)Throw is followed by an instance.Throws is followed by class.
4)Throw is used within the method.Throws is used with the method signature.
5)You cannot throw multiple exceptions.You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.

8).Difference between final, finally and finalize

There are many differences between final, finally and finalize. A list of differences between final, finally and finalize are given below:

No.finalfinallyfinalize
1)Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed.Finally is used to place important code, it will be executed whether exception is handled or not.Finalize is used to perform clean up processing just before object is garbage collected.
2)Final is a keyword.Finally is a block.Finalize is a method.

Example 1:

public class finalkeyword
{
public static void main(String[] args)
{
final int x=100;
x=200;//Compile Time Error  
}
}

Example 2:

public class finalblock
{
public static void main(String[] args)
{
try
{
int x=300;
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
System.out.println(“finally block is executed”);
}
}
}

Example 3:

class Finalmethod
{
public void finalize()
{
System.out.println(“finalize called”);
}
public static void main(String[] args)
{
Finalmethod f1=new Finalmethod();
Finalmethod f2=new Finalmethod();
f1=null;
f2=null;
System.gc();
}
}

Custom Exception

If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let’s see a simple example of java custom exception.

class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
public class Exceptioncustom
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException(“not valid”);
else
System.out.println(“welcome to vote”);
}

public static void main(String args[])
{
try
{
validate(13);
}catch(Exception m)
{System.out.println(“Exception occured: “+m);
}

System.out.println(“rest of the code…”);
}
}

Hits: 51

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don’t know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

  1. Abstract class 
  2. Interface 

1).Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember

  • An abstract class must be declared with an abstract keyword.
  • It can have abstract and non-abstract methods.
  • It cannot be instantiated.
  • It can have constructors and static methods also.
  • It can have final methods which will force the subclass not to change the body of the method.

Example 1 

abstract class Bike
{
abstract void run();
}
class abstractfirst extends Bike
{
void run()
{
System.out.println(“running safely”);
}
public static void main(String[] args)
{
abstractfirst obj=new abstractfirst();
obj.run();
}
}

Example 2

abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println(“drawing rectangle”);
}
}
class Circle extends Shape
{
void draw()
{
System.out.println(“drawing circle”);
}
}
class abstract2nd
{
public static void main(String args[])
{
Circle c=new Circle();
c.draw();
Rectangle r=new Rectangle();
r.draw();
}
}

Example 3

abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
class Testank
{
public static void main(String[] args)
{
SBI bs=new SBI();
System.out.println(“Rate of interest is:” +bs.getRateOfInterest()+”%”);
PNB bp=new PNB();
System.out.println(“Rate of interest is:” +bp.getRateOfInterest()+”%”);
}
}

Abstract class having constructor, data member and methods

An abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and even main() method.

Example 4

abstract class Bike1
{
Bike1()
{
System.out.println(“bike is created”);
}
abstract void run();
void changeGear()
{
System.out.println(“gear changed”);
}
}
class Honda extends Bike1
{
void run()
{
System.out.println(“running safely”);
}
}
public class abstractconstructor
{
public static void main(String[] args)
{
Honda obj=new Honda();
obj.run();
obj.changeGear();
}
}

Rule: If there is an abstract method in a class, that class must be abstract.

  1. class Bike12{  
  2. abstract void run();  
  3. }  

Rule: If you are extending an abstract class that has an abstract method, you must either provide the implementation of the method or make this class abstract.

2).Interface

An interface in java is a blueprint of a class. It has static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body.

Example

interface A2
{
void a();
void b();
void c();
void d();
}

abstract class B2 implements A2
{
public void c()
{
System.out.println(“I am c”);
}
}
class M2 extends B2
{
public void a()
{
System.out.println(“I am a”);
}
public void b()
{
System.out.println(“I am b”);
}
public void d()
{
System.out.println(“I am d”);
}
}

public class abstractinterface
{
public static void main(String[] args)
{
M2 mm=new M2();
mm.a();
mm.b();
mm.c();
mm.d();
}
}

Hits: 64

Polymorphism in Java

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.

Real life example of polymorphism: A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behaviour in different situations. This is called polymorphism.

Polymorphism is considered as one of the important features of Object Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms.

In Java polymorphism is mainly divided into two types:

  • Compile time Polymorphism
  • Runtime Polymorphism
  1. Compile time polymorphism: It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading.
    • Method Overloading: When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments.
      1. Example: By using different types of arguments class MultiplyFun
        { // Method with 2 parameter
        static int Multiply(int a, int b)
        {
        return a * b;
        } // Method with the same name but 3 parameter
        static int Multiply(int a, int b, int c)
        {
        return a * b * c;
        }
        } class methodoverloading
        {
        public static void main(String[] args)
        {
        MultiplyFun mul=new MultiplyFun(); System.out.println(MultiplyFun.Multiply(2, 4));
        System.out.println(MultiplyFun.Multiply(2, 7, 3));
        }
        }
      2. Example: By using different numbers of arguments // Java program for Method overloading class MultiplyFun { // Method with 2 parameter static int Multiply(int a, int b) { return a * b; } // Method with the same name but 2 double parameter static double Multiply(double a, double b) { return a * b; } } class methodoverloading2 { public static void main(String[] args) { System.out.println(MultiplyFun.Multiply(2, 4)); System.out.println(MultiplyFun.Multiply(5.5, 6.3)); } }
    • Operator Overloading: Java also provide option to overload operators. For example, we can make the operator (‘+’) for string class to concatenate two strings. We know that this is the addition operator whose task is to add two operands. So a single operator ‘+’ when placed between integer operands, adds them and when placed between string operands, concatenates them.In java, Only “+” operator can be overloaded:
      • To add integers
      • To concatenate strings
      Example: class OperatorOVERDDN
      {
      void operator(String str1, String str2)
      {
      String s = str1 + str2;
      System.out.println(“Concatinated String – “+ s);
      }
      void operator(int a, int b)
      {
      int c = a + b;
      System.out.println(“Sum = ” + c);
      }
      }
      class operatoroverloading
      {
      public static void main(String[] args)
      {
      OperatorOVERDDN obj = new OperatorOVERDDN();
      obj.operator(2, 3);
      obj.operator(“Ruchika “, “Katoch”);
      }
      }
  2. Runtime polymorphism: It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding.
    • Method overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.Example: class Parent
      {
      void Print()
      {
      System.out.println(“parent class”);
      }
      }
      class subclass1 extends Parent
      {
      void Print()
      {
      System.out.println(“subclass1”);
      }
      } class subclass2 extends Parent
      {
      void Print()
      {
      System.out.println(“subclass2”);
      }
      } class TestPolymorphism3
      {
      public static void main(String[] args)
      { subclass1 aa= new subclass1();
      aa.Print();
      subclass2 aa1= new subclass2();
      aa1.Print();
      }
      } No. Method Overloading Method Overriding 1) Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class. 2) Method overloading is performed within class. Method overriding occurs in two classes that have IS-A (inheritance) relationship. 3) In case of method overloading, parameter must be different. In case of method overriding, parameter must be same. 4) Method overloading is the example of compile time polymorphism. Method overriding is the example of run time polymorphism. 5) In java, method overloading can’t be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Return type must be same or covariant in method overriding.

Hits: 13

Types of inheritance in Java

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

  • For Method Overriding (so runtime polymorphism can be achieved).
  • For Code Reusability.

Terms used in Inheritance

  • Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
  • Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
  • Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
  • Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
    Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
Types of inheritance in Java
Multiple inheritance in Java

1).Single Inheritance 

Example:-

class Animal

{
void eat()

{

System.out.println(“eating…”);

}
}
class Dog extends Animal

{
void bark()

{System.out.println(“barking…”);

}
}
class TestInheritance

{
public static void main(String args[])

{
Dog d=new Dog();
d.bark();
d.eat();
}}

2).Multilevel Inheritance 

Example:-

class Animal

{
void eat()

{

System.out.println(“eating…”);

}
}
class Dog extends Animal

{
void bark()

{

System.out.println(“barking…”);

}
}
class BabyDog extends Dog

{
void weep(){System.out.println(“weeping…”);

}
}
class TestInheritance2

{
public static void main(String args[])

{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}

}

3)Hierarchical Inheritance Example

class Animal

{
void eat()

{

System.out.println(“eating…”);

}
}
class Dog extends Animal

{
void bark(){System.out.println(“barking…”);

}
}
class Cat extends Animal

{
void meow()

{

System.out.println(“meowing…”);

}
}
class TestInheritance3

{
public static void main(String args[])

{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}

}

4).Multiple Inheritance in Java

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. 

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 reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

    GrandParent
           /     \
          /       \
      Parent1      Parent2
          \       /
           \     /
             Test

Solution:-

Multiple inheritance in java can be implemented by the use of interfaces.

What is Interface in java:-

Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final).

default and static methods may have implementation in the interface definition.

Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the non-default methods described in the interface, or be an abstract class

Super Keyword in java

The super keyword in Java is a reference variable which is used to refer immediate parent class object.

Example:-

interface PI1 
{ 
    // default method 
    default void show() 
    { 
        System.out.println("Default PI1"); 
    } 
} 
  
interface PI2 
{ 
    // Default method 
    default void show() 
    { 
        System.out.println("Default PI2"); 
    } 
} 
  
// Implementation class code 
class Multipleinheritance implements PI1, PI2 
{ 
    // Overriding default show method 
    public void show() 
    { 
        // use super keyword to call the show 
        // method of PI1 interface 
        PI1.super.show(); 
  
        // use super keyword to call the show 
        // method of PI2 interface 
        PI2.super.show(); 
    } 
  
    public static void main(String args[]) 
    { 
        Multipleinheritance d = new Multipleinheritance(); 
        d.show(); 
    } 
}

Hits: 26

Constructors in Java

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn’t have any.

Rules for creating Java constructor

There are two rules defined for the constructor.

  1. Constructor name must be the same as its class name
  2. A Constructor must have no explicit return type
  3. A Java constructor cannot be abstract, static, final, and synchronized
    Types of Java constructors There are two types of constructors in Java:
    1. Default constructor (no-arg constructor)
    2. Parameterized constructor

1) Java Default Constructor

A constructor is called “Default Constructor” when it doesn’t have any parameter

Example of default constructor

class Defaultconstructor

{

Defaultconstructor()
{
System.out.println(“Constructor is created”);

}

public static void main(String args[])

{
Defaultconstructor b=new Defaultconstructor();
}
}

2)Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.

class Paraconstructor
{
int id;
String name;

Paraconstructor(int i,String n)
{
id = i;
name = n;
}
void display(){System.out.println(id+” “+name);}

public static void main(String args[]){
Paraconstructor s1 = new Paraconstructor(111,”Karan”);
Paraconstructor s2 = new Paraconstructor(222,”Aryan”);
s1.display();
s2.display();
}
}

Difference between constructor and method in Java

There are many differences between constructors and methods. They are given below.

Java ConstructorJava Method
A constructor is used to initialize the state of an object.A method is used to expose the behavior of an object.
A constructor must not have a return type.A method must have a return type.
The constructor is invoked implicitly.The method is invoked explicitly.
The Java compiler provides a default constructor if you don’t have any constructor in a class.The method is not provided by the compiler in any case.
The constructor name must be same as the class name.The method name may or may not be same as the class name.

Hits: 35

Operators in java

Java Operators

Operators are used to perform operations on variables and values.

The value is called an operand, while the operation (to be performed between the two operands) is defined by an 

public class MyClass

{
public static void main(String[] args)

{
int x = 100 + 50;
System.out.println(x);
}
}

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

public class MyClass

{
public static void main(String[] args)

{
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
}
}

Java divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators

1).Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

OperatorNameDescriptionExample 
+AdditionAdds together two valuesx + y 
SubtractionSubtracts one value from anotherx – y 
*MultiplicationMultiplies two valuesx * y 
/DivisionDivides one value from anotherx / y 
%ModulusReturns the division remainderx % y 
++IncrementIncreases the value of a variable by ++x 
DecrementDecreases the value of a variable by 1–x

2).Java Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

public class MyClass

{
public static void main(String[] args)

{
int x = 10;
System.out.println(x);
}
}

The addition assignment operator (+=) adds a value to a variable:

public class MyClass

{
public static void main(String[] args)

{
int x = 10;
x += 5;
System.out.println(x);
}
}

A list of all assignment operators:

OperatorDescriptionExample
=Simple assignment operator. Assigns values from right side operands to left side operand.C = A + B will assign value of A + B into C
+=Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand.C += A is equivalent to C = C + A
-=Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand.C -= A is equivalent to C = C – A
*=Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand.C *= A is equivalent to C = C * A
/=Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand.C /= A is equivalent to C = C / A
%=Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand.C %= A is equivalent to C = C % A
<<=Left shift AND assignment operator.C <<= 2 is same as C = C << 2
>>=Right shift AND assignment operator.C >>= 2 is same as C = C >> 2
&=Bitwise AND assignment operator.C &= 2 is same as C = C & 2
^=bitwise exclusive OR and assignment operator.C ^= 2 is same as C = C ^ 2
|=bitwise inclusive OR and assignment operator.C |= 2 is same as C = C | 2

3).Java Comparison Operators

Comparison operators are used to compare two values:

OperatorNameExample 
==Equal tox == y 
!=Not equalx != y 
>Greater thanx > y 
<Less thanx < y 
>=Greater than or equal tox >= y 
<=Less than or equal tox <= y

4).Java Logical Operators

Logical operators are used to determine the logic between variables or values:

OperatorNameDescriptionExample 
&& Logical andReturns true if both statements are truex < 5 &&  x < 10 
|| Logical orReturns true if one of the statements is truex < 5 || x < 4 
!Logical notReverse the result, returns false if the result is true!(x < 5 && x < 10)

Hits: 16

Strings in java

Java Strings

Strings are used for storing text.

String variable contains a collection of characters surrounded by double quotes:

Example

Create a variable of type String and assign it a value:

public class MyClass

{
public static void main(String[] args)

{
String abc = “Hello”;
System.out.println(abc);
}
}

1)String Length

A String in Java is actually an object, which contain methods that can perform certain operations on strings. For example, the length of a string can be found with the length() method:

Example

public class MyClass

{
public static void main(String[] args)

{
String txt = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
System.out.println(“The length of the txt string is: ” + txt.length());
}
}

2)More String Methods

There are many string methods available, for example toUpperCase() and toLowerCase():

public class MyClass

{
public static void main(String[] args)

{
String txt = “Hello World”;
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}
}

3)Finding a String in a String

The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including whitespace):

public class MyClass

{
public static void main(String[] args)

{
String txt = “Please locate where ‘locate’ occurs!”;
System.out.println(txt.indexOf(“locate”));
}
}

4)String Concatenation

The + operator can be used between strings to add them together to make a new string. This is called concatenation:

public class MyClass

{
public static void main(String[] args)

{
String firstName = “Ruchika”;
String lastName = “Katoch”;
System.out.println(firstName + ” ” + lastName);
}
}

You can also use the concat() method to concatenate two strings:

public class MyClass

{
public static void main(String[] args)

{
String firstName = “Ruchika”;
String lastName = “Katoch”;
System.out.println(firstName.concat(lastName));
}
}

5)Special Characters

Because strings must be written within quotes, Java will misunderstand this string, and generate an error:

String txt = “We are the so-called “Vikings” from the north.”;

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

Escape character Result Description
\’ Single quote
\” Double quote
\\ \ Backslash

The sequence \"  inserts a double quote in a string:

public class MyClass {
public static void main(String[] args)

{
String txt = “We are the so-called \”Vikings\” from the north.”;
System.out.println(txt);
}
}

The sequence \'  inserts a single quote in a string:

public class MyClass

{
public static void main(String[] args)

{
String txt = “It\’s alright.”;
System.out.println(txt);
}
}

The sequence \\  inserts a backslash in a string:

public class MyClass

{
public static void main(String[] args)

{
String txt = “The character \\ is called backslash.”;
System.out.println(txt);
}
}

Six other escape sequences are valid in Java:

Code Result
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed

6)Adding Numbers and Strings

Java uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two strings, the result will be a string concatenation:

Example

public class MyClass

{
public static void main(String[] args)

{
String x = “10”;
String y = “20”;
String z = x + y;
System.out.println(z);
}
}

Hits: 8

Boolean in Java

Java Booleans

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

For this, Java has a boolean data type, which can take the values true or false.

1)Boolean Values

A boolean type is declared with the boolean keyword and can only take the values true or false:

public class MyClass
{
public static void main(String[] args)
{
boolean firstvalue = true;
boolean secondvalue = false;
System.out.println(firstvalue);
System.out.println(secondvalue);
}
}

However, it is more common to return boolean values from boolean expressions, for conditional testing (see below).


2)Boolean Expression

Boolean expression is a Java expression that returns a Boolean value: true or false.

You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:

Example

public class MyClass

{
public static void main(String[] args)

{
int x = 10;
int y = 9;
System.out.println(x > y); // returns true, because 10 is higher than 9
}
}

Example

public class MyClass

{
public static void main(String[] args)

{
System.out.println(10 > 9); // returns true, because 10 is higher than 9
}
}

Example

In the examples below, we use the equal to (==) operator to evaluate an expression:

public class MyClass

{
public static void main(String[] args)

{
int x = 10;
System.out.println(x == 10); // returns true, because the value of x is equal to 10
}
}

Example

public class MyClass

{
public static void main(String[] args)

{
System.out.println(15 == 10); // returns false, because 10 is not equal to 15
}
}

Hits: 36

If … Else in Java

Java Conditions and If Statements

Java supports the usual logical conditions from mathematics:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to a == b
  • Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

1)The if Statement

Use the if statement to specify a block of Java code to be executed if a condition is true.

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:

Example

public class MyClass

{
public static void main(String[] args)

{
int x = 20;
int y = 18;
if (x > y)

{
System.out.println(“x is greater than y”);
}
}
}

2)The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Example

public class Conditional

{
public static void main(String[] args)

{
int x = 20;
int y = 18;
if (x > y)
{
System.out.println(“x is greater than y”);
}
else
{
System.out.println(“y is greater then x”);
}
}
}

3)The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Example

public class Conditional

{
public static void main(String[] args)

{
int x = 20;
int y = 18;
if (x > y)
{
System.out.println(“x is greater than y”);
}
else if(y > x)
{
System.out.println(“y is greater then x”);
}
else
{
System.out.println(“x is equal y”);
}
}
}

Hits: 12