Tuesday, March 3, 2015

Autoboxing and Autounboxing

Autoboxing is the process of converting the primitive type to Wrapper type(object) and unboxing is the vice versa .Below example illustrate the same.

package autobox;

public class AutoBoxExample {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int i=10;
  Integer i1=new Integer(i);//boxing
  Integer i2=20;//boxing
  int i3=i2;//unboxing
  System.out.println(i1);
 }

}

output:
10 >>>Final
------------------------------------------------------------------------------------------------------------

Interfaces

Interface is used to attain 100% abstraction.
-- Interface contains only the definition and not the implementation.
-- interface by default attach variable (public static final) and for method it is (public and abstract)
-- interface can extends any number of interfaces and class can implement any number of interfaces.
-- The rule is it must override all the methods defined in the interface else it needs to be defined as abstract.


------

>>>Final
------------------------------------------------------------------------------------------------------------

Monday, March 2, 2015

enum in Java

enum in java is a datatype which hold constant values. Please follow the below example to explore more about enum.

 
package Enumpackage;

public class enumexampleagain {
 enum days{mon(10),tue,wed(20),thu,fri(30),sat,sun(100);
 private int result;
 days(){
  System.out.println("default constructor of days");
 }
 days(int i){
  this.result=i;
  System.out.println("This day as some value "+this.result);
 }
}
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  for(days d:days.values()){
   System.out.println(d);
  }
  if(days.mon==days.tue){
   System.out.println("Do something different");
  }
  else{
   System.out.println("everyday is a new day");
  }
  
 }

}

output: This day as some value 10
default constructor of days
This day as some value 20
default constructor of days
This day as some value 30
default constructor of days
This day as some value 100
mon
tue
wed
thu
fri
sat
sun
everyday is a new day

>>>Final
------------------------------------------------------------------------------------------------------------

Daemon Thread

A Daemon Thread is a thread that runs in the background, JVM stops if all the user threads are stopped and doesn't bother about the daemon thread. Used for garbage collection, clock handler

 
package Threadsdeamon;

public class mainclass {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Thread t=new Thread1();
  Runnable t2=new Thread2();
  t.setDaemon(true);
  t.start();
  new Thread(t2).start(); 
  
  if(t.isDaemon()){
   System.out.println("Daemon thread is still alive");
  }
 }

}


>>>
------------------------------------------------------------------------------------------------------------

Priority of Threads

By Default the priority of the thread is 5 and you can set the priority of the thread to minimum which is 1 and max which is 10. Below example illustrates the same.

package Threadspriority;

public class mainclass {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Thread t=new thread1();
  Runnable r=new thread2();
  
  t.start();  
  new Thread(r).start();
  System.out.println(t.getName());
  System.out.println("Priority of the thread by default"+t.getPriority());
  t.setPriority(t.MIN_PRIORITY);
  System.out.println("Priority of the thread after setting "+t.getPriority());
  t.setPriority(t.MAX_PRIORITY);
  System.out.println("Priority of the thread after setting "+t.getPriority());
 }

}

>>>
------------------------------------------------------------------------------------------------------------

Synchronized Thread

By making a the run method of the thread synchronized then the corresponding thread is locked and it executes the other all threads and then execute this one. By using notify it release the threads.

 
thread1.java

package Threadsexample;

public class thread1 extends Thread {
 
 synchronized public void run(){
  System.out.println("thread one");
  
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  notify();
 }
 
}

thread2,java

package Threadsexample;

public class thread2 implements Runnable{

 @Override
 public void run() {
  // TODO Auto-generated method stub
  System.out.println("Thread 2");
  
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
}

mainclass.java

package Threadsexample;

public class mainclass {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Thread t=new thread1();
  Runnable r=new thread2();
  
  t.start();  
  new Thread(r).start();
  System.out.println(t.getName());
 }

}


>>>
------------------------------------------------------------------------------------------------------------

Join in Threads

About join, when I use join method on a thread then it waits for that particular thread to complete/die and then proceed with the other threads.Below example explains the same.

thread1.java

package Threadsexample;

public class thread1 extends Thread {
 
 public void run(){
  System.out.println("thread one");
  
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
}

thread2.java

package Threadsexample;

public class thread2 implements Runnable{

 @Override
 public void run() {
  // TODO Auto-generated method stub
  System.out.println("Thread 2");
  
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
}

mainclass.java

 
package Threadsexample;

public class mainclass {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Thread t=new thread1();
  Runnable r=new thread2();
  
  t.start();
  try {
   t.join();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  new Thread(r).start();
  System.out.println(t.getName());
 }

}


output :
thread one
Thread-0
Thread 2
>>>
------------------------------------------------------------------------------------------------------------

Friday, February 27, 2015

Threads

1. Thread is light weight process, independent, separate path of execution.
2. multithreading is different from multiprocessing.
3. Life cycle of thread and it is decided by JVM new,runnable,running,nonrunnable,terminated.
4. Thread can created by extending thread class or implementing runnable interface.
5. thread scheduler is a part of JVM which thread needs to be executed and depends on the preemptive and time slicing(which is the priority of the thread)
6. join is used to wait for the thread to die, in other words the thread is completed fully and then proceeds with the other thread.
7. if the method is synchronized then it locks and wait for the method to complete and then resumes.
8. wait, notify and notifyall wait method releases the lock, while notify wakesup the thread. notifyall wakes up all the thread
9. interrupt is interrupting from the sleep or wait.

thread1.java

package awesomeThreads;

public class thread1 extends Thread{
 
 
 public void run(){
  
  for(int i=0;i<3;i++){
   System.out.println("First Thread");
  }
  
  try {
   Thread.sleep(10000);
   System.out.println("First Thread in sleeping mode");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

thread2.java

package awesomeThreads;

public class thread2 implements Runnable {

 @Override
 public void run() {
  // TODO Auto-generated method stub
  System.out.println("Seccond Thread");
  
  try {
   Thread.sleep(5000);
   System.out.println("second Thread in sleeping mode");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 

}
thread3.java

package awesomeThreads;

public class thread3 extends Thread{
 public void run(){
  
  for(int i=0;i<3;i++){
   System.out.println("third Thread");
  }
  
  try {
   Thread.sleep(2000);
   System.out.println("Third Thread in sleeping mode");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

mainclass.java

package awesomeThreads;

public class mainclass {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Thread t1=new thread1();
  Runnable r2=new thread2();
  Thread t3=new thread3();
  
  t1.start();
  new Thread(r2).start();
  t3.start();
 }
}

Output:
First Thread
First Thread
First Thread
Seccond Thread
third Thread
third Thread
third Thread
Third Thread in sleeping mode
second Thread in sleeping mode
First Thread in sleeping mode

>>>
------------------------------------------------------------------------------------------------------------

Sunday, February 22, 2015

Packages

Package it is used to store your classes, avoid class name conflict and with the help of access specifier we can control the access.
we have 4 access modifier public, protected, private and no access specifier mentioned.

--public is accessed inside the class,inside the package,outside the class,outside the package and even in subclass and non subclass.
--private is accessible only inside the same class and other all places it is restricted.
--no access specifier it is accessible from the same class, subclass non subclass from the same package but not outside the package.
--protected is accessible in same class , subclass, non subclass of the same package other package subclass but not the other package non subclass.
Follow the below example with the comments


protectedclass.java
package p1;

public class protectedclass {
	
	int i =10;
	private int privatev=100;
	protected int protectedv=1000;
	public int publicv=10000;

}

subclass.java

package p1;

public class subclass extends p1.protectedclass {
		
		subclass(){
			System.out.println("access default variable "+i);
			//System.out.println("access to private variable "+privatev);//private cannot be accessed outside the class
			System.out.println("access to protected variable "+protectedv);
			System.out.println("acces to public variable "+publicv);
		}
}

nonsubclass.java

package p1;

public class nonsubclass {
	nonsubclass(){
		protectedclass p=new protectedclass();
		System.out.println("access default variable "+p.i);
		//System.out.println("access to private variable "+p.privatev);//private cannot be accessed outside the class
		System.out.println("access to protected variable "+p.protectedv);
		System.out.println("acces to public variable "+p.publicv);
	}
}

Different package p2 protectedclass.java

package p2;

public class protectedclass extends p1.protectedclass{
	protectedclass(){
	
	//System.out.println("access default variable "+i);default access in not valid outside the package
	//System.out.println("access to private variable "+privatev);//private cannot be accessed outside the class
	System.out.println("access to protected variable "+protectedv);
	System.out.println("acces to public variable "+publicv);
	}

}

nonsubclass.java
package p2;

public class nonsubclass {
	
	nonsubclass(){
		p1.protectedclass p2=new p1.protectedclass();
		
		//System.out.println("access default variable "+p2.i);//does not work in different package
		//System.out.println("access to private variable "+privatev);//private cannot be accessed outside the class
		//System.out.println("access to protected variable "+p2.protectedv);//proctected does not work in non subclasses
		System.out.println("acces to public variable "+p2.publicv);
	}

}

>>>Final
------------------------------------------------------------------------------------------------------------

Saturday, February 21, 2015

Inheritance

Inheritance, with help of inheritance you can inherit the superclass methods,variables.
Multiple inheritance is not possible in Java instead we can acieve this with interface.
super is used to call the superclass constructor, super.methodname is used to invoke the super call methods.
method overriding - in which the method is overriden in the superclass.
method overloading - if the method signature is changed then it is overloading
final - by using the class or method final it stops inheritance.
Object class is the superclass of all classes.
Follow the below example

InterestCalculation.java
package InheritanceExample;

public class InterestCalculation {
	public int amount;
	public String category;

	InterestCalculation(String category, int amount) {
		this.category = category;
		this.amount = amount;
	}

	void interestratecalculation() {
		System.out.print("For " + this.category + " and for this amount "
				+ this.amount);
	}
}



Adult.java
package InheritanceExample;

public class Adult extends InterestCalculation {
	private int interestrate;
	Adult(String category, int amount){
		super(category,amount);
	}
	
	void interestratecalculation(){
		if(amount<=1000){
			interestrate=8;
		}else{
		  interestrate=9;
		}
		super.interestratecalculation();
		System.out.println(" The interest rate is "+interestrate);
	}

}




Senior.java

package InheritanceExample;

public class Senior extends InterestCalculation {
	private int interestrate;
	Senior(String category, int amount){
		super(category,amount);
	}

	void interestratecalculation(){
		   interestrate=10;
			super.interestratecalculation();
			System.out.println(" The interest rate is "+interestrate);
		}
}



mainClass.java
package InheritanceExample;

public class MainClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Adult adultobj=new Adult("adult",1000);
		Adult adultobj1=new Adult("adult",1001);
		Senior seniorobj=new Senior("senior",1000);
		
		adultobj.interestratecalculation();
		adultobj1.interestratecalculation();
		seniorobj.interestratecalculation();

	}

}


Output:
For adult and for this amount 1000 The interest rate is 8
For adult and for this amount 1001 The interest rate is 9
For senior and for this amount 1000 The interest rate is 10
>>>
------------------------------------------------------------------------------------------------------------

Monday, February 16, 2015

Strings and String Builder

In this Section we are going to see what is Strings and String builders and different kind of operations performed on Strings. Strings are immutable that is once created it cannot be changed and the next change occurs and stored in a different object. However in string builders that is not the case Strings are mutable it can be changed. Please follow the below example for more details


package Example1;

import java.util.Arrays;

public class StringOperations {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String name="Albert Einstein";
  
  //CharAt
  System.out.println("Character at "+name.charAt(3));
  //uppercase;
  System.out.println("Uppercase "+name.toUpperCase());
  //concat
  System.out.println(name.concat("ka"));
  System.out.println(name);
  
  //equals and equalsignorecase
  if(name.equals("Albert Einstein")){
   System.out.println("its is true");
  }
  
  if(name.equalsIgnoreCase("Albert Einstein")){
   System.out.println("ignores the case ");
  }
  //string contains
  System.out.println("Contains the string " +name.contains("ber"));
  
  //index of
  System.out.println("Index of e is  "+name.indexOf("e"));
  
  //length of the string
  System.out.println("length of String is "+name.length());
  
  //Replace
  System.out.println("Repalce string "+name.replace("A", "Dr A"));
  
  
  //creation of string builder
  StringBuilder names=new StringBuilder("Charles Darwin");
  //append operation
  System.out.println("Uppercase "+names.append("ka"));
  System.out.println(names);
  
  //capacity
  System.out.println(names.capacity());
  
 }

}


output:
Character at e
Uppercase ALBERT EINSTEIN
Albert Einsteinka
Albert Einstein
its is true
ignores the case
Contains the string true
Index of e is 3
length of String is 15
Repalce string Dr Albert Einstein
Uppercase Charles Darwinka
Charles Darwinka
30

>>>Final
------------------------------------------------------------------------------------------------------------

LinkedList

The below Example explains about linked list and the associated methods.The main difference between arraylist and linkedlist is in the usage.
arraylist is better used for searching the element, while linked list is used for inserting deleting.


package Example1;

import java.util.LinkedList;

public class LInkedList {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		LinkedList linkedlistone=new LinkedList();//gerneric linkedlist
		LinkedList names=new LinkedList();//LinkedList specific to String
		
		//adding elements
		names.add("Jill");
		names.add("Jack");
		names.add("Roy");
		
		//Display elements
		
		for(String lists:names){
			System.out.println(lists);
		}
		//get a particular index
		System.out.println("Get the list as the index mentioned "+ names.get(2));
		
		//Get the first value
		System.out.println("Get the first value "+names.getFirst());
		
		//Get the last value
		System.out.println("Get the last value "+names.getLast());
		
		//copy of the linkedlist
		LinkedList newlist=new LinkedList(names);
		System.out.println("New linked list same as names "+newlist.toString());
		
		//check if a element exist
		if(newlist.contains("Jill")){
			System.out.println("Jill is present in the list");
		}
		//Check all as the othe list
		if(newlist.containsAll(names)){
			System.out.println("Both the list matches");
		}
		//index
		System.out.println("Return the index value "+newlist.indexOf("Jack"));
		
		//peek - returns the first element
		System.out.println(newlist.peek());
		
		//Poll - returns teh first element and delete it from the list
		System.out.println(newlist.poll());
		
		for(String display:newlist){
			System.out.println("This is the element in the newlist "+display.toString());
		}
		//push
		newlist.push("Jack");
		newlist.push("derek");
		
		System.out.println(newlist.toString());
		
		//clear
		newlist.clear();
		System.out.println(newlist.toString());
		
	}

}


output:
Jill
Jack
Roy
Get the list as the index mentioned Roy
Get the first value Jill
Get the last value Roy
New linked list same as names [Jill, Jack, Roy]
Jill is present in the list
Both the list matches
Return the index value 1
Jill
Jill
This is the element in the newlist Jack
This is the element in the newlist Roy
[derek, Jack, Jack, Roy]
[]

>>>Final
------------------------------------------------------------------------------------------------------------

ArrayList function

Below are the list of operations that can be performed on the arraylist.

package Example1;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayList1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		ArrayList newarray=new ArrayList();
		newarray.add("John");
		newarray.add("Kevin");
	
	
//	Iterator ite=newarray.iterator();
//		while(ite.hasNext()){
//			System.out.println(ite.next());
//		}
		
//		for(int i=0;i< newarray.size();i++){
//			System.out.println(newarray.get(i));
//		}
		newarray.remove(1);
		newarray.add(1, "Lisa");
		Boolean containsornot=newarray.contains("Lisa");
		for(String i:newarray){
			System.out.println(i);
		}
		System.out.println(containsornot);
		System.out.println(newarray.indexOf("john"));
		System.out.println(newarray.indexOf("John"));
		System.out.println(newarray.isEmpty());
		System.out.println(newarray.set(1, "kevin"));
		for(String i:newarray){
			System.out.println(i);
		}
		System.out.println(newarray.toString());
	}
}


output: Execute this program to view the result >>>
------------------------------------------------------------------------------------------------------------

ArrayList

ArrayList is a like a array in which you ca add, remove, update the list and its dynamic.Below example explains the arraylist creation, storing values and displaying them.


package Example1;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

public class Arraylist {

 public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayList newarry=new ArrayList();
		newarry.add("abc");
		newarry.add("def");
		newarry.add("xyz");
		newarry.add("232");
		newarry.add("121");
		
//		Iterator ite=newarry.iterator();
//		while(ite.hasNext()){
//			System.out.println(ite.next());
//		}
		
//		for(int i=0;i< newarry.size();i++){
//			System.out.println(newarry.get(i));
//		}
		
//		for(String i:newarry){
//			System.out.println(i);
//		}

		//newarry.remove(2);
		//newarry.removeAll(newarry);
		for(String i:newarry){
			System.out.println(i);
		}
	}

}


output:
abc
def
xyz
232
121
iterator is used to display the arraylist or you can use a for loop or enhanced for loop to display the array list. >>>
------------------------------------------------------------------------------------------------------------

Sunday, February 15, 2015

Array Functions

We have couple of arrays functions that could be handy to perform some array operations.Listed below
- Copying array
- Copying array of a particular range
- Sorting Array
- search array


package Example1;

import java.util.Arrays;

public class CopyArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int[] array1=new int[10];
		int randomnumber;
		for(int i=0;i< array1.length;i++){
			randomnumber=(int)(Math.random()*51);
			array1[i]=randomnumber;
		}
		
		for(int row:array1){
			System.out.print(" "+row+" ");
		}
		//copy array
		System.out.println();
		int[] copyarray=Arrays.copyOf(array1, 3);
		for(int row:copyarray){
			System.out.print(" "+row+" ");
		}
		//copy array in a particular range
		System.out.println();
		int[] copyarray2=Arrays.copyOfRange(array1, 2, 6);
		for(int row:copyarray2){
			System.out.print(" "+row+" ");
		}
		
		//sort the array		
		System.out.println();
		Arrays.sort(array1);
                int exist=Arrays.binarySearch(array1, 50);
		System.out.println(exist);
		System.out.println(Arrays.toString(array1));
	}

}


output :
27 20 20 31 32 21 28 27 40 46
27 20 20
20 31 32 21
-ve value [20, 20, 21, 27, 27, 28, 31, 32, 40, 46]
>>>
------------------------------------------------------------------------------------------------------------

Enhanced Forloop


package Example1;

public class enhanceforloop {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  int[] singlearray = new int[10];
  int k = 0;
  while (k <= 15) {
   System.out.print("-");
   k++;
  }
  System.out.println();

  for (int i = 0; i < singlearray.length; i++) {
   singlearray[i] = i;
  }
  for (int row : singlearray) {
   System.out.print(" " + row + " ");
  }
  System.out.println();

  k = 0;
  while (k <= 15) {
   System.out.print("-");
   k++;
  }
  System.out.println();

  char[][] multiarray = new char[10][10];

  for (int i = 0; i < multiarray.length; i++) {
   for (int j = 0; j < multiarray[i].length; j++) {
    multiarray[i][j] = '*';
   }
  }

  for (char[] row : multiarray) {
   for (char column : row) {
    System.out.print(" " + column + " ");
   }
   System.out.println();
  }
 }
}


>>>
------------------------------------------------------------------------------------------------------------

Arrays

Arrays can be of single dimension or multidimension, its a collection of similar datatypes. below example illustarte the creation of arrays.


package Example1;

import java.lang.reflect.Array;

public class CreateArray {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("single dimension array");
  int[] singlearray = new int[10];
  for (int i = 0; i < singlearray.length; i++) {
   singlearray[i] = i;
   System.out.print(" " + singlearray[i] + " ");
  }
  System.out.println();

  int k = 0;
  while (k <= 15) {
   System.out.print("-");
   k++;
  }
  System.out.println();
  
  
  System.out.println("multi dimension array");
  int[][] multiarray = new int[10][10];

  for (int i = 0; i < multiarray.length; i++) {
   for (int j = 0; j < multiarray[i].length; j++) {
    multiarray[i][j] = i;
    System.out.print("|" + multiarray[i][j] + "|");
   }
   System.out.println();
  }
 }

}


output :
single dimension array
0 1 2 3 4 5 6 7 8 9
----------------
multi dimension array
|0||0||0||0||0||0||0||0||0||0|
|1||1||1||1||1||1||1||1||1||1|
|2||2||2||2||2||2||2||2||2||2|
|3||3||3||3||3||3||3||3||3||3|
|4||4||4||4||4||4||4||4||4||4|
|5||5||5||5||5||5||5||5||5||5|
|6||6||6||6||6||6||6||6||6||6|
|7||7||7||7||7||7||7||7||7||7|
|8||8||8||8||8||8||8||8||8||8|
|9||9||9||9||9||9||9||9||9||9|
>>>
------------------------------------------------------------------------------------------------------------

Saturday, February 14, 2015

Guess the Magic letter

I have created a program which displays's a array of 10*10 and everytime you execute, it display a magic letter. Execute the program to see the Magic

package Example1;

import java.util.Arrays;

public class GuessTheStar {
 private static char design = '*';
 private static int xposition = 0;
 private static int yposition = 0;
 private static char magiccharacter='A';
 
 private static int randomnumber;

 char[][] arraycontent = new char[10][10];

 public GuessTheStar(char design) {
  this.design = design;
  
  xposition=(int)(Math.random()*10);
  yposition=(int)(Math.random()*10);
  
  randomnumber=(int)(Math.random()*24);
  magiccharacter=(char) (magiccharacter+randomnumber);
  
  
  for (int i = 0; i < arraycontent.length; i++) {
   for (int j = 0; j < arraycontent[i].length; j++) {
    if(xposition==i && yposition==j){
     System.out.print(arraycontent[i][j]=magiccharacter);
     System.out.print("\t");
    }else{
     System.out.print(arraycontent[i][j]=this.design);
     System.out.print("\t");
    }
   }
   System.out.println("");
   
  }  
  
 }

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  GuessTheStar obj=new GuessTheStar('*');
 }

}


>>>
------------------------------------------------------------------------------------------------------------

Friday, February 13, 2015

Finally

Finally is a block of code which would be executed irrespective of the exception exist or not, generally it is known as the clean up code, it is used to close the database connection if open etc.

package Example1;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ExceptionAgain {
 static Scanner scanobj=new Scanner(System.in);
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("how old are you");
  int age=checktheage();
  if(age!=0){
   System.out.println(" you are "+age+" old");
  }
 }

 public static int checktheage(){
  try{
   return scanobj.nextInt();
  }
  catch(InputMismatchException e){
   System.out.println("Do not enter whole number");
   return 0;
  }
  finally{
   System.out.println("clean up code");
  }
 }
}


>>>
------------------------------------------------------------------------------------------------------------

Exception Handling

The below example catches exception if you enter a value other than int

package Example1;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ExceptionAgain {
 static Scanner scanobj=new Scanner(System.in);
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("how old are you");
  int age=checktheage();
  if(age!=0){
   System.out.println(" you are "+age+" old");
  }
 }

 public static int checktheage(){
  try{
   return scanobj.nextInt();
  }
  catch(InputMismatchException e){
   System.out.println("Do not enter whole number");
   return 0;
  }
 }
}

- We can add multiple catch block however the most appropriate exception should be mentioned first then the least excepted exception and then general exception.
- If we want to ignore an exception then catch the exception but do not do anything inside the block example is shown below

catch(InputMismatchException e){}
- Catching multiple exception in single catch is also possible.
catch(InputMismatchException | IOException e){} >>>Finally
------------------------------------------------------------------------------------------------------------