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

Exception

Exception highlights/handles the errors. Please find the example how to catch the exception and display so that we can take an appropriate action on the statement that is triggering this.


package Example1;

public class ExceptionExample {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  dividebyzero(2);
 }
 public static void dividebyzero(int a){
  try{
   a=a/0;
  }
  catch(Exception e){
   System.out.println(e.getMessage());
   System.out.println(e.toString());
   e.printStackTrace();
  }
 }
}

output:
/ by zero
java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
at Example1.ExceptionExample.dividebyzero(ExceptionExample.java:11)
at Example1.ExceptionExample.main(ExceptionExample.java:7)

>>>Exceptions
------------------------------------------------------------------------------------------------------------

Random Number

Random Number Generation example

package Example1;
import java.util.Scanner;

public class RandomNumber {
 static int RandomNumber;
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("The Random Number generated is "+GenerateRandom());
  Scanner obj=new Scanner(System.in);
  
  
  int guessednumber=1;
  while(guessednumber!=-1){
   System.out.println("Guess a Number between 1 to 50?");
   guessednumber=obj.nextInt();
   guessednumber=CheckRandom(guessednumber);
  }
  System.out.println("yes you guessed it is "+RandomNumber);
 }
 
 public static int GenerateRandom(){  
  RandomNumber=(int)(Math.random()*51);
  return RandomNumber;
 }
 
 public static int CheckRandom(int passedguessednumber){ 
  if(passedguessednumber==RandomNumber){
   return -1;
  }
  else{
   return passedguessednumber;
  }
 }


output:
You need to execute in order to view the result >>>Exception
------------------------------------------------------------------------------------------------------------

Pass By Value

Pass by value is explained in the below example.

package Example1;

public class PassByValue {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
   int x=10;
   display(x);//value of 10 is passed
   System.out.println("x value in the main method "+x);
 }

 public static void display(int a){
  a=a+1;
  System.out.println("x value in the display "+a);
 }
}

output:
x value in the display 11
x value in the main method 10
>>>Random Number Generation
------------------------------------------------------------------------------------------------------------

Local Variable vs Class Variable

When a variable is defined in a class it is the gloabl variable and it can be accessed from any class or method. When a variable is defined inside a method then it is the local variable.Check the below example which explains the below concepts.

package Example1;

public class LocalVsGlobal {
 static int interest=10;//global variable
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  display();
  System.out.println("inside the main method "+interest);
 }
 public static void display(){
  int interest=8;// local variable
  System.out.println("Inside the display method "+interest);
 }
}

output:
Inside the display method 8
inside the main method 10

The value of interest inside display method uses the local variable value which is 8, while the interest value inside main method uses gloabl variable and that is the reason it is different.
If we want the gloabl variable value to be updated with the local variable value then just remove the keyword int it and it affects all value in all places. >>>Pass By value
------------------------------------------------------------------------------------------------------------

Do While

Do while is another type of looping and how is it different from while loop. It executes the do part irrespective of the while condition for the first time,you can check the below example.

package Example1;

public class DoWhileExample {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int i=10;
  do{
   System.out.println(i);
  }while(i>10);
 }

}


output:
10

In the above example the do block is executed irrespective of whether the while condition is true or false. if the same scenario was used for while loops then nothing is printed in the console reason the while condition is false. >>>Local Variable vs Class Variable
------------------------------------------------------------------------------------------------------------

For Loop

A simple For loop example which illustrates 6 multiples and this can be extended for any multiples.


package Example1;

public class ForLoopExample {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  System.out.println("Display's 6 multiples");
  for(int i=6;i<=60;i+=6){
   if(i%6==0){
    System.out.println(i);
   }
  }
 }

}


output:
Display's 6 multiples
6
12
18
24
30
36
42
48
54
60

>>>do While
------------------------------------------------------------------------------------------------------------

While Loop With Break and Continue

This section exlains about While loop with break and continue, the below example explains how the flow is affected with the usage of break/continue.


package Example1;

public class WhileLoopWithBreak {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int j=0;
  while(j<=10){
   System.out.println(j);
   j++;
   if(j==5){
    System.out.println("its five");
    if(j%5==0){
     break;
    }    
   }
  }
 }
}

output:
0
1
2
3
4
its five



package Example1;

public class WhileLoopWithContinue {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int j=0;
  while(j<=10){
   System.out.println(j);
   j++;
   if(j==5){
    System.out.println("its five");
    if(j%5==0){
     continue;
    }    
   }
  }
 }
}

output:
0
1
2
3
4
its five
5
6
7
8
9
10

When break is used it total comes out of all the loops while continue break the existing loop and continue from the beginning of the loop. >>>ForLoop
------------------------------------------------------------------------------------------------------------

Thursday, February 12, 2015

Switch

Switch is used if you know the number of options.Please follow the below example


package Example1;

public class SwitchClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String grade="B";
		switch (grade) {
		case "A":
			System.out.println("Excellent");
			break;
		case "b":
		case "B":
			System.out.println("Good");
			break;
		case "C":
			System.out.println("Average");
			break;
		default:
			System.out.println("Better luck next time");
			break;
		}
	}

}


Output:
Good

Please note, It is case sensitive and there is a difference between 'b' and 'B' and you can see that in the example.
Usage of Break ensures it comes out of the loop as soon as the condition is true else it keeps checking all the case block. If no condition matches then it execute the default block. >>>
------------------------------------------------------------------------------------------------------------

Ternary Operator

Ternary operations contains a condition and execute the true or false apart accordingly it also possible to assign it to a variable.


package Example1;

public class TernaryOperator {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int x=10;
		int y=20;
		String result=(x
output:
x is less than y
>>>Switch
------------------------------------------------------------------------------------------------------------

Logical Operator

Logical operators are used to perform all the logical operations like and, or not and XOR. Please follow the below example for more details.

package Example1;

public class LogicalOperator {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  if(true && true){
   System.out.println("the value is true");
  }
  if(false || true){
   System.out.println("the value is false");
  }
  if(!(false)){
   System.out.println("the value is true");
  }
  if(true ^ false){
   System.out.println("the value is false");
  }
 }

}


output: the value is true
the value is false
the value is true
the value is false
>>>Ternary
------------------------------------------------------------------------------------------------------------

Relational Operator

This section discuss about Relational operations and you can see the below example with all the kinds of relational operations.


package Example1;

public class RelationalOperator {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int randomnumber=(int)(Math.random()*49);
  
  if(randomnumber<25){
   System.out.println("The number is less than 25");
  }else if(randomnumber > 40){
   System.out.println("The number is greater than 40");
  }else if(randomnumber == 30){
   System.out.println("The number is equal to 30");
  }else if(randomnumber != 10){
   System.out.println("The number is not equal to 10");
  }else if(randomnumber <= 14){
   System.out.println("The number is less than equal to 14");
  }else if(randomnumber >= 14){
   System.out.println("The number is greater than equal to 14");
  }else{
   System.out.println("nothing matched");
  }
  System.out.println("The random number is "+randomnumber);
 }

}


output: Is not predictable since it uses random value
>>>Logical Operator
------------------------------------------------------------------------------------------------------------

Math Function

We have couple of Math functions defined to make math operations more ease. I have listed couple of them in the below example.

package Example1;

public class MathOperator2 {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  float x=-10.4f;
  
  //absolute
  System.out.println(Math.abs(x));
  //max and min value
  System.out.println(Math.max(10,100));
  System.out.println(Math.min(10,100));
  //ceil
  System.out.println((int)Math.ceil(100.34));
  //floor
  System.out.println((int)Math.floor(100.34));
  //round
  System.out.println((int)Math.round(100.34));
  //random number
  System.out.println((int)(Math.random()*10));//10 helps you generate number between 1 to 9
 }

}


output:
10.4
100
10
101
100
100
6

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

Math Operators- Increment and Decrement

Increment/Decrement operators are used to increase a decrease the value, well the catch is, is it post or pre increment.
++i is different from i++ and similarly --i is different from i--
lets watch this with an example

package Example1;

public class IncrementOrDecrement {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int x=10;
  System.out.println(x++);first display x value and then increment so now x is 11
  System.out.println(++x);first it increments which would be 12 and then display
 }

}

output:
10
12

package Example1;

public class IncrementOrDecrement {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int x=10;
  System.out.println(x--);first display x value and then decrement so now x is 9
  System.out.println(--x);first it decrements which would be 8 and then display
 }

}

output:
10
8
>>>Math functions
------------------------------------------------------------------------------------------------------------

Math Operators

We have a set of math operators that are used and the below example explains each and every operations.

package Example1;
import java.util.Scanner;
public class MathOperator {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Scanner scanobj=new Scanner(System.in);
  System.out.println("Enter a number");
  int result=scanobj.nextInt();
  
  //Addition
  int additionvalue=result+result;
  System.out.println(result+"+"+result+"="+additionvalue);
  
  //subtraction
  int subvalue=result-result;
  System.out.println(result+"-"+result+"="+subvalue);
  
  //multiplication
  int multiplicationvalue=result*result;
  System.out.println(result+"*"+result+"="+multiplicationvalue);
  
  //division
  int divisionvalue=result/result;
  System.out.println(result+"/"+result+"="+divisionvalue);
  
  //Modules
  int modulesvalue=result%2;
  System.out.println(result+"%2="+modulesvalue);
 }

}


output:
Enter a number
99
99+99=198
99-99=0
99*99=9801
99/99=1
99%2=1

>>>Math operators
------------------------------------------------------------------------------------------------------------