Exception Handling (try...catch...finally)


The try...catch block is mainly use to handle exceptions in java as shown below.

First block : try

Second block : catch
Third block (optional): finally

Source: 
TestException.java


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class TestException {

    public static void main(String[] args) {
        try {
       
            Scanner scanner = new Scanner(new File("ccc"));
       
        } catch (FileNotFoundException exception) {


            exception.printStackTrace();
            System.out.println("Please contact sysadmin. 5111");


        } finally {

            //close any database or other resources, as this block will be executed irrespective of any exceptions or not in above 2 blocks
        }
   
        System.out.println("Thank you.");

    }

}



As the ccc file is not available the above program throws exception of FileNotFoundException type

File Handling


File Writer 


How to use existing Java API for writing data to external file for persistance.
Source: TestFileWriter.java


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class 
TestFileWriter {
    public static void main(String[] args) {
    try {
            FileWriter writer = new FileWriter("c:/citydata.txt", true); //set true for append mode
            BufferedWriter bufferedWriter =new BufferedWriter(writer);
            bufferedWriter.write("Tokyo");
            bufferedWriter.write(",");
            bufferedWriter.write("New York");
            bufferedWriter.write(",");
            bufferedWriter.write("Colombo");
            bufferedWriter.write(",");
            bufferedWriter.write("Korea");
            bufferedWriter.write("\n");

            bufferedWriter.flush();
            bufferedWriter.close();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output
After running above program check for creation of c:/citydata.txt with following contents


Tokyo, New York, Colombo, Korea
=================================================


File Reader 


How to use existing Java API for reading data from external file.
Source: TestFileReader.java

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;

public class 
TestFileReader {
    public static void main(String[] args) {
        File file = new File("c:/citydata.txt");
        try {
            Scanner scan = new Scanner(file);
            while (scan.hasNext()) {
                System.out.println(scan.nextLine());
            }       
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

Output
Tokyo, New York, Colombo, Korea

DataStructures : ArrayList, HashMap, Set


ArrayList



- Values could be duplicated

- Use to store multiple "elements" together, represented by single variable name

- The "elements" could be of different Data types such as int, double, Objects
- No need to specify size while declaration, size = Dynamic
- Element can be accessed using array "index"
- Array index starts from zero [0]


--------------------------------------------------------------------------------------
Ex. 1: ArrayList 

Source: TestArrayList.java
import java.util.ArrayList;

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



        ArrayList list = new ArrayList();
   
        list.add("Tokyo");
        list.add("Edogawa ku");
        list.add("Minato ku");
        list.add("Toshima ku");



        Customer cust = new Customer();
        list.add(cust); // object can be added to ArrayList
   
        System.out.println(list.get(3));
  
  }
}



Output
Toshima ku


======================================================

HashMap


- Use to store data in key and value pair 

- Key should be unique and of reference data type
- No need to specify size while declaration, size = Dynamic
---------------------------------------------------------------------------------------
Ex. 2: HashMap 

Source: TestHashMap.java
import java.util.HashMap;

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



        HashMap hash = new HashMap();
        //key and value pair (phone/name)
        hash.put("5678", "Yamada");
        hash.put("8934", "Suzuki");
        hash.put("1234", "John");
   
        System.out.println(hash.get("8934"));
    }
}




Output
Suzuki


======================================================

TreeSet



- Use to store unique values, no duplicates


- Use to store multiple "elements" together, represented by single variable name

- The "elements" could be of different Data types such as int, double, Objects
- No need to specify size while declaration, size = Dynamic
- Element can be accessed using array "index"
- Array index starts from zero [0]
----------------------------------------------------------------------------------------
Ex. 3: TreeSet 

Source: TestTreeSet.java
import java.util.TreeSet;

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

        TreeSet tset = new TreeSet();        
        tset.add(1);
        tset.add(2);
        tset.add(3);
        tset.add(3);
   
        System.out.println(tset.toString());
    
   }
}


Output
[1,2,3]

Application : Calculator (For 3 Numbers)

Requirements:
Create Calculator Application to have following functionality,
- Add 3 numbers
- Subtract 3 numbers
- Divide 3 numbers 
- Multiply 3 numbers


- Take command line input for 3 numbers
- User can enter option based on the menu as shown below,

Menu 
(1=Add, 2=Sub, 3=Div, 4=Mul )


Design:

Implementation:
[CalculatorApp.java]
import java.util.Scanner;

public class CalculatorApp {

    public static void main(String[] args) {



        //read command line arguments from the command line while running this application
        double n1 = Double.parseDouble(args[0]);  //first number
        double n2 = Double.parseDouble(args[1]);  //second number
        double n3 = Double.parseDouble(args[2]);  //third number
        

        //use to get user input for operation
        Scanner scan = new Scanner(System.in);

    
        System.out.println("Menu ");
        System.out.println("(1=Add, 2=Sub, 3=Div, 4=Mul )");

        int option = scan.nextInt();
   
        CalculatorApp appC = new CalculatorApp();

        switch (option) {

        case 1 :
            appC.add(n1, n2, n3);
            break;

        case 2 :
            appC.sub(n1, n2, n3);
            break;

        case 3 :
            appC.div(n1, n2, n3);
            break;
        case 4 :
            appC.mul(n1, n2, n3);
            break;

        default :
            System.out.println("Invalid option.");
        }
   
    } //end of main() method

    //Method to add three numbers and display results
    public void add(double n1, double n2, double n3) {
        System.out.println("Adding...");
        double result = n1 + n2 + n3;
        System.out.println(result);
    }

    
 //Method to subtract three numbers and display results    

    public void sub(double n1, double n2, double n3) {
        System.out.println("Subtracting...");
        double result = n1 - n2 - n3;
        System.out.println(result);
    }

    //Method to divide three numbers and display results  
    public void div(double n1, double n2, double n3) {
        System.out.println("Dividing...");
        double result = n1 / n2 / n3;
        System.out.println(result);
    }

   //Method to multiply three numbers and display results  
    public void mul(double n1, double n2, double n3) {
        System.out.println("Multiplying...");
        double result = n1 * n2 * n3;
        System.out.println(result);
    }

}



Testing:
=============How to Compile using java command line without Eclipse
javac CalculatorApp.java
The above command will compile CalculatorApp.java to CalculatorApp.class
=============How to Run using Command prompt (such as dos/unix/linux) 
java CalculatorApp 1 2 3
The above command will run CalculatorApp application with 3 arguments (Number1, Number2 and Number3)
=============Output: For Add option [other 3 options (Sub, Div, Mul) ]
Menu 
(1=Add, 2=Sub, 3=Div, 4=Mul )


1
Adding...
6.0

Switch Statement

Source: TestSwitch.java


import java.util.Scanner;

public class TestSwitch {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

System.out.println("Enter month number");
int monthNumber = scan.nextInt();

switch (monthNumber) {
case 1: System.out.println("JAN");
break;
case 2 : System.out.println("FEB");
break;
case 3 : System.out.println("MAR");
break;
case 4 : System.out.println("APR");
break;
default :
System.out.println("Invalid Month");
}
}
}

User Interaction (Getting Users' Input)


Source: TestUserInput.java


import java.util.Scanner;

public class TestUserInput {


public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your Name : ");
String name = scan.next();

System.out.println("Enter your marks : ");
int marks = scan.nextInt();

if (marks > 90) {
System.out.println("Hi " + name + " You got A");
} else if (marks > 70) {
System.out.println("Hi " + name + " You got B");
} else if (marks > 50) {
System.out.println("Hi " + name + " You got C");
} else {
System.out.println("Sorry Dude better luck next time");
}
}
}



Mechanism of Method Execution

When we run TestApp5 application, the JVM start the execution by calling main() method of TestApp5.

Command: 
java TestApp5

Execution Model:

Array

- Use to store multiple "elements" together, represented by single variable name
- Need to specify size while declaration, size = total number of elements
- Element can be accessed using array "index"
- Array index starts from zero [0]



======================================================
Ex. 1: Array of int (primitive data type)

Source: TestArray1.java

public class TestArray1 {

    public static void main(String[] args) {
     
        int[ ] ilist = new int [10];
        ilist[0] = 101;
        ilist[7] = 200;
     
        for(int k = 0; k < ilist.length; k++ ) {
            System.out.println(ilist[k]);
        }
    }
}

Output
101
0
0
0
0
0
0
200
0
0
======================================================
Ex. 2: Array of float (primitive data type)

Source: TestArray2.java

public class TestArray2 {


    public static void main(String[] args) {
       
        float[] ilist = new float [10]; // size
        ilist[0] = 101.50;
        ilist[7] = 200.25;
       
        for(int k = 0; k < ilist.length; k++ ) {
            System.out.println(ilist[k]);
        }
    }
}

Output
101.50
0.0
0.0
0.0
0.0
0.0
0.0
200.25
0.0
0.0
======================================================
Ex. 3: Array of String (reference data type)

Source: TestArray3.java

public class TestArray3 {

   public static void main(String[] args) {
     
   String[] weekdays = new String[7]; // size
        weekdays[0] = "Monday";
        weekdays[1] = "Tuesday";
        weekdays[2] = "Wednesday";
        weekdays[3] = "Thursday";
        weekdays[4] = "Friday";
        weekdays[5] = "Saturday";
        weekdays[6] = "Sunday";
      
        for(int k = 0; k < weekdays.length; k++ ) {
            System.out.println(weekdays[k]);
        }
    }
}

Output
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday