[go: up one dir, main page]

0% found this document useful (0 votes)
206 views424 pages

Cat 2 STS

This document discusses exception handling in Java. It defines what exceptions are and common reasons they occur, like user errors, programmer errors, and physical errors. It provides examples of checked and unchecked exceptions and how to handle them using try, catch, and throw keywords. Finally, it discusses exception hierarchies in Java and the internal working of try-catch blocks.

Uploaded by

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

Cat 2 STS

This document discusses exception handling in Java. It defines what exceptions are and common reasons they occur, like user errors, programmer errors, and physical errors. It provides examples of checked and unchecked exceptions and how to handle them using try, catch, and throw keywords. Finally, it discusses exception hierarchies in Java and the internal working of try-catch blocks.

Uploaded by

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

Exception Handling

What is Exception?
Exception Handling
An exception can occur for following
reasons.

•User error

•Programmer error

•Physical error
1 import java.util.*;
2 public class MyClass
3 {
4 public static void main(String args[])
5 {
6 int x=10;
7 int y=0;
8 int z=x/y;
9 System.out.println(z);
10 }
11 }
12
13
14
15
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero at
MyClass.main(MyClass.java:6)
1 import java.io.*;
2 public class Main {
3 public static void main(String[] args){
4 System.out.println("First line");
5 System.out.println("Second line");
6 int[] myIntArray = new int[]{1, 2, 3};
7 print(myIntArray);
8 System.out.println("Third line");
9 }
10 public static void print(int[] arr) {
11 System.out.println(arr[3]);
12 System.out.println("Fourth element successfully displayed!");
13 }
14 }
15
Output
First line
Second line
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Main.print(Main.java:11)
at Main.main(Main.java:7)
Hierarchy of Java Exception classes
Exception IOException

SQLException

Throwable ClassNot
FoundException

RuntimeException

Error
Types of Exception
•Checked Exception
•Unchecked Exception
1 //Example for Checked exception
2 import java.io.FileInputStream;
3 public class Main {
4 public static void main(String[] args) {
5 FileInputStream fis = null;
6 fis = new FileInputStream(“D:/myfile.txt");
7 int k;
8 while(( k = fis.read() ) != -1)
9 {
10 System.out.print((char)k);
11 }
12 fis.close();
13 }
14 }
15
Output
Exception in thread "main" java.lang.Error: Unresolved compilation
problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
1 //Example for Unchecked exception
2 import java.io.*;
3 public class Main {
4 public static void main(String[] args){
5 int[] arr = new int[]{7, 11, 30, 63};
6 System.out.println(arr[5]);
7 }
8 }
9
10
11
12
13
14
15
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Main.main(Main.java:5)
Exception Handling
Exception Handling?

It is the process of responding to the


occurrence during computation of
exceptions.
Exceptional Handling Keywords
•try
•catch
•finally
•throw
•throws
1 import java.util.*; 1 import java.util.*;
2 public class MyClass 2 public class MyClass
3 { 3 {
4 public static void main(String 4 public static void main(String
5 args[]) 5 args[])
6 { 6 {
7 int x=10; 7 int x=10;
8 int y=0; 8 int y=0;
9 int z=x/y; 9 try
10 System.out.println(z); 10 {
11 } 11 int z=x/y;
12 } 12 }
13 13 catch(Exception e)
14 14 {
15 15 System.out.print(e);
16 16 }
17 17 }
18 18 }
19 19
20 20
21 21
22 22
1 import java.util.*; comment/pseudo code/output
2 public class MyClass Output:
3 { java.lang.ArithmeticException: /
4 public static void main(String by zero
5 args[])
6 {
7 int x=10;
8 int y=0; Syntax:
9 try try
10 { {
11 int z=x/y; // Protected code
12 } }
13 catch(Exception e) catch (ExceptionName e1)
14 { {
15 System.out.print(e); // Catch block
16 } }
17 }
18 }
19
20
21
22
1 import java.io.*;
2 public class Main {
3 public static void main(String[] args){
4 System.out.println("First line");
5 System.out.println("Second line");
6 try{
7 int[] myIntArray = new int[]{1, 2, 3};
8 print(myIntArray);
9 }
10 catch (ArrayIndexOutOfBoundsException e){
11 System.out.println("The array doesn't have fourth element!");
12 }
13 System.out.println("Third line");
14 }
15 public static void print(int[] arr) {
16 System.out.println(arr[3]);
17 }
18 }
19
20
21
22
OUTPUT

First line
Second line
The array doesn't have fourth element!
Third line
Internal Working of try-catch Block
System.out.print(arr[3]) Exception object
An object of
exception class is
thrown
Is
Handled?

no yes
JVM
• Prints out exception rest of code
Description is executed
• Prints stack trace
• Terminates the
program
1 //Predict the Output
2 import java.util.*;
3 public class MyClass
4 {
5 public static void main(String args[])
6 {
7 MyClass ob = new MyClass();
8 try
9 {
10 ob.meth1();
11 }
12 catch(ArithmeticException e)
13 {
14 System.out.println("ArithmaticException thrown by meth1()
15 method is caught in main() method");
16 }
17 }
18
19
20
21
22
1 public void meth1()
2 {
3 try
4 {
5 System.out.println(100/0);
6 }
7 catch(NullPointerException nullExp)
8 {
9 System.out.println("We have an Exception - "+nullExp);
10 }
11 System.out.println("Outside try-catch block");
12 }
13 }
14
15
16
17
18
19
20
21
22
1 import java.util.*;
2 public class MyClass {
3 public static void main(String[] args) {
4 try{
5 int arr[]=new int[5];
6 arr[7]=100/0;
7 }
8 catch(ArithmeticException e)
9 {
10 System.out.println("Arithmetic Exception occurs");
11 }
12 catch(ArrayIndexOutOfBoundsException e)
13 {
14 System.out.println("ArrayIndexOutOfBounds Exception occurs");
15 }
16 catch(Exception e)
17 {
18 System.out.println("Parent Exception occurs");
19 }
20 System.out.println("rest of the code");
21 }
22 }
1 //Predict the Output
2 import java.util.*;
3 public class MyClass
4 {
5 public static void main(String[] args)
6 {
7 String[] s = {"Hello", "423", null, "Hi"};
8 for (int i = 0; i < 5; i++)
9 {
10 try
11 {
12 int a = s[i].length() + Integer.parseInt(s[i]);
13 }
14 catch(NumberFormatException ex)
15 {
16 System.out.println("NumberFormatException");
17 }
18
19
20
21
22
1 catch (ArrayIndexOutOfBoundsException ex)
2 {
3 System.out.println("ArrayIndexOutOfBoundsException");
4 }
5 catch (NullPointerException ex)
6 {
7 System.out.println("NullPointerException");
8 }
9 System.out.println("After catch, this statement will be
10 executed");
11 }
12 }
13 }
14
15
16
17
18
19
20
21
22
1 // Pipe(|) operator
2 import java.util.*;
3 public class Main
4 {
5 public static void main(String[] args)
6 {
7 String[] s = {"abc", "123", null, "xyz"};
8 for (int i = 0; i < 5; i++)
9 {
10 try
11 {
12 int a = s[i].length() + Integer.parseInt(s[i]);
13 }
14 catch(NumberFormatException | NullPointerException |
15 ArrayIndexOutOfBoundsException ex)
16 {
17 System.out.println("Handles above mentioned three
18 Exception");
19 }
20 }
21 }
22 }
1 //Predict the output
2 import java.util.*;
3 public class Main
4 {
5 public static void main(String[] args)
6 {
7 try
8 {
9 int i = Integer.parseInt("Thor");
10 }
11 catch(Exception ex)
12 {
13 System.out.println("This block handles all exception types");
14 }
15 catch(NumberFormatException ex)
16 {
17 System.out.print("This block handles NumberFormatException");
18 }
19 }
20 }
21
22
1 //Predict the OUtput
2 import java.util.*;
3 public class Main
4 {
5 public static void main(String[] args)
6 {
7 String[] str = {null, "Marvel"};
8 for (int i = 0; i < str.length; i++)
9 {
10 try
11 {
12 int a = str[i].length();
13 try
14 {
15 a = Integer.parseInt(str[i]);
16 }
17 catch (NumberFormatException ex)
18 {
19 System.out.println("NumberFormatException");
20 }
21 }
22
1 catch(NullPointerException ex)
2 {
3 System.out.println("NullPointerException");
4 }
5 }
6 }
7 }
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1 //Syntax for finally block Description
2
3 try { It contains all the crucial
4 //Statements that may cause an statements that must be executed
5 exception whether exception occurs or not.
6 }
7 catch {
8 //Handling exception
9 }
10 finally {
11 //Statements to be executed
12 }
13
14
15
16
17
18
19
20
21
22
1 public class MyClass{
2 public static void main(String args[]){
3 try{
4 int data = 30/3;
5 System.out.println(data);
6 }
7 catch(NullPointerException e)
8 {
9 System.out.println(e);
10 }
11 finally
12 {
13 System.out.println("finally block is always executed");
14 }
15 }
16 }
17
18
19
20
21
22
1 public class MyClass
2 {
3 public static void main(String args[]) {
4 try{
5 int num=121/0;
6 System.out.println(num);
7 }
8 catch(ArithmeticException e){
9 System.out.println("Number should not be divided by zero");
10 }
11 finally{
12 System.out.println("This is finally block");
13 }
14 System.out.println("Out of try-catch-finally");
15 }
16 }
17
18
19
20
21
22
1 public class MyClass
2 {
3 public static void main(String args[])
4 {
5 System.out.println(MyClass.myMethod());
6 }
7 public static int myMethod()
8 {
9 try
10 {
11 return 0;
12 }
13 finally
14 {
15 System.out.println("This is Finally block");
16 System.out.println("Finally block ran even after return
17 statement");
18 }
19 }
20 }
21
22
1 public class MyClass
2 {
3 public static void main(String args[])
4 {
5 System.out.println(MyClass.myMethod());
6 }
7 public static int myMethod()
8 {
9 try
10 {
11 return 0;
12 }
13 finally
14 {
15 System.out.println("This is Finally block");
16 System.out.println("Finally block ran even after return
17 statement");
18 }
19 }
20 }
21
22
Cases when the finally block doesn’t
execute
• The death of a Thread.
• Using of the System. exit() method.
• Due to an exception arising in the finally block.
1 public class MyClass{
2 public static void main(String args[])
3 {
4 System.out.println(MyClass.myMethod());
5 }
6 public static int myMethod(){
7 try {
8 int x = 63;
9 int y = 9;
10 int z=x/y;
11 System.out.println("Inside try block");
12 System.exit(0);
13 }
14 catch (Exception exp){
15 System.out.println(exp);
16 }
17 finally{
18 System.out.println("Java finally block");
19 return 0;
20 }
21 }
22 }
1 public class MyClass{
2 public static void main(String args[])
3 {
4 System.out.println(MyClass.myMethod());
5 }
6 public static int myMethod(){
7 try {
8 int x = 63;
9 int y = 0;
10 int z=x/y;
11 System.out.println("Inside try block");
12 System.exit(0);
13 }
14 catch (Exception exp){
15 System.out.println(exp);
16 }
17 finally{
18 System.out.println("Java finally block");
19 return 0;
20 }
21 }
22 }
1 //Syntax for throw block Description
2
3 The Java throw keyword is used
4 throw new exception_class("error message"); to explicitly throw an
5 exception.
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1 public class MyClass
2 {
3 public static void validate(int age)
4 {
5 if(age<21 || age>27)
6 throw new ArithmeticException("not eligible");
7 else
8 System.out.println("Eligible to attend Military Selection ");
9 }
10 public static void main(String args[])
11 {
12 validate(30);
13 System.out.println("rest of the code...");
14 }
15 }
16
17
18
19
20
21
22
OUTPUT

Exception in thread "main" java.lang.ArithmeticException: not eligible


at MyClass.validate(MyClass.java:6)
at MyClass.main(MyClass.java:12)
1 public class MyClass
2 {
3 public static void validate(int age)
4 {
5 if(age<21 || age>27)
6 throw new ArithmeticException("not eligible");
7 else
8 System.out.println("Eligible to attend Military Selection ");
9 }
10 public static void main(String args[])
11 {
12 try
13 {
14 validate(30);
15 }
16 catch(ArithmeticException e)
17 {
18 System.out.println(e);
19 }
20 System.out.println("rest of the code...");
21 }
22 }
OUTPUT

java.lang.ArithmeticException: not eligible


rest of the code...
1 public class MyClass
2 {
3 public static void validate(int age)
4 {
5 if(age<21 || age>27)
6 throw new ArithmeticException("not eligible");
7 else
8 System.out.println("Eligible to attend Military Selection ");
9 }
10 public static void main(String args[])
11 {
12 try
13 {
14 validate(21);
15 }
16 catch(ArithmeticException e)
17 {
18 System.out.println(e);
19 }
20 System.out.println("rest of the code...");
21 }
22 }
OUTPUT

Eligible to attend Military Selection


rest of the code...
1 //Syntax for throw block Description
2
3 The Java throw keyword is used
4 return_type method_name() throws to explicitly throw an
5 exception_class_name exception.
6 {
7 //method code
8 }
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1 import java.io.BufferedReader;
2 import java.io.FileNotFoundException;
3 import java.io.FileReader;
4 public class Main {
5 public static void main(String[] args) {
6 Read r = new Read();
7 try {
8 r.read();
9 }
10 catch (Exception e) {
11 System.out.print(e);
12 }
13 }
14 }
15 public class Read {
16 void read() throws FileNotFoundException
17 {
18 BufferedReader bufferedReader = new BufferedReader(new
19 FileReader("F://file.txt"));
20 }
21 }
22
OUTPUT

java.io.FileNotFoundException: F:\file.txt (The system cannot find the


file specified)
1 import java.io.*;
2 class MyMethod {
3 void myMethod(int num)throws IOException, ClassNotFoundException{
4 if(num==1)
5 throw new IOException("IOException Occurred");
6 else
7 throw new ClassNotFoundException("ClassNotFoundException");
8 }
9 }
10 public class MyClass{
11 public static void main(String args[]){
12 try{
13 MyMethod obj=new MyMethod();
14 obj.myMethod(1);
15 }
16 catch(Exception ex){
17 System.out.println(ex);
18 }
19 }
20 }
21
22
OUTPUT

java.io.FileNotFoundException: F:\file.txt (The system cannot find the


file specified)
Throw vs. Throws
throw throws

1. Used to explicitly throw an exception 1. Used to declare an exception

2. Checked exceptions cannot be propagated 2. Checked exceptions can be


using throw only propagated
3. Followed by an instance 3. Followed by a class

4. Used within a method 4. Used with a method signature

5. Cannot throw multiple exceptions 5. Can declare multiple exceptions


Programming
Question 1
Write a program to split the string based on /(slash) symbol in a string.
Perform exception handling and also include finally block which will print
"Inside finally block".

Get a string from the user.

If the length of the string is > 2 then call user defined function splitString()
and print the split string along with index.

Else print the NullPointerException.


Question 1
Sample Input: Sample Output:
Happy/coding/Java Splitted string at index 0 is : Happy
Splitted string at index 1 is : coding
Splitted string at index 2 is : Java
Inside finally block
1 import java.util.*;
2 public class Main
3 {
4 static void splitString(String text)
5 {
6 try
7 {
8 String[] splittedString =text.split("/");
9 for(int i = 0; i < splittedString.length; i++)
10 {
11 System.out.println("Splitted string at index "+i+" is :
12 "+splittedString[i]);
13 }
14 }
15 catch(Exception e)
16 {
17 System.out.println("Exception : "+e.toString());
18 }
19 finally{
20 System.out.println("Inside finally block");
21 }
22 }
1 public static void main(String args[])
2 {
3 Scanner scanner = new Scanner(System.in);
4 String text = scanner.nextLine();
5 if(text.length()>2)
6 {
7 splitString(text);
8 }
9 else
10 {
11 splitString(null);
12 }
13 }
14 }
15
16
17
18
19
20
21
22
Question 2
You are required to compute the power of a number by implementing a
calculator. Create a class MyCalculator which consists of a single method
long power(int, int). This method takes two integers, n and p, as parameters
and finds np. If either n or p is negative, then the method must throw an
exception which says “n or p should not be negative.". Also, if both n and p
are zero, then the method must throw an exception which says “n and p
should not be zero."

For example, -4 and -5 would result in java.lang.Exception: n or p should not


be negative

Complete the function power in class MyCalculator and return the


appropriate result after the power operation or an appropriate exception as
detailed above.
Question 2
Sample Input: Sample Output:
35 243
24 16
00 java.lang.Exception: n and p should
-1 -2 not be zero.
-1 3 java.lang.Exception: n or p should
not be negative.
java.lang.Exception: n or p should
not be negative.
1 import java.util.Scanner;
2 class MyCalculator {
3 public static int power(int n,int p) throws Exception
4 {
5 if(n<0 || p<0)
6 {
7 throw new Exception ("n or p should not be negative.");
8 }
9 else if(n==0 && p==0)
10 {
11 throw new Exception ("n and p should not be zero.");
12 }
13 else
14 {
15 return((int)Math.pow(n,p));
16 }
17 }
18 }
19
20
21
22
1 public class Solution {
2 public static final MyCalculator my_calculator = new MyCalculator();
3 public static final Scanner in = new Scanner(System.in);
4 public static void main(String[] args) {
5 while (in .hasNextInt()) {
6 int n = in .nextInt();
7 int p = in .nextInt();
8
9 try {
10 System.out.println(my_calculator.power(n, p));
11 } catch (Exception e) {
12 System.out.println(e);
13 }
14 }
15 }
16 }
17
18
19
20
21
22
MCQ
1 // Predict the output
2 public class Test{
3 public static void main(String args[]){
4 try{
5 int i;
6 return;
7 }
8 catch(Exception e){
9 System.out.print("CatchBlock");
10 }
11 finally{
12 System.out.println("FinallyBlock");
13 }
14 }
15 }
16
17
18
19
20
21
22
Question 1
A) CatchBlock

B) CatchBlock FinallyBlock

C) FinallyBlock

D) No Output
1 // Predict the output
2 class Bike{
3 public void petrol() {}
4 }
5 public class Test{
6 public static void main(String args[]){
7 Bike fz = null;
8 try{
9 fz.petrol();
10 }
11 catch(NullPointerException e){
12 System.out.print("There is a NullPointerException. ");
13 }
14 catch(Exception e){
15 System.out.print("There is an Exception. ");
16 }
17 System.out.print("Everything went fine. ");
18 }
19 }
20
21
22
Question 2
A) There is a NullPointerException. Everything went fine.

B) There is a NullPointerException.

C) There is a NullPointerException. There is an Exception.

D) This code will not compile, because in Java there are no pointers.
1 // Predict the output
2 public class MyClass{
3 public static void main(String args[]){
4 try{
5 String arr[] = new String[10];
6 arr = null;
7 arr[0] = "one";
8 System.out.print(arr[0]);
9 }
10 catch(Exception ex)
11 {
12 System.out.print("exception");
13 }
14 catch(NullPointerException nex)
15 {
16 System.out.print("null pointer exception");
17 }
18 }
19 }
20
21
22
Question 3
A) "one" is printed.

B) "null pointer exception" is printed.

C) Compilation fails saying NullPointerException has already been caught.

D) "exception" is printed.
1 // Predict the output
2 import java.lang.Exception;
3 public class MyClass{
4 void m() throws Exception {
5 throw new java.io.IOException("Error");
6 }
7 void n() {
8 m();
9 }
10 void p() {
11 try {
12 n();
13 } catch (Exception e) {
14 System.out.println("Exception Handled");
15 }
16 }
17 public static void main(String args[]){
18 MyClass obj = new MyClass();
19 obj.p();
20 System.out.println("Normal Flow");
21 }
22 }
Question 4
A) Error

B) Error
Exception Handled
Normal Flow
C) Compilation Error

D) No Output
1 // Predict the output
2 public class MyClass {
3 public static void main(String[] args) {
4 for (int i = 0; i < 3; i++)
5 {
6 try
7 {
8 execute(i);
9
10 }
11 catch (Exception e) {
12 }
13 System.out.print("-");
14 }
15 }
16
17
18
19
20
21
22
1 public static void execute(int i) {
2 p('S');
3 try {
4 p('H');
5 t(i == 1);
6 try{
7 p('A');
8 t(i == 3);
9 }
10 finally {
11 p('R');
12 }
13 }
14 catch (Exception e) {
15 p('K');
16 t(i == 3);
17 }
18 }
19
20
21
22
1 public static void p(char c)
2 {
3 System.out.print(c);
4 }
5 public static void t(boolean thrw)
6 {
7 if (thrw)throw new RuntimeException();
8 }
9 }
10
11
12
13
14
15
16
17
18
19
20
21
22
Question 5
A) SHARK-SH-SHK-

B) SHAR-SHK-SHAR-

C) Compilation Error

D) SHARK-SHARK-SHARK-
THANK YOU
Creating own Exception
• User Defined Exception or custom exception is creating your own
exception class and throws that exception using ‘throw’ keyword.

• This can be done by extending the class Exception.


Need for own Exception
• Business logic exceptions –
Exceptions that are specific to the business logic and workflow.

These help the application users or the developers understand


what the exact problem is.

• To catch and provide specific treatment to a subset of existing Java


exceptions
Rules for creating own Exception
• All exceptions must be a child of Throwable.

• If you want to write a checked exception that is automatically enforced by


the Handle or Declare Rule, you need to extend the Exception class.

• If you want to write a runtime exception, you need to extend the


RuntimeException class.
1 import java.util.Scanner;
2 class InvalidbloodDonateException extends Exception
3 {
4 InvalidbloodDonateException(String s){
5 super(s);
6 }
7 }
8 public class MyClass
9 {
10 static void validate(int age,int weight)throws
11 InvalidbloodDonateException
12 {
13 if(age<18 && weight <55)
14 throw new InvalidbloodDonateException("Not Eligible");
15 else
16 System.out.println("Can Donate Blood");
17 }
18
19
20
21
22
1 public static void main(String args[])
2 {
3 Scanner sc = new Scanner(System.in);
4 int age = sc.nextInt();
5 int weight = sc.nextInt();
6 try
7 {
8 validate(age, weight);
9 }
10 catch(Exception m)
11 {
12 System.out.println("Exception occured: "+m);
13 }
14 System.out.println("rest of the code...");
15 }
16 }
17
18
19
20
21
22
OUTPUT

Exception occured: InvalidAgeException: Invalid Input


rest of the code...
1 class InvalidAgeException extends Exception{
2 InvalidAgeException(String s){
3 super(s);
4 }
5 }
6 public class MyClass{
7 static void validate(int age)throws InvalidAgeException{
8 if(age<18)
9 throw new InvalidAgeException("Invalid Input");
10 else
11 System.out.println("Right to vote");
12 }
13 public static void main(String args[]){
14 try{
15 validate(14);
16 }
17 catch(Exception m){
18 System.out.println("Exception occured: "+m);
19 }
20 System.out.println("rest of the code...");
21 }
22 }
OUTPUT

Exception occured: InvalidAgeException: Invalid Input


rest of the code...
Types
• Checked custom Exception
• Unchecked custom Exception
1 //Checked Custom Exception
2 import java.util.*;
3 class NamenotFoundException extends Exception
4 {
5 NamenotFoundException(String message)
6 {
7 super(message);
8 }
9 }
10 public class Main {
11 public static void main(String args[]) {
12 Scanner sc = new Scanner(System.in);
13 String name = sc.nextLine();
14 try
15 {
16 customername(name);
17 }
18 catch(Exception e)
19 {
20 System.out.print(e);
21 }
22 }
1 static void customername(String name)throws NamenotFoundException
2 {
3 if(name.isEmpty())
4 {
5 throw new NamenotFoundException("Name id Empty");
6 }
7 else
8 {
9 System.out.print("Hi "+ name + ", Welcome to our store");
10 }
11 }
12 }
13
14
15
16
17
18
19
20
21
22
OUTPUT

NamenotFoundException: Name id Empty


1 //Unchecked Custom Exception
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.List;
6 class ListTooLargeException extends RuntimeException
7 {
8 ListTooLargeException(String message)
9 {
10 super(message);
11 }
12 }
13 public class MyClass
14 {
15 public void analyze(List<String> data)
16 {
17 if (data.size() > 50)
18 {
19 throw new ListTooLargeException("List can't exceed 50 items!");
20 }
21 }
22
1 public static void main(String[] args) {
2 MyClass obj = new MyClass();
3 List<String> data = new ArrayList<>(Collections.nCopies(100,
4 "Customer Details"));
5 obj.analyze(data);
6 }
7 }
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

NamenotFoundException: Name id Empty


Rethrowing an Exception Wrapped
Inside a Custom Exception
catching of a built-in exception and re-throwing it via a custom exception

public Exception(String message, Throwable cause)


1 //Rethrowing an Exception Wrapped inside a custom Exception
2
3 import java.util.Scanner;
4 class InvalidCurrencyDataException extends RuntimeException
5 {
6 public InvalidCurrencyDataException(String message, Throwable cause)
7 {
8 super(message, cause);
9 }
10 }
11
12
13
14
15
16
17
18
19
20
21
22
1 class CurrencyConvertor
2 {
3 public void convertDollarsToRupees(String value)
4 {
5 try {
6 int x = Integer.parseInt(value);
7 System.out.print(x*72);
8 }
9 catch (NumberFormatException e)
10 {
11 throw new InvalidCurrencyDataException("Invalid data", e);
12 }
13 }
14 }
15 public class Main {
16 public static void main(String[] args) {
17 Scanner sc = new Scanner(System.in);
18 CurrencyConvertor money = new CurrencyConvertor();
19 money.convertDollarsToRupees(sc.next());
20 }
21 }
22
OUTPUT

Exception in thread "main" InvalidCurrencyDataException: Invalid data


at CurrencyConvertor.convertDollarsToRupees(Main.java:15)
at Main.main(Main.java:24)
Caused by: java.lang.NumberFormatException: For input string: "hello"
at
java.lang.NumberFormatException.forInputString(NumberFormatException.jav
a:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at CurrencyConvertor.convertDollarsToRupees(Main.java:11)
... 1 more
Programming
Question 1
Create your own exception called InvalidDirectionException it should
display an message called “You are going in wrong direction”. Your code
should get two input’s which is HouseDirection and GpsLocation.

If both are equal “You are going in correct direction”.


If both are not equal InvalidDirectionException is Thrown “You are going in
wrong direction”.
Question 1
Sample Input1: Sample Output1:
North You are going in correct direction
North

Sample Input2: Sample Output2:


North InvalidDirectionException: You are
south going in wrong direction
1 import java.util.Scanner;
2 class InvalidDirectionException extends Exception
3 {
4 public InvalidDirectionException(String message)
5 {
6 super(message);
7 }
8 }
9 class Map
10 {
11 public void CheckDirection(String HouseDirection, String GpsLocation) throws
12 InvalidDirectionException
13 {
14 if(HouseDirection.equals(GpsLocation))
15 {
16 System.out.print("You are going in correct direction");
17 }
18 else
19 throw new InvalidDirectionException("You are going in wrong direction");
20 }
21 }
22
1 public class Main
2 {
3 public static void main(String[] args)
4 {
5 Scanner sc = new Scanner(System.in);
6 String HouseDirection = sc.next();
7 String GpsLocation = sc.next();
8 Map map = new Map();
9 try
10 {
11 map.CheckDirection(HouseDirection, GpsLocation);
12 }
13 catch(Exception e)
14 {
15 System.out.print(e);
16 }
17 }
18 }
19
20
21
22
Question 2
Create your own exception called CheckUserMailException it should
display an message called “Email Already Registered”. Your code should get
two input from the user which are list of valid mail id’s and mail id which
user want to create.

If the mail entered is doesn’t exist on the list of valid mail id’s, then the
output is “New user”.

If the mail entered is exist on the list of valid mail id’s, an exception is
thrown called CheckUserMailException.
Question 2
Sample Input: Sample Output:
ironman@gmail.com CheckUserMailException: Email
godofthunder@gmail.com Already Registered
captainamerica@gmail.com
nicolasfury@gmail.com
hulk@gmail.com

godofthunder@gmail.com
1 import java.util.*;
2 class CheckUserMailException extends Exception
3 {
4 public CheckUserMailException(String message)
5 {
6 super(message);
7 }
8 }
9 class RegistrationService
10 {
11 public void validateEmail(List registeredEmails,String email) throws CheckUserMailException
12 {
13 if (registeredEmails.contains(email))
14 {
15 throw new CheckUserMailException("Email Already Registered");
16 }
17 else
18 System.out.print("New user");
19 }
20 }
21
22
1 public class RegistrationServiceClient {
2 public static void main(String[] args) {
3 Scanner sc = new Scanner(System.in);
4 String str[]= new String[5];
5 for(int i=0;i<5;i++)
6 {
7 str[i]=sc.next();
8 }
9 String mail = sc.next();
10 List<String> registeredEmails = Arrays.asList(str);
11 RegistrationService service = new RegistrationService();
12 try{
13 service.validateEmail(registeredEmails, mail);
14 }
15 catch (CheckUserMailException e) {
16 System.out.print(e);
17 }
18 }
19 }
20
21
22
Question 3
Create your own exception called IncorrectPinException it should display
an message called “Please Try again”. Your code should get two input from
the user which are setpin and pin.

If the setpin matches with the pin, then the output is “Mobile Unlocked”.

If the setpin doesn’t matches with the pin, an exception is thrown called
IncorrectPinException.
Question 3
Sample Input1: Sample Output1:
475 IncorrectPinException: Please Try
485 again

Sample Input2: Sample Output2:


8562 Mobile Unlocked
8562
1 import java.util.Scanner;
2 class IncorrectPinException extends Exception
3 {
4 public IncorrectPinException(String message)
5 {
6 super(message);
7 }
8 }
9 class Pin
10 {
11 public void CheckPin(int setpin,int pin) throws IncorrectPinException {
12 if (setpin == pin)
13 {
14 System.out.print("Mobile Unlocked");
15 }
16 else
17 throw new IncorrectPinException("Please Try again");
18 }
19 }
20
21
22
1 public class Lockscreen
2 {
3 public static void main(String[] args)
4 {
5 Scanner sc = new Scanner(System.in);
6 int setpin = sc.nextInt();
7 int pin = sc.nextInt();
8 Pin num = new Pin();
9 try {
10 num.CheckPin(setpin,pin);
11 }
12 catch (IncorrectPinException e) {
13 System.out.print(e);
14 }
15 }
16 }
17
18
19
20
21
22
Question 4
Write a java program which will throw an Build-in exception called
ArrayIndexOutOfBounds Exception. You should catch that build-in
exception and rethrow that exception using your own exception named
InvalidAccessingDataException with message “There is no such data
available”.

Get size of an array ,array elements and the element at which index need be
fetched in the array from the user.
Question 4
If the given index is with in the range, it will display the element.

If the given index is out of bound, it will throw an


ArrayIndexOutOfBoundException. This exception is caught and rethrow
using own exception called InvalidAccessingDataException.
Question 4
Sample Input: Sample Output:
5 Exception in thread "main"
98 InvalidAccessingDataException: There is no such
65 data available
75 at StudentMark.fetchMark(Main.java:18)
42 at Main.main(Main.java:33)
Caused by:
98
java.lang.ArrayIndexOutOfBoundsException: 9
9 at StudentMark.fetchMark(Main.java:14)
... 1 more
1 import java.util.Scanner;
2 class InvalidAccessingDataException extends RuntimeException
3 {
4 public InvalidAccessingDataException(String message, Throwable cause)
5 {
6 super(message, cause);
7 }
8 }
9 class StudentMark
10 {
11 public void fetchMark(int arr[], int rollno)
12 {
13 try {
14 System.out.print("Mark of the rollno "+ rollno + " is = "+ arr[rollno]);
15 }
16 catch (ArrayIndexOutOfBoundsException e)
17 {
18 throw new InvalidAccessingDataException("There is no such data available", e);
19 }
20 }
21 }
22
1 public class Main {
2 public static void main(String[] args) {
3 Scanner sc = new Scanner(System.in);
4 int no_of_details = sc.nextInt();
5 int arr[] = new int[no_of_details];
6 for(int i=0;i<no_of_details;i++)
7 {
8 arr[i]=sc.nextInt();
9 }
10 int rollno = sc.nextInt();
11 StudentMark sm = new StudentMark();
12 sm.fetchMark(arr,rollno);
13 }
14 }
15
16
17
18
19
20
21
22
Question 5
Write a java program which will throw an Build-in exception called
NullPointerException. You should catch that build-in exception and rethrow
using your own exception named EnteryourPasswordException with
message “Kindly Enter the Password”.

Your program should get password from the user.

If the user forget to enter the password, it will throw an


NullPointerException and this exception thrown by using your own
exception named EnteryourPasswordException.
Question 5
Sample Input: Sample Output:
No input Exception in thread "main"
EnteryourPasswordException: Kindly Enter the
Password
at LoginPage.CheckPassword(Main.java:26)
at Main.main(Main.java:35)
Caused by: java.lang.NullPointerException
at LoginPage.CheckPassword(Main.java:18)
... 1 more
1 import java.util.Scanner;
2 class EnteryourPasswordException extends RuntimeException
3 {
4 public EnteryourPasswordException(String message, Throwable cause)
5 {
6 super(message, cause);
7 }
8 }
9 class LoginPage
10 {
11 public void CheckPassword(String Password)
12 {
13 if(Password.length()==0)
14 {
15 Password = null;
16 }
17 try {
18 if(Password.equals("Thanos"))
19 System.out.print("Successfully Logged in");
20 else
21 System.out.print("Invalid Password");
22 }
1 catch (NullPointerException e)
2 {
3 throw new EnteryourPasswordException("Kindly Enter the Password", e);
4 }
5 }
6 }
7 public class Main {
8 public static void main(String[] args) {
9 Scanner sc = new Scanner(System.in);
10 String Password = sc.nextLine();
11 LoginPage login = new LoginPage();
12 login.CheckPassword(Password);
13 }
14 }
15
16
17
18
19
20
21
22
THANK YOU
Question 1
Imagine you are about to meet your school friends after long time. You have
planned to play cards with your friends , but your friends are unaware of
how shuffling works in playing cards, so write a program in Java to give the
shuffled cards as the output to proceed your game with fun.

Sample Input: Sample Output:


8 [2, 6, 7, 3, 1, 5, 8, 4]
12345678
1 import java.util.*;
2 public class Main
3 {
4 public static void main(String args[])
5 {
6 LinkedList<Integer> list=new LinkedList<Integer>();
7 Scanner s=new Scanner(System.in);
8 int num=s.nextInt();
9 while(num!=0)
10 {
11 list.add(s.nextInt());
12 num--;
13 }
14 Collections.shuffle(list);
15 System.out.println(list);
16 }
17 }
18
19
20
21
22
Question 2
Imagine that you have opened a new saving account in Central Bank of
India and you have applied for an ATM card. The card in given to you and
you are instructed to generate the PIN number of your choice for doing, so ,
You have to follow the instructions given by police department. If you are
ready to take amount from an ATM centre using your ATM card and a
robber came inside and asks you to withdraw the cash for him. The
instruction from the police to handle the situation in to enter the PIN in
reverse direction (eg : 1234 – ATM PIN number reversed PIN number to
alert police 4321). To make the job of police easy , the generate PIN
number should not be a palindrome, number which could the robber’s job
easy, so , Write a program in Java helping the user to generate valid PIN
number.
Question 2
Sample Input 1: Sample Output 1:
4 Not a Palindrome
1234

Sample Input 2: Sample Output 2:


4 Palindrome
1221
1 import java.util.Scanner;
2 import java.util.LinkedList;
3 import java.util.Collections;
4 public class Main{
5 public static void main(String args[]){
6 LinkedList<Integer> list=new LinkedList<Integer>();
7 Scanner s=new Scanner(System.in);
8 int num=s.nextInt();
9 while(num!=0){
10 list.add(s.nextInt());
11 num--;
12 }
13 LinkedList<Integer> newlist = new LinkedList<Integer>(list);
14 Collections.reverse(list);
15 if(list.equals(newlist)){
16 System.out.println("Palindrome");
17 }
18 else{
19 System.out.println("Not a Palindrome");
20 }
21 }
22 }
Question 3
Let us consider your college has planned a game to make the students
happy. Each student is given with a profession. The game is to find the thief.
There are “n” students in your college each having a no starting from 1 to till
n and a unique profession. All the students are not mandatorily arranged in
the order. They are standing with their own friends. Your principal picked
“n” number of students from the group and asked them to stand in a line
with “n” numbers . The person who is standing in the “yth” position after
being involved for “x” clockwise pivot, is considered to be the thief . Write a
program in Java to help your principal in finding the thief .
Question 3
Sample Input 1: Sample Output 1:
5 [1, 32, 3, 4, 5]
1 32 3 4 5 [4, 5, 1, 32, 3]
2 4
0

Sample Input 2: Sample Output 2:


6 [2, 356, 7, 8, 90, 1]
2 356 7 8 90 1 [8, 90, 1, 2, 356, 7]
3 356
4
1 import java.util.Scanner;
2 import java.util.LinkedList;
3 import java.util.Collections;
4 public class Main{
5 public static void main(String args[])
6 {
7 LinkedList<Integer> list=new LinkedList<Integer>();
8 Scanner s=new Scanner(System.in);
9 int num=s.nextInt();
10 while(num!=0)
11 {
12 list.add(s.nextInt());
13 num--;
14 }
15 int num1=s.nextInt();
16 System.out.println(list);
17 Collections.rotate(list, num1);
18 System.out.println(list);
19 int value=s.nextInt();
20 System.out.println(list.get(value));
21 }
22 }
Question 4
Write a Java program to rearrange the linked list, so that it has alternating
high, low values .

Description:
Given an linked list of integers rearrange it such the every second node of
the linked list is greater than its left and right nodes. In other words
rearrange linked list node in alternating high to low. Assume no duplicate
nodes are present in the linked list.
Sample Input: Sample Output:
7 1325476
1234567
1 import java.util.Scanner;
2 class Node
3 {
4 int data;
5 Node next;
6
7 Node(int data, Node next) {
8 this.data = data;
9 this.next = next;
10 }
11 };
12 public class Main
13 {
14 public static void printList(Node head)
15 {
16 Node ptr = head;
17 while (ptr != null)
18 {
19 System.out.print(ptr.data+" ");
20 ptr = ptr.next;
21 }
22 }
1 public static Node rearrange(Node head)
2 {
3 if (head == null)
4 return null;
5 Node prev = head;
6 Node curr = head.next;
7 while (curr != null)
8 {
9 if (prev.data > curr.data)
10 {
11 int temp = prev.data;
12 prev.data = curr.data;
13 curr.data = temp;
14 }
15 if (curr.next != null && curr.next.data > curr.data)
16 {
17 int temp = curr.next.data;
18 curr.next.data = curr.data;
19 curr.data = temp;
20 }
21 prev = curr.next;
22
1 if (curr.next == null){
2 break;
3 }
4 curr = curr.next.next;
5 }
6 return head;
7 }
8 public static void main(String[] args){
9 Scanner s=new Scanner(System.in);
10 int num=s.nextInt();
11 int keys[]=new int[num];
12 Node head = null;
13 for(int i=0;i<num;i++){
14 keys[i]=s.nextInt();
15 }
16 for (int i = keys.length - 1; i >= 0; i--){
17 head = new Node(keys[i], head);
18 }
19 head = rearrange(head);
20 printList(head);
21 }
22 }
Question 5
Write a Java program to find the reverse an every group of k nodes in given
linked list.

Description:
Given a linked list, reverse every adjacent group of k nodes in it, where k is
given positive integer

Sample Input: Sample Output:


8 32165487
123456 78
3
1 import java.util.Scanner;
2 class Node
3 {
4 int data;
5 Node next;
6 Node(int data, Node next)
7 {
8 this.data = data;
9 this.next = next;
10 }
11 public void print()
12 {
13 Node ptr = this;
14 while (ptr.next != null)
15 {
16 System.out.print(ptr.data + " ");
17 ptr = ptr.next;
18 }
19 System.out.println(ptr.data);
20 }
21 };
22
1 public class Main
2 {
3 public static Node reverseInGroups(Node head, int k)
4 {
5 if (head == null)
6 {
7 return null;
8 }
9 Node current = head;
10 Node prev = null;
11 int count = 0;
12 while (current != null && count++ < k)
13 {
14 Node next = current.next;
15 current.next = prev;
16 prev = current;
17 current = next;
18 }
19 head.next = reverseInGroups(current, k);
20 return prev;
21 }
22
1 public static void main(String[] args)
2 {
3 Scanner s=new Scanner(System.in);
4 int num=s.nextInt();
5 int keys[]=new int[num];
6 for(int i=0;i<num;i++)
7 {
8 keys[i]=s.nextInt();
9 }
10 Node head = null;
11 int value=s.nextInt();
12 for (int i = keys.length - 1; i >= 0; i--)
13 {
14 head = new Node(keys[i], head);
15 }
16 head = reverseInGroups(head, value);
17 head.print();
18 }
19 }
20
21
22
THANK YOU
Programming
Question 1
Write a java program to implement Stack using Arrays

Sample Input:
1
56
3
2
2
4
Question 1
Sample Output:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Question 1
Sample Output:
Printing stack elements:
56

1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Question 1
Sample Input:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

Underflow !!
1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Exiting....
1 import java.util.Scanner;
2 class Stack
3 {
4 int top;
5 int maxsize = 10;
6 int[] arr = new int[maxsize];
7 boolean isEmpty(){
8 return (top < 0);
9 }
10 Stack()
11 {
12 top = -1;
13 }
14
15
16
17
18
19
20
21
22
1 boolean push (Scanner sc)
2 {
3 if(top == maxsize-1)
4 {
5 System.out.println("Overflow !!");
6 return false;
7 }
8 else
9 {
10 int val = sc.nextInt();
11 top++;
12 arr[top]=val;
13 return true;
14 }
15 }
16
17
18
19
20
21
22
1 boolean pop ()
2 {
3 if (top == -1)
4 {
5 System.out.println("Underflow !!");
6 return false;
7 }
8 else
9 {
10 top --;
11 return true;
12 }
13 }
14 void display () {
15 System.out.println("Printing stack elements:");
16 for(int i = top; i>=0;i--)
17 {
18 System.out.println(arr[i]);
19 }
20 }
21 }
22
1 public class Stack_Operations {
2 public static void main(String[] args) {
3 int choice=0;
4 Scanner sc = new Scanner(System.in);
5 Stack s = new Stack();
6 while(choice != 4) {
7 System.out.println("1.Push\n2.Pop\n3.Show\n4.Exit");
8 System.out.println("Enter your choice \n");
9 choice = sc.nextInt();
10 switch(choice)
11 {
12 case 1: {
13 s.push(sc);
14 break;
15 }
16 case 2: {
17 s.pop();
18 break;
19 }
20
21
22
1 case 3:
2 {
3 s.display();
4 break;
5 }
6 case 4:
7 {
8 System.out.println("Exiting....");
9 System.exit(0);
10 break;
11 }
12 default:
13 {
14 System.out.println("Please Enter valid choice ");
15 }
16 };
17 }
18 }
19 }
20
21
22
Question 2
Java Program to Implement Stack using Linked List.

Sample Input:
1
20
1
30
1
25
1
37
3
4
Question 2
Sample Output:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Question 2
Sample Input:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

37->25->30->20->
1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Exiting....
1 import java.util.*;
2 class StackUsingLinkedlist
3 {
4 private class Node {
5 int data;
6 Node link;
7 }
8 Node top;
9 StackUsingLinkedlist()
10 {
11 this.top = null;
12 }
13 public void push(int x)
14 {
15 Node temp = new Node();
16 temp.data = x;
17 temp.link = top;
18 top = temp;
19 }
20
21
22
1 public void pop()
2 {
3 if (top == null) {
4 System.out.print("Stack Underflow\n");
5 return;
6 }
7 top = (top).link;
8 }
9 public void display(){
10 if (top == null) {
11 System.out.printf("No elements to Display\n");
12 }
13 else {
14 Node temp = top;
15 while (temp != null) {
16 System.out.printf("%d->", temp.data);
17 temp = temp.link;
18 }
19 System.out.printf("\n");
20 }
21 }
22 }
1 public class Stack_Operations
2 {
3 public static void main(String[] args)
4 {
5 StackUsingLinkedlist obj = new StackUsingLinkedlist();
6 int choice=0;
7 Scanner sc = new Scanner(System.in);
8 Stack s = new Stack();
9 while(choice != 4) {
10 System.out.println("1.Push\n2.Pop\n3.Show\n4.Exit");
11 System.out.println("Enter your choice\n");
12 choice = sc.nextInt();
13 switch(choice)
14 {
15 case 1: int x = sc.nextInt();
16 obj.push(x);
17 break;
18 case 2: obj.pop();
19 break;
20 case 3: obj.display();
21 break;
22
1 case 4: System.out.println("Exiting....");
2 System.exit(0);
3 default:System.out.println("Please Enter valid choice");
4 break;
5 }
6 }
7 }
8 }
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Question 3
Write a java program to implement Stack using Collections
Question 3
Sample Input:
1
71
1
35
1
96
2
3
1
92
3
4
Question 3
Sample Output:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Question 3
Sample Output:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Question 3
Sample Output:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

The contents of the Stack are:71


35
1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Question 3
Sample Output:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

The contents of the Stack are:71 35 92


1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Exiting....
1 import java.util.*;
2 class StackUsingCollections
3 {
4 Stack<Integer> stack = new Stack<>();
5 public void push(int x)
6 {
7 stack.push(x);
8 }
9 public void pop()
10 {
11 if(!(stack.isEmpty()))
12 {
13 stack.pop();
14 }
15 else
16 System.out.print("Stack Underflow\n");
17 }
18 public void display()
19 {
20 if(stack.isEmpty()) {
21 System.out.print("No Elements to display\n");
22 }
1 else{
2 System.out.print("The contents of the Stack are:");
3 for(int i: stack)
4 System.out.printf(i + " ");
5 System.out.println();
6 }
7 }
8 }
9 public class dd
10 {
11 public static void main(String[] args)
12 {
13 StackUsingCollections s = new StackUsingCollections();
14 int choice = 0;
15 Scanner sc = new Scanner(System.in);
16 while(choice != 4)
17 {
18 System.out.println("1.Push\n2.Pop\n3.Show\n4.Exit");
19 System.out.println("Enter your choice\n");
20 choice = sc.nextInt();
21
22
1 while(choice != 4)
2 {
3 System.out.println("1.Push\n2.Pop\n3.Show\n4.Exit");
4 System.out.println("Enter your choice\n");
5 choice = sc.nextInt();
6 switch(choice)
7 {
8 case 1: int x = sc.nextInt();
9 s.push(x);
10 break;
11 case 2: s.pop();
12 break;
13 case 3: s.display();
14 break;
15 case 4: System.out.println("Exiting....");
16 System.exit(0);
17 default:System.out.println("Please Enter valid choice");
18 break;
19 }
20 }
21 }
22 }
Question 4
Evaluate given postfix expression using stack

Sample Input: Sample Output:


74-3*15+* 54
1 import java.util.*;
2 import java.util.Stack;
3 public class Main
4 {
5 public static int postfixEval(String exp)
6 {
7 Stack<Integer> stack = new Stack<>();
8 for (int i = 0; i < exp.length(); i++)
9 {
10 if (Character.isDigit(exp.charAt(i))) {
11 stack.push(exp.charAt(i) - '0');
12 }
13 else
14 {
15 int x = stack.pop();
16 int y = stack.pop();
17 if(exp.charAt(i) == '+') {
18 stack.push(y + x);
19 }
20 else if(exp.charAt(i) == '-') {
21 stack.push(y - x);
22 }
1 else if(exp.charAt(i) == '*') {
2 stack.push(y * x);
3 }
4 else if(exp.charAt(i) == '/') {
5 stack.push(y / x);
6 }
7 }
8 }
9 return stack.pop();
10 }
11 public static void main(String[] args)
12 {
13 Scanner sc = new Scanner(System.in);
14 String exp = sc.next();
15 System.out.println(postfixEval(exp));
16 }
17 }
18
19
20
21
22
Question 5
Find all binary strings that can be formed from given wildcard pattern.

Sample Input: Sample Output:


74-3*15+* 54
1 import java.util.*;
2 import java.util.Stack;
3 public class Combinations
4 {
5 public static void printAllCombinations(String pattern)
6 {
7 Stack<String> stack = new Stack();
8 stack.push(pattern);
9 int index;
10 while (!stack.empty())
11 {
12 String curr = stack.pop();
13 if ((index = curr.indexOf('?')) != -1)
14 {
15 for (char ch = '0'; ch <= '1'; ch++)
16 {
17 curr = curr.substring(0, index) + ch +
18 curr.substring(index + 1);
19 stack.push(curr);
20 }
21 }
22
1 else
2 System.out.println(curr);
3 }
4 }
5 public static void main(String[] args)
6 {
7 Scanner sc = new Scanner(System.in);
8 String str = sc.next();
9 printAllCombinations(str);
10 }
11 }
12
13
14
15
16
17
18
19
20
21
22
Question 6
Write a java program to implement Stack using Queue.

Sample Input:
1
56
3
2
2
4
Question 6
Sample Output:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Question 6
Sample Output:
Printing stack elements:
56

1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Question 6
Sample Output:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

Underflow !!
1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Exiting....
1 import java.util.*;
2 import java.util.LinkedList;
3 import java.util.Queue;
4 public class Stack {
5 Queue<Integer> q = new LinkedList<Integer>();
6 void push(int val) {
7 int size = q.size();
8 q.add(val);
9 for (int i = 0; i < size; i++)
10 {
11 int x = q.remove();
12 q.add(x);
13 }
14 }
15 int pop() {
16 if (q.isEmpty()) {
17 System.out.println("No elements");
18 return -1;
19 }
20 int x = q.remove();
21 return x;
22 }
1 void display()
2 {
3 if(!(q.isEmpty()))
4 {
5 System.out.print("The contents of the stack are\n");
6 for(int i:q)
7 {
8 System.out.printf("%d->",i);
9 }
10 }
11 else
12 {
13 System.out.print("No elements to display");
14 }
15 System.out.print("\n");
16 }
17 public static void main(String[] args)
18 {
19 Scanner sc = new Scanner(System.in);
20 int ch;
21 Stack s = new Stack();
22
1 do {
2 System.out.print("Enter your choice\n");
3 ch = sc.nextInt();
4 switch(ch) {
5 case 1: System.out.print("Enter the element to be
6 pushed\n");
7 int x = sc.nextInt();
8 s.push(x);
9 break;
10 case 2: int data1 = s.pop();
11 if(data1 != -1)
12 System.out.printf("The popped element is
13 %d\n",data1);
14 break;
15 case 3: s.display();
16 break;
17 default:System.out.print("Exit");
18 System.exit(0);
19 }
20 } while(true);
21 }
22 }
THANK YOU
Programming
Question 1
Write a java program to implement Queue using Array. The capacity of the
queue is given by the user.
Question 1
Sample Input:
5
1
56
1
27
1
33
1
6
3
2
3
4
Question 1
Sample Output:
1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice

1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice
Question 1
Sample Output:
1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice

1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice

1.Enqueue
Question 1
Sample Output:
1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice

56 <-- 27 <-- 33 <-- 6 <--


1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice
Question 1
Sample Output:
1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice

1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice
Question 1
Sample Output:
33 <-- 6 <--
1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice

Exiting....
1 import java.util.*;
2 class Queue {
3 private static int front, rear, capacity;
4 private static int queue[];
5 Queue(int c)
6 {
7 front = rear = 0;
8 capacity = c;
9 queue = new int[capacity];
10 }
11 static void queueEnqueue(int data)
12 {
13 if (capacity == rear) {
14 System.out.printf("\nQueue is full\n");
15 return;
16 }
17 else {
18 queue[rear] = data;
19 rear++;
20 }
21 return;
22 }
1 static void queueDequeue()
2 {
3 if (front == rear) {
4 System.out.printf("\nQueue is empty\n");
5 return;
6 }
7 else {
8 for (int i = 0; i < rear - 1; i++) {
9 queue[i] = queue[i + 1];
10 }
11 if (rear < capacity)
12 queue[rear] = 0;
13 rear--;
14 }
15 return;
16 }
17
18
19
20
21
22
1 static void queueDisplay()
2 {
3 int i;
4 if (front == rear) {
5 System.out.printf("\nQueue is Empty\n");
6 return;
7 }
8 for (i = front; i < rear; i++) {
9 System.out.printf(" %d <-- ", queue[i]);
10 }
11 System.out.println();
12 return;
13 }
14 }
15 public class Queue_Operations {
16 public static void main(String[] args) {
17 int choice=0;
18 Scanner sc = new Scanner(System.in);
19 int size = sc.nextInt();
20 Queue q = new Queue(size);
21
22
1 while(choice != 4) {
2 System.out.println("1.Enqueue\n2.Dequeue\n3.Show\n4.Exit");
3 System.out.println("Enter your choice\n");
4 choice = sc.nextInt();
5 switch(choice) {
6 case 1: {
7 int x = sc.nextInt();
8 q.queueEnqueue(x);
9 break;
10 }
11 case 2: {
12 q.queueDequeue();
13 break;
14 }
15
16
17
18
19
20
21
22
1 case 3: {
2 q.queueDisplay();
3 break;
4 }
5 case 4: {
6 System.out.println("Exiting....");
7 System.exit(0);
8 break;
9 }
10 };
11 }
12 }
13 }
14
15
16
17
18
19
20
21
22
Question 2
Write a java program to implement Queue using Linked List
Question 2
Sample Input:
1
14
1
7
1
23
3
2
2
2
2
3
4
Question 2
Sample Input:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

1.Push
2.Pop
3.Show
4.Exit
Enter your choice

1.Push
Question 2
Sample Input:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Question 2
Sample Input:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

1.Push
2.Pop
3.Show
4.Exit
Enter your choice

14 7 23
Question 2
Sample Input:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Question 2
Sample Input:
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Question 2
Sample Input:
Queue is empty..
1.Push
2.Pop
3.Show
4.Exit
Enter your choice

No elements to display
1.Push
2.Pop
3.Show
4.Exit
Enter your choice
Exiting....
1 import java.util.Scanner;
2 public class LinkedListQueue
3 {
4 Node front;
5 Node rear;
6 public LinkedListQueue()
7 {
8 front = null;
9 rear = null;
10 }
11 private class Node
12 {
13 int i;
14 Node next;
15 Node(int i)
16 {
17 this.i = i;
18 }
19 public void displayData(){
20 System.out.print(i + " ");
21 }
22 }
1 public void insertLast(int i)
2 {
3 Node newNode = new Node(i);
4 if(front == null)
5 {
6 front = newNode;
7 }
8 else
9 {
10 rear.next = newNode;
11 }
12 rear = newNode;
13 }
14 public int removeFirst()
15 {
16 if(front == null){
17 System.out.print("Queue is empty..\n");
18 return 1;
19 }
20
21
22
1 else{
2 int temp = front.i;
3 if(front.next == null){
4 rear = null;
5 }
6 front = front.next;
7 return temp;
8 }
9 }
10 public void displayList(){
11 Node current = front;
12 if(current == null)
13 System.out.print("No elements to display\n");
14 else{
15 while(current != null)
16 {
17 current.displayData();
18 current = current.next;
19 }
20 System.out.println();
21 }
22 }
1 public static void main(String[] args)
2 {
3 LinkedListQueue queue = new LinkedListQueue();
4 int choice=0;
5 Scanner sc = new Scanner(System.in);
6 while(choice != 4) {
7 System.out.println("1.Push\n2.Pop\n3.Show\n4.Exit");
8 System.out.println("Enter your choice\n");
9 choice = sc.nextInt();
10 switch(choice)
11 {
12 case 1: int x = sc.nextInt();
13 queue.insertLast(x);
14 break;
15 case 2: queue.removeFirst();
16 break;
17 case 3: queue.displayList();
18 break;
19
20
21
22
1 case 4: System.out.println("Exiting....");
2 System.exit(0);
3 default: System.out.println("Please Enter valid choice");
4 break;
5 }
6 }
7 }
8 }
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Question 3
Write a java program to implement Queue using Stack
Question 3
Sample Input:
1
7
1
5
1
103
3
2
2
2
2
3
4
Question 3
Sample Output:
Enter your choice
Enter your choice
Enter your choice
Enter your choice
The contents of queue are:
7<-5<-103<-
Enter your choice
Enter your choice
Enter your choice
Enter your choice
Underflow
Question 3
Sample Output:
Enter your choice
No elements to Display
Enter your choice
Exit
1 import java.util.*;
2 import java.util.Stack;
3 public class Queue<T> {
4 private Stack<T> s;
5 Queue() {
6 s = new Stack<>();
7 }
8 public void enqueue(T data) {
9 s.push(data);
10 }
11 public T dequeue()
12 {
13 T top = s.pop();
14 try
15 {
16 if (s.isEmpty()) {
17 return top;
18 }
19 }
20
21
22
1 catch(Exception ex)
2 {
3
4 }
5 T item = dequeue();
6 s.push(top);
7 return item;
8 }
9 public int display()
10 {
11 if(!s.isEmpty())
12 {
13 System.out.print("The contents of queue are:\n");
14 for(T i:s) {
15 System.out.print(i + "<-");
16 }
17 System.out.print("\n");
18 return 2;
19 }
20 else
21 return 1;
22 }
1 public static void main(String[] args)
2 {
3 Scanner sc = new Scanner(System.in);
4 int ch;
5 Queue q = new Queue();
6 do {
7 System.out.print("Enter your choice\n");
8 ch = sc.nextInt();
9 switch(ch)
10 {
11 case 1: int x = sc.nextInt();
12 q.enqueue(x);
13 break;
14 case 2: try
15 {
16 q.dequeue();
17 }
18 catch(Exception ex)
19 {
20 System.out.print("Underflow\n");
21 }
22 break;
1 case 3: int y = q.display();
2 if(y==1)
3 {
4 System.out.print("No elements to Display\n");
5 }
6 break;
7 default: System.out.print("Exit");
8 System.exit(0);
9 }
10 } while(true);
11 }
12 }
13
14
15
16
17
18
19
20
21
22
Question 4
Generate binary number between 1 to n using queue.

Sample Input: Sample Output:


5 1 10 11 100 101
1 import java.util.*;
2 import java.util.ArrayDeque;
3 import java.util.Queue;
4 public class Main
5 {
6 public static void generate(int n){
7 Queue<String> q = new ArrayDeque<>();
8 q.add("1");
9 int i = 1;
10 while (i++ <= n)
11 {
12 q.add(q.peek() + "0");
13 q.add(q.peek() + "1");
14 System.out.print(q.poll() + ' ');
15 }
16 }
17 public static void main(String[] args){
18 Scanner sc = new Scanner(System.in);
19 int x = sc.nextInt();
20 generate(x);
21 }
22 }
Question 5
Write a java program to implement Queue using Collections
Question 5
Sample Input:
1
20
1
30
1
40
3
2
2
2
2
3
4
Question 5
Sample Output:
1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice

1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice
Question 5
Sample Output:
1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice

1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice
Question 5
Sample Output:
The contents of the Queue are:20 30 40
1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice

1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice
Question 5
Sample Output:
1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice

1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice
Question 5
Sample Output:
Queue Underflow
1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice
No Elements to display
1.Enqueue
2.Dequeue
3.Show
4.Exit
Enter your choice
Exiting....
1 import java.util.*;
2 class QueueUsingCollections
3 {
4
5 Queue<Integer> q = new LinkedList<Integer>();
6 public void enqueue(int x)
7 {
8 q.add(x);
9 }
10 public void dequeue()
11 {
12 if(!(q.isEmpty()))
13 {
14 q.remove();
15 }
16 else
17 System.out.print("Queue Underflow\n");
18 }
19
20
21
22
1 public void display()
2 {
3 if(q.isEmpty()) {
4 System.out.print("No Elements to display\n");
5 }
6
7 else{
8 System.out.print("The contents of the Queue are:");
9 for(int i: q)
10 System.out.printf(i + " ");
11 System.out.println();
12 }
13 }
14 }
15 public class Main
16 {
17 public static void main(String[] args) {
18 QueueUsingCollections Q = new QueueUsingCollections();
19 int choice = 0;
20 Scanner sc = new Scanner(System.in);
21
22
1
2 while(choice != 4) {
3 System.out.println("1.Enqueue\n2.Dequeue\n3.Show\n4.Exit");
4 System.out.println("Enter your choice\n");
5 choice = sc.nextInt();
6 switch(choice)
7 {
8 case 1: int x = sc.nextInt();
9 Q.enqueue(x);
10 break;
11 case 2: Q.dequeue();
12 break;
13 case 3: Q.display();
14 break;
15 case 4: System.out.println("Exiting....");
16 System.exit(0);
17 default:System.out.println("Please Enter valid choice");
18 break;
19 }
20 }
21 }
22 }
THANK YOU
Question 1
Central Board of secondary education had recently conducted a board
exam for grade “Xth” students. They need to sort the “n” students based on
rank. Write a java program to help the CBSE to get the students name list
on rank basis.

Note:
Consider there are “n” no of students whose marks are calculated out
of 600.
Question 1
Sample Input: Sample Output:
4 The ranks based on their marks:
541 Rank 1: Arun
Arun Rank 2: Saran
452 Rank 3: Tamil
Tamil Rank 4: Merin
367
Merin
456
Saran
1 import java.util.Map;
2 import java.util.TreeMap;
3 import java.util.NavigableMap;
4 import java.util.Scanner;
5 public class Main {
6 public static void main(String[] args) {
7 TreeMap<Integer, String> p1 = new TreeMap<Integer, String>();
8 Scanner sc = new Scanner(System.in);
9 int num =sc.nextInt();
10 String name;
11 int mark;
12 while(num!=0)
13 {
14 mark=sc.nextInt();
15 name=sc.next();
16 p1.put(mark,name);
17 num--;
18 }
19 NavigableMap<Integer, String> Rank = p1.descendingMap();
20 System.out.println("The ranks based on their marks: ");
21 int count = 0;
22
1 for (NavigableMap.Entry<Integer, String> entry:Rank.entrySet())
2 {
3 count++;
4 String str = Integer.toString(count);
5 System.out.println("Rank " + str + ": "
6 +entry.getValue());
7 }
8 }
9 }
10
11
12
13
14
15
16
17
18
19
20
21
22
Question 2
India is a country which is famous for its culture. One such culture is having
father’s name as the surname of all the members of the family. You are
aware of all the names of your family, But you don’t know their surname, so
you are seeking help from your grandfather , your grandfather told you that
he can tell only the father’s name. Preparing the name list of your friends
family with their surname is the duty of your work, so write a java program
to preparing such list.

Note :
Each individual is having unique first name.
Question 2
Sample Input: Sample Output:
4 SurName : Arun
Aruna [Aruna Arun, Karthi Arun, Keerthi Arun,
Karthi Swathi Arun]
Keerthi
Swathi
Arun
1 import java.util.Scanner;
2 import java.util.TreeSet;
3 public class Main{
4 public static void main(String args[]){
5 TreeSet<StringBuilder> list=new TreeSet<StringBuilder>();
6 Scanner s=new Scanner(System.in);
7 int num=s.nextInt();
8 while(num!=0){
9 StringBuilder sb=new StringBuilder(s.next());
10 list.add(sb);
11 num--;
12 }
13 String st=s.next();
14 StringBuilder str1=new StringBuilder(st);
15 for(StringBuilder i :list)
16 {
17 i.append(" " +str1);
18 }
19 System.out.println("SurName : " + str1);
20 System.out.println(list);
21 }
22 }
Question 3
Imagine you are working as a professor in “XYZ” college. You are in charge
of conducting the lab exams for a set of students for ‘n’ number of students
. You have prepared ‘n’ number of questions and they are ordered as per
the attendance . [ Experiment ‘1’ will be assigned to the students ‘1’ in he
attendence ], But your plan was leaked somehow to the students, so you
need to handle the situation by not giving the same question which was
assigned earlier, so you have decided to reverse the experiment list so that
last student will receive the experiment “1”, Now it is time for conduct the
lab exams . Students are entering the laboratory not necessarily, in the
same order as in the attendence, but your principal instructed you to give
the students names alone in the order of experiments assigned [ Starting
form the students having experiment 1, but in your idea is last student is a
first student and he/his will receive the experiment] , so , Write
Question 3
a Java program to get the students name list in the required order.

Sample Input: Sample Output:


4 [Arun, Karthi, Keerthi, Sangeetha]
Karthi [Sangeetha, Keerthi, Karthi, Arun]
Keerthi
Arun
Sangeetha
1 import java.util.TreeSet;
2 import java.util.Comparator;
3 import java.util.Scanner;
4 public class Main
5 {
6 public static void main(String args[])
7 {
8 TreeSet<String> list=new TreeSet<String>();
9 Scanner s=new Scanner(System.in);
10 int num=s.nextInt();
11 while(num!=0)
12 {
13 list.add(s.next());
14 num--;
15 }
16 System.out.println(list);
17 TreeSet<String> newSet =new TreeSet<String>( list.descendingSet());
18 System.out.println(newSet);
19 }
20 }
21
22
Question 4
You are working as a professor in XYZ college. Your are instructed to select
a set of students for your class as you are allocated as the class advisor for
that class, But you colleague had picket a set of students in the attendance
order starting from ‘A’ you have to select the students in the attendance
order starting from the students who on after the last person of your
colleagues class . [For example if your colleague stopped the attendance
order with names of ‘R’ , then you have pick the students from names of ‘S’].
Your colleague gave you the list of students of his class but not in the
attendance order. Write a program in Java to find out the rear name in the
attendance of your colleague’s class.
Question 4
Sample Input: Sample Output:
5 [Arun, Aruna, Kavin, Ramya, sangeetha]
Sangeetha Sangeetha
Aruna
Arun
Kavin
Ramya
1 import java.util.Set;
2 import java.util.TreeSet;
3 import java.util.Comparator;
4 import java.util.Scanner;
5 public class Main
6 {
7 public static void main(String args[])
8 {
9 TreeSet<String> list=new TreeSet<String>();
10 Scanner s=new Scanner(System.in);
11 int num=s.nextInt();
12 while(num!=0)
13 {
14 list.add(s.next());
15 num--;
16 }
17 System.out.println(list.last());
18 }
19 }
20
21
22
Question 5
Write java program to construct a complete binary tree from given array in
level order fashion.

Sample Input: Sample Output:


9 646251636
1
2
3
4
5
6
6
6
6
1 import java.util.Scanner;
2 public class Tree {
3 Node root;
4 static class Node
5 {
6 int data;
7 Node left, right;
8 Node(int data) {
9 this.data = data;
10 this.left = null;
11 this.right = null;
12 }
13 }
14 public Node insertLevelOrder(int[] arr, Node root, int i) {
15 if (i < arr.length) {
16 Node temp = new Node(arr[i]);
17 root = temp;
18 root.left = insertLevelOrder(arr, root.left, 2 * i + 1);
19 root.right = insertLevelOrder(arr, root.right, 2 * i + 2);
20 }
21 return root;
22 }
1 public void inOrder(Node root) {
2 if (root != null)
3 {
4 inOrder(root.left);
5 System.out.print(root.data + " ");
6 inOrder(root.right);
7 }
8 }
9 public static void main(String args[])
10 {
11 Scanner s=new Scanner(System.in);
12 Tree t2 = new Tree();
13 int num=s.nextInt();
14 int arr[]=new int[num];
15 for(int i=0;i<num;i++)
16 {
17 arr[i]=s.nextInt();
18 }
19 t2.root = t2.insertLevelOrder(arr, t2.root, 0);
20 t2.inOrder(t2.root);
21 }
22 }
THANK YOU
API:
Java application programming interface.

Java Program

Java Compiler

Java API Java Platform


Java virtual
Machine

Hardware Based Platform


API Packages:
import
import java
java .util.
.lang. reflect
Scanner
Thread
* exception
Collections
reflect
ArrayList
LinkedList
Reflection in Java
What is Reflection:
• java.lang.reflect package has the classes and interfaces to do
reflection.

• The java.lang.class can be used as an entry point for the reflection.


Real time application
1 What will be the output of this program?
2 import java.util.*;
3
4 interface Demo1{
5 public void method1();
6 }
7 interface Demo2{
8
9 public void method2();
10 }
11 class Alldemo implements Demo1,Demo2{
12 public void method1(){
13
14 System.out.println("Demo1 Created");
15 }
16 public void method2()
17 {
18
19 System.out.println("Demo2 Created");
20 }
21 }
22
1 public class Main Output:
2 { Demo2 Created
3
4 public static void main(String args[]) Demo1 Created
5 {
6 Alldemo obj = new Alldemo();
7 obj.method2();
8
9 obj.method1();
10 }
11 }
12
13
14
15
16
17
18
19
20
21
22
What is the SuperClass of previous program?

util lang
lang
1 //Predict the Output
2 import java.util.Class;
3 interface Animal
4 {
5 public void display();
6 }
7 interface Mammal
8 {
9 public void makeSound();
10 }
11 class Dog implements Animal, Mammal
12 {
13 public void display()
14 {
15 System.out.println("I am a dog.");
16 }
17 public void makeSound()
18 {
19 System.out.println("Bark bark");
20 }
21 }
22
1 public class Main
2 {
3 public static void main(String[] args)
4 {
5 try
6 {
7 Dog d1 = new Dog();
8 Class obj = d1.getClass();
9 Class obj1=obj.getSuperclass();
10 System.out.println(obj);
11 System.out.println(obj1);
12 }
13 catch(Exception e)
14 {
15 e.printStackTrace();
16 }
17 }
18 }
19
20
21
22
1 //Predict the Output
2 import java.lang.Class;
3 interface Animal
4 {
5 public void display();
6 }
7 interface Mammal
8 {
9 public void makeSound();
10 }
11 class Dog implements Animal, Mammal
12 {
13 public void display()
14 {
15 System.out.println("I am a dog.");
16 }
17 public void makeSound()
18 {
19 System.out.println("Bark bark");
20 }
21 }
22
1 public class Main
2 {
3 public static void main(String[] args) Output:
4 { class Dog
5 try class java.lang.Object
6 {
7 Dog d1 = new Dog();
8 Class obj = d1.getClass();
9 Class obj1=obj.getSuperclass();
10 System.out.println(obj);
11 System.out.println(obj1);
12 }
13 catch(Exception e)
14 {
15 e.printStackTrace();
16 }
17 }
18 }
19
20
21
22
1 //Predict the Output
2 import java.lang.reflect.*;
3 interface Telephone
4 {
5 public void display();
6 }
7 interface Mobile
8 {
9 public void trent();
10 }
11 class android implements Telephone, Mobile
12 {
13 public void display()
14 {
15 System.out.println("Wattsapp");
16 }
17 public void trent()
18 {
19 System.out.println("ringtone");
20 }
21 }
22
1 public class Main
2 {
3 public static void main(String[] args)
4 {
5 try
6 {
7 android set = new android();
8 Class obj = set.getClass();
9 Class[] objInterface = obj.getInterfaces();
10 for(Class c : objInterface)
11 {
12 System.out.println("Interface Name: " + c.getName());
13 }
14 }
15 catch(Exception e)
16 {
17 e.printStackTrace();
18 }
19 }
20 }
21
22
Reflecting Fields:

• java.lang.reflect.Field

• It is used to get the value of the field object.

• If Field has a primitive type then the value of the field is automatically
wrapped in an object.
1 //Predict the Output
2 import java.lang.Class;
3 import java.lang.reflect.*;
4 class Dog
5 {
6 public String method;
7 }
8 public class Main
9 {
10 public static void main(String[] args)
11 {
12 try
13 {
14 Dog d1 = new Dog();
15 Class obj = d1.getClass();
16 Field field1 = obj.getField("method");
17 field1.set(d1, "Itallic");
18 String typeValue = (String)field1.get(d1);
19 System.out.println("type: " + typeValue);
20
21
22
1 int mod1 = field1.getModifiers();
2 String modifier1 = Modifier.toString(mod1);
3 System.out.println("Modifier: " + modifier1);
4 System.out.println(" ");
5 }
6 catch(Exception e)
7 {
8 e.printStackTrace();
9 }
10 }
11 }
12
13
14
15
16
17
18
19
20
21
22
1 //Predict the Output
2 import java.lang.Class;
3 import java.lang.reflect.*;
4 class Hacker{
5 public void coding () {
6 System.out.println("I am a Coder");
7 }
8 protected void hacking() {
9 System.out.println("I am a Hacker");
10 }
11 private void codehacking() {
12 System.out.println("This is my world");
13 }
14 }
15 public class Main{
16 public static void main(String[] args){
17 try {
18 Hacker d1 = new Hacker();
19 Class obj = d1.getClass();
20 Method[] methods = obj.getDeclaredMethods();
21
22
1 for(Method m : methods)
2 {
3 System.out.println("Method Name: " + m.getName());
4 int modifier = m.getModifiers();
5 System.out.println("Modifier: " +
6 Modifier.toString(modifier));
7 System.out.println("Return Types: " + m.getReturnType());
8 System.out.println(" ");
9 }
10 }
11 catch(Exception e)
12 {
13 e.printStackTrace();
14 }
15 }
16 }
17
18
19
20
21
22
Reflecting Fields:

• java.lang.reflect.Constructor

• class provides information about, and access to, a single constructor


for a class
1 //Predict the Output
2 import java.lang.Class;
3 import java.lang.reflect.*;
4 class World
5 {
6 public World()
7 {
8
9 }
10 public World(int Count)
11 {
12
13 }
14 private World(String people, String type)
15 {
16
17 }
18 }
19
20
21
22
1 public class Main {
2 public static void main(String[] args) {
3 try {
4 World d1 = new World();
5 Class obj = d1.getClass();
6 Constructor[] constructors = obj.getDeclaredConstructors();
7 for(Constructor c : constructors)
8 {
9 System.out.println("Constructor Name: " + c.getName());
10 int modifier = c.getModifiers();
11 System.out.println("Modifier: " +
12 Modifier.toString(modifier));
13 System.out.println("Parameters: " +c.getParameterCount());
14 System.out.println(" ");
15 }
16 }
17 catch(Exception e)
18 {
19 e.printStackTrace();
20 }
21 }
22 }
THANK YOU
Reflection –Annotations:

• Annotations are a kind of comment or meta data you can insert in


your Java code.
• These annotations can then be processed at compile time by pre-
compiler tools, or at runtime via Java Reflection
What are annotations?

Annotations are used to represent the syntactic metadata related to


the class, interface, methods or fields used in the source code and some
additional information which is used by java interpreter and the JVM
Why do we need Annotations?

• Compiler instructions
• Build-time instructions
• Run-time instructions
Annotations:

Types

Marker Annotations

Single Annotations

Full Annotations
Build in Annotations:

• Retention Annotation
• Depricated Annotation
• Override Annotation
• Suppress Warning Annotation
• Documented
• Target
• Inherited
1 //Predict the Output
2 import java.lang.annotation.*;
3 import java.lang.reflect.*;
4 /* a single-member annotation */
5 @Retention(RetentionPolicy.RUNTIME)
6 @interface MyValue
7 {
8 int value(); // this variable name must be value
9 }
10 public class Single
11 {
12 /* annotate a method using a single-member annotation */
13 @MyValue(100)
14 public static void myMethod()
15 {
16 Single obj = new Single();
17 try
18 {
19
20
21
22
1 Method m = obj.getClass().getMethod("myMethod");
2 MyValue annotation = m.getAnnotation(MyValue.class);
3 System.out.println(annotation.value()); // displays10
4 }
5 catch(NoSuchMethodException exc)
6 {
7 System.out.println("Method not found");
8 }
9 }
10 public static void main(String args[])
11 {
12 myMethod();
13 }
14 }
15
16
17
18
19
20
21
22
1 //Predict the Output
2 import java.lang.annotation.Annotation;
3 import java.lang.annotation.Retention;
4 import java.lang.annotation.RetentionPolicy;
5 import java.lang.reflect.Method;
6 @Retention(RetentionPolicy.RUNTIME)
7 @interface MyAnno
8 {
9 String str();
10 int val();
11 }
12 @Retention(RetentionPolicy.RUNTIME)
13 @interface Java
14 {
15 String description();
16 }
17 @Java(description = "An annotation test class")
18 @MyAnno(str = "Meta2", val = 1000)
19 public class Methods
20 {
21 @Java(description = "An annotation test method")
22 @MyAnno(str = "Testing", val = 100)
1 public static void myMethod() {
2 Methods ob = new Methods();
3 try {
4 Annotation annos[] = ob.getClass().getAnnotations();
5 System.out.println("All annotations for Method:");
6 for(Annotation a : annos)
7 System.out.println(a);
8 Method m = ob.getClass().getMethod("myMethod");
9 annos = m.getAnnotations();
10 System.out.println("All annotations for myMethod:");
11 for (Annotation a : annos)
12 System.out.println(a);
13 }
14 catch (NoSuchMethodException exc) {
15 System.out.println("Method Not Found.");
16 }
17 }
18 public static void main(String args[]) {
19 myMethod();
20 }
21 }
22
1 //Predict the Output
2 import java.lang.annotation.*;
3 import java.lang.reflect.*;
4 class Animal {
5 public void makeSound(){
6
7 }
8 }
9 class Cat extends Animal{
10 @Override
11 public void makeSound(){
12 System.out.println("Yowling");
13 }
14 }
15 public class Main
16 {
17 public static void main(String[] args)
18 {
19 Cat b = new Cat();
20 b.makeSound();
21 }
22 }
1 //Predict the Output
2 import java.lang.annotation.*;
3 import java.lang.reflect.*;
4 public class MyDeprecated
5 {
6 /**
7 * @deprecated
8 * reason for why it was deprecated
9 */
10 @Deprecated
11 public void showDeprecatedMessage()
12 {
13 System.out.println("This method is marked as deprecated");
14 }
15 public static void main(String a[])
16 {
17 MyDeprecated mde = new MyDeprecated();
18 mde.showDeprecatedMessage();
19 }
20 }
21
22
Reflection –Array:

• java.lang.Object
java.lang.reflect.Array

• This class provides static methods to dynamically create and access


Java arrays.
Reflection –Array Method:

• public static Object get(Object array, int index)


throws IllegalArgumentException,
ArrayIndexOutOfBoundsException
1 //Predict the Output
2 import java.lang.reflect.Array;
3 public class Main
4 {
5 public static void main(String... args)
6 {
7 Object[] arr = {1, 2, 3, "four"};
8 Object o = Array.get(arr, 2);
9 System.out.printf("object type: %s, value:%s%n", o.getClass(), o);
10 o = Array.get(arr, 3);
11 System.out.printf("object type: %s, value:%s%n", o.getClass(), o);
12 }
13 }
14
15
16
17
18
19
20
21
22
1 //Predict the Output
2 import java.lang.reflect.Array;
3 public class Main
4 {
5 public static void main(String args[])
6 {
7 Object arr = new Object();
8 Object o = Array.get(arr, 2);
9 System.out.printf("object type: %s, value:%s%n", o.getClass(), o);
10 }
11 }
12
13
14
15
16
17
18
19
20
21
22
1 //Predict the Output
2 import java.lang.reflect.Array;
3 public class Main
4 {
5 public static void main(String[] args)
6 {
7 int a[] = { 1, 2, 3, 4, 5 };
8 for (int i = 0; i < 5; i++)
9 {
10 int x = Array.getInt(a, i);
11 System.out.print(x + " ");
12 }
13 }
14 }
15
16
17
18
19
20
21
22
1 //Predict the Output
2 import java.lang.reflect.Array;
3 import java.util.Arrays;
4 public class Main
5 {
6 public static void main (String args[])
7 {
8 boolean[] array = new boolean[]{true,true,true};
9 Array.setBoolean(array, 1, false);
10 System.out.println(Arrays.toString(array));
11 }
12 }
13
14
15
16
17
18
19
20
21
22
1 //Predict the Output
2 import java.lang.reflect.Array;
3 public class Main
4 {
5 public static void main(String[] args)
6 {
7 int a[] = { 1, 2, 3, 4, 5 };
8 for (int i = 0; i < 5; i++)
9 {
10 long x = Array.getLong(a, i);
11 System.out.print(x + " ");
12 }
13 }
14 }
15
16
17
18
19
20
21
22
MCQ
1 //Predict the Output
2 import java.lang.reflect.*;
3 public class Main
4 {
5 public static void main(String args[])
6 {
7 try
8 {
9 Class cls = Class.forName("java.lang.String[]");
10 System.out.print(cls.getClass());
11 }
12 catch (ClassNotFoundException ex)
13 {
14 System.out.print("Exception Occured");
15 }
16 }
17 }
18
19
20
21
22
Question 1
A) Prints Main

B) Prints [java.lang.String; on console

C) Prints Exception Occur on console

D) Compilation error
Question 2
What is not the advantage of Reflection?

A) Examine a class’s field and method at runtime

B) Construct an object for a class at runtime

C) Examine a class’s field at compile time

D) Examine an object’s class at runtime


Question 3
How method can be invoked on unknown object?

A) obj.getClass().getDeclaredMethod()

B) obj.getClass().getDeclaredField()

C) obj.getClass().getMethod()

D) obj.getClass().getObject()
THANK YOU
SQL:

➢ Structured Query Language

➢ The standard for relational database management systems (RDBMS)

➢ RDBMS: A database management system that manages data as a


collection of tables in which all relationships are represented by common
values in related tables
What is SQL:

➢ It is designed for managing data in a relational database management


system (RDBMS).
➢ It is pronounced as S-Q-L or sometime See-Qwell.
What SQL does?

➢ With SQL, a user can access data from a relational database management
system.
➢ It allows the user to describe the data.
➢ It allows the user to define the data in the database and manipulate it
when needed.
SQL Environment
SQL Syntax:

➢ SQL is not case sensitive. Generally SQL keywords are written in


uppercase.
➢ SQL statements are dependent on text lines. We can place a single SQL
statement on one or multiple text lines.
SQL Statement:

SQL statements are started with any of the SQL commands/keywords like
SELECT, INSERT, UPDATE, DELETE, ALTER, DROP etc. and the statement
ends with a semicolon (;).

SQL statement:
SELECT "column_name" FROM "table_name";
RDBMS
➢ RDBMS stands for Relational Database Management System.
➢ RDBMS is the basis for SQL, and for all modern database systems like MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
Table

Record or row
Fields
Column

Roll No Name Address Mobile Number


15BEE2024 Dharma Karur 9058236956
15BEE2025 Eniyan Chennai 9885695666
15BEE2026 Gayathiri Trichy 7894689465
RDBMS

➢ RDBMS stands for Relational Database Management System.


➢ RDBMS is the basis for SQL, and for all modern database systems like MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
SQL Commands:
SQL Command

DDL DML DCL DDL

CREATE SELECT GRANT COMMIT


ALTER INSERT REVOKE ROLLBACK
DROP UPDATE SAVEPOINT
RENAME DELETE SET TRANSACTION
TRUNCATE MERGE
COMMENT CALL
EXPLAIN PLAN
LOCK TABLE
DDL

➢ Data Definition Language.


➢ It is used to define the database structure or schema.
➢ It is used to specify additional properties of the data
DML

➢ DML statements are used for managing data with in schema objects
Procedural DML’s
Declerative DML’s
TCL

➢ Transaction Control Language.


➢ Transaction Control Language commands are used to manage
transactions in the database
DCL (Data Control Language)

➢ A Data Control Language is a syntax similar to a computer programming


language used to control access to data stored in a database
(Authorization).
➢ In particular, it is a component of Structured Query Language (SQL).
SQL Data Types:

➢ String Data types


➢ Numeric Data types
➢ Date and time Data types
MySQL String Data Types:

➢ CHAR(Size)
➢ VARCHAR(Size)
➢ BINARY(Size)
➢ VARBINARY(Size)
➢ TEXT(Size)
➢ TINYTEXT
➢ MEDIUMTEXT
➢ LONGTEXT
MySQL Numeric Data Types:

➢BIT(Size)
➢INT(size)
➢INTEGER(size)
➢FLOAT(size, d)
➢FLOAT(p)
➢DOUBLE(size, d)
MySQL Data and Time Date Types:

➢ DATE
➢ DATETIME(fsp)
➢ TIMESTAMP(fsp)
➢ TIME(fsp)
➢ YEAR
SQL Operators

➢ SQL Arithmetic Operators


➢ SQL Comparison Operators
➢ SQL Logical Operators
CREATE DATABASE:

To create a new database <testDB>, then use the CREATE DATABASE


statement

Syntax:
CREATE DATABASE DatabaseName;
DROP DATABASE:

To delete an existing database <testDB>, then use the DROP DATABASE


statement.

Syntax:
DROP DATABASE DatabaseName;
SELECT DATABASE:

The SQL USE statement is used to select any existing database in the SQL
schema.

Syntax:
USE DatabaseName;
Create Table:

CREATE TABLE is the keyword telling the database system to create a table.

Syntax:
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
Drop Table:

DROP TABLE statement is used to remove a table definition and all the data,
indexes, triggers, constraints and permission specifications for that table.

Syntax:
DROP TABLE table_name;
THANK YOU
Oracle Installation
Install Oracle 11g from the internet.
Oracle Installation
Oracle Installation
Oracle Installation
Oracle Installation
Oracle Installation
Oracle Installation
Oracle Installation
Oracle Installation
1 CREATE TABLE student
2 {
3 student_id number(10) NOT NULL,
4 student_name varchar2(50) NOT NULL,
5 student_city varchar2(50)
6 };
7 INSERT into student VALUES(101, 'ABC', 'Coimbatore');
8 select * from student;
9
10
11
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

Table is created
1 CREATE TABLE student
2 {
3 student_id number(10) NOT NULL,
4 student_name varchar2(50) NOT NULL,
5 student_city varchar2(50)
6 };
7 INSERT into student VALUES(101, 'ABC', 'Coimbatore');
8 select * from student;
9
10
11
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

1 row is inserted
1 CREATE TABLE student
2 {
3 student_id number(10) NOT NULL,
4 student_name varchar2(50) NOT NULL,
5 student_city varchar2(50)
6 };
7 INSERT into student VALUES(101, 'ABC', 'Coimbatore');
8 select * from student;
9
10
11
12
13
14
15
16
17
18
19
20
21
22
OUTPUT

STUDENT_ID STUDENT_NAME STUDENT_CITY


101 ABC Coimbatore
THANK YOU
GUI
• GUI stands for Graphical User Interface.

• It refers to an interface that allows one to interact with electronic


devices like computers and tablets through graphic elements.
Typical Elements:

• Input controls such as buttons, dropdown lists, checkboxes, and text


fields.

• Informational elements such as labels, banners, icons, or notification


dialogs.

• Navigational elements, including sidebars, breadcrumbs, and menus.


Real time example:
Real time example:
Packages:

• java.awt
• java.awt.event
• javax.swing
Class Hierarchy:
java.lang.Object

Java.awt.component

Java.awt.container
Javax.swing.jComponent

Java.awt.Panel Javax.awt.Window Javax.swing.JTextCompo Javax.swing.JAbstr


nent actButton
Java.applet.Applet Javax.awt.Frame
etc..
Javax.swing.JTextField Javax.swing.JTextArea
Javax.swing.JApplet Javax.swing.JFrame
Javax.swing.JButton
Javax.swing.Jpanel Java.swing.JLabel
Commonly Used Classes:

➢ javax.swing.Jlabel

➢ javax.swing.Jbutton

➢ javax.swing.JTextField

➢ javax.swing.JTextArea

➢ javax.swing.JFrame

➢ java.awt.Container
Event Handling in java GUIs:

➢ java.awt.event.ActionListener
➢ java.awt.event.MouseListener
➢ java.awt.event.MouseMotionListener
AWT:

• Java AWT (Abstract Window Toolkit) is an API to develop GUI or


window-based applications in java.
• Java AWT components are platform-dependent i.e. components are
displayed according to the view of operating system. AWT is
heavyweight .
Swing:

• Java Swing tutorial is a part of Java Foundation Classes (JFC) that


is used to create window-based applications. It is built on the top of AWT
(Abstract Windowing Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and
lightweight components.
MCQ
Question 01
Which is the container that doesn't contain title bar and MenuBars but it
can have other components like button, textfield etc?

A) Window
B) Frame
C) Panel
D) Container
Question 02
Which method is used to set the graphics current color to the specified
color in the graphics class?

A) public abstract void setFont(Font font)


B) public abstract void setColor(Color c)
C) public abstract void drawString(String str, int x, int y)
D) None of the above
Question 03
Which is used to store data and partial results, as well as to perform
dynamic linking, return values for methods, and dispatch exceptions?

A) Window
B) Panel
C) Container
D) Frame
Question 04
The Swing Component classes that are used in Encapsulates a mutually
exclusive set of buttons?

A) AbstractButton
B) ButtonGroup
C) ImageIcon
D) JButton
Question 05
Which package provides many event classes and Listener interfaces for
event handling?

A) java.awt
B) java.awt.Graphics
C) java.awt.event
D) None of the above mentioned
THANK YOU
JDBC
• JDBC is an acronym for Java Database Connectivity. It’s an advancement
for ODBC ( Open Database Connectivity ).
• JDBC is an standard API specification developed in order to move data
from frontend to backend.
• This API consists of classes and interfaces written in Java.
Functions
• Connect to a data source, like a database.
• Send queries and update statements to the database.
• Retrieve and process the results received from the database in answer to
your query.
Types
• JDBC-ODBC Bridge Driver
• Native Driver
• Network Protocol Driver
• Thin Driver
Java Application

JDBC
Database
Advance Features
• Connection Management.
• Auto loading of Driver Interface.
• Better exception handling.
• Support for large object.
• Annotation in SQL query.
Classes of JDBC
• DriverManager class
• Blob class
• Clob class
• Types class
JDBC-ODBC bridge
• The JDBC-ODBC bridge driver uses ODBC driver to connect to the
database.
• It converts JDBC method calls into the ODBC function calls.
JDBC-ODBC bridge
Native ODBC Call

JDBC Call
Native DBMS Specific Call

JDBC- Database
Java App ODBC ODBC Server
Bridge Driver
Driver
JDBC-ODBC bridge
Advantages:
• easy to use.
• can be easily connected to any database.
Disadvantages:
• Performance degraded because JDBC method call is converted into the
ODBC function calls.
• The ODBC driver needs to be installed on the client machine.
Native-API driver
• The Native API driver uses the client-side libraries of the database.
• The driver converts JDBC method calls into native calls of the database
API.
• It is not written entirely in java.
Native-API driver
JDBC Call Native Call

Native Database
Java App
API Server
Driver
Native-API driver
Advantages:
• faster as compared to JDBC- ODBC Bridge Driver.
• Contains additional features.
Disadvantages:
• Requires native library.
• Increased cost of Application.
Network Protocol driver
• The Network Protocol driver uses middleware (application server) that
converts JDBC calls directly or indirectly into the vendor-specific database
protocol.
• It is fully written in java.
Network Protocol driver
Server Specific Call

Middleware
JDBC Call
Server Native DBMS Call

Network Server Database


Java App
Protocol Driver Server
Driver
Network Protocol driver
Advantages:
• Does not require any native library to be installed.
• Database Independency.
• Provide facility to switch over from one database to another database.
Disadvantages:
• Slow due to increase number of network call.
Thin Driver
• This is Driver called Pure Java Driver because.
• This driver interact directly with database.
• It does not require any native database library, that is why it is also known
as Thin Driver.
Thin Driver
• This is Driver called Pure Java Driver because.
• This driver interact directly with database.
• It does not require any native database library, that is why it is also known
as Thin Driver.
Thin Driver
JDBC Call DB Specific Call

Database
Java App Thin Server
Driver
Thin Driver
Advantages:
• Better performance than all other drivers.
• No software is required at client side or server side.
Disadvantages:
• Drivers depend on the Database.
THANK YOU
Basic steps to use a database in Java
• Establish a connection
• Create JDBC Statements
• Execute SQL Statements
• GET ResultSet
• Close connections
Driver Manager
JDBC Driver :
Is a set of classes and interfaces, written according to JDBC API to
communicate with a database.
Driver Manager
The JDBC API defines a set of interfaces that encapsulate major database
functionality like
• Running queries
• Processing results
• Determining configuration information
Driver Manager
• The DriverManager class acts as an interface between user and drivers
Methods of DriverManager class:
1. public static void registerDriver(Driver driver)
2. public static void registerDriver(Driver driver)
3. public static Connection getConnection(String url)
4. public static Connection getConnection(String url,String userName,String
password)
Establish a connection
import java.sql.*;

Load the vendor specific driver :

Class.forName("oracle.jdbc.driver.OracleDriver");

What do you think this statement does, and how?

- Dynamically loads a driver class, for Oracle database


Connection
Connect Register the driver

Query Connect to the database

Process
results

Close
Establish a connection
Make the connection :

Connection con = DriverManager.getConnection(


"jdbc:oracle:thin:@oracle-prod:1521:OPROD", username, passwd);

What do you think this statement does?

- Establishes connection to database by obtaining a Connection


object
URL represents a protocol to connect to
the database
About JDBC URL
A JDBC driver uses a JDBC URL to identify and connect to a particular
database.

These URLs are generally of the form:

jdbc:<subprotocol>:<subname>

or

jdbc:driver:databasename
About JDBC URL
For example, the Oracle JDBC-Thin driver uses a URL of the form:

jdbc:oracle:thin:@site:port:database

while the JDBC-ODBC Bridge uses:

jdbc:odbc:datasource:odbcoptions

The only requirement is that a driver be able to recognize


its own URLs
Host Details
• You should be aware of the IP address of the system or the host name,
from where Oracle Database is being accessed.
• If your Oracle database is running on the same system, where you are
executing your jdbc program, then you can use @localhost (in place of the
IP address), in your JDBC URL

jdbc:oracle:thin:@localhost
Service Name and Port No.
You should be aware of the service name and port no. on which oracle
service is running :
Service Name and Port No.
• Find the service name and the port no. of the database that you want to
connect, by opening a file called tnsnames.ora
• This file will be found within one of the subdirectories of Oracle
installation directory. You will have to look for a folder called app, which
contains files and folders related to Oracle Software. In one of the sub-
directories in this hierarchy, ADMIN, you will find tnsnames.ora file
• For e.g. in my machine, tnsnames.ora is found within the following path :
E:\app\harb\product\11.1.0\db_1\NETWORK\ADMIN
Statement
Connect Create a statement

Query Query the database

Process
results

Close
The Statement Object
To execute SQL statements use Statement Object.
• You need an active connection to create a JDBC statement
• Statement object has three methods to execute a SQL statements:
➢ executeQuery() for SELECT statements
➢ executeUpdate()for INSERT, UPDATE, DELETE, or DDLstatements
➢ execute() for either type of statement
How to Query the Database?
To execute SQL statement , we should first create Statement
object, as:

Statement stmt = conn.createStatement();

To execute the query on the database :

ResultSet rset = stmt.executeQuery(statement);


int count = stmt.executeUpdate(statement);
boolean isquery = stmt.execute(statement);
Result Set
Connect

Query Step through the results

Process Assign results to Java


results variables

Close
The ResultSet Object
• ResultSet is an object that contains the results of executing a SQL
statement

• A ResultSet maintains a cursor pointing to its current row of


data

• Use next() to step through the result set row by row

• To retrieve the data from the columns, we can use getXXX() method
The ResultSet Object
• The ResultSet.next() method moves the cursor to the next row in the
ResultSet object.
• The general form of a result set is a table with column headings and the
corresponding values returned by a query.
How to Process the Result?
while (rset.next()) { ... }

String val = String val =


rset.getString(colname); rset.getString(colIndex);

while (rset.next()) {
String name = rset.getString(“NAME");
String supervisor =
rset.getString(“SUPERVISOR");
... // Process or display the data
}
How to Process the Result?
• A ResultSet object maintains a cursor, which points to its current row of
data.
• The cursor moves down one row each time the method next is called.
When a ResultSet object is first created, the cursor is positioned before
the first row, so the first call to the next method puts the cursor on the
first row, making it the current row.
• ResultSet rows can be retrieved in sequence from top to bottom as the
cursor moves down one row with each successive call to the method
next.
Get ResultSet
ResultSet rs = Stmt.executeQuery(query);
//What does this statement do?

while (rs.next()) {
int ssn = rs.getInt("SSN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
}
Close connection
• stmt.close();
• con.close();

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1
521:xe","system","oracle");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp765");
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}}
Question 1
Which one of the following statements is used to register the
jdbc driver

A) Claas.Forname(“oracle.jdbc.driver.OracleDriver”);

B) Class.forName(“oracle.jdbc.driver.OracleDriver”);

C) class.forname(“oracle.jdbc.driver.OracleDriver”);

D) Class.ForName(“oracle.jdbc.driver.OracleDriver”);
Question 2
Which is the correct syntax for creating the Connection object

A) Connection.getConnection(URL, username, password);

B) Connection.createConnection(URL, username, password);

C) DriverManager.createConnection(URL, username, password);

D) DriverManager.getConnection(URL, username, password);


THANK YOU
Prepared Statement
• Using PreparedStatement in place of Statement interface will improve the
performance of a JDBC program

• PreparedStatement is inherited from Statement; the difference is that a


PreparedStatement holds precompiled SQL statements
Prepared Statement
• If you execute a Statement object many times, its SQL statement is
compiled each time. PreparedStatement is more efficient because its SQL
statement is compiled only once, when you first prepare the
PreparedStatement.

• After that, each time you execute the SQL statement in the
PreparedStatement, the SQL statement does not have to be recompiled
PreparedStatement Object
PreparedStatement Parameters
• A PreparedStatement does not have to execute exactly the same
• query each time. You can specify parameters in the
PreparedStatement SQL string and supply the actual values for these
• parameters when the statement is executed.
• The following slide shows how to supply parameters and execute a
PreparedStatement.
How to Create a PreparedStatement?
1. Register the driver and create the database connection
2. Create the prepared statement,
- identifying variables witha question mark (?)
How to Create a PreparedStatement?
PreparedStatement pstmt =
conn.prepareStatement("update STUDENT
set SUPERVISOR = ? where ID = ?");

PreparedStatement pstmt =
conn.prepareStatement("select SUPERVISOR from
STUDENT where ID = ?");
How to execute PreparedStatement?
Supply values for the variables

pstmt.setXXX(index, valu);

Specifying Values for the Bind Variables


You use the PreparedStatement.setXXX() methods to supply values for the
variables in a prepared statement. There is one setXXX() method for each
Java type: setString(), setInt(), and so on.
How to execute PreparedStatement?
Execute the statement

pstmt.executeQuery();
pstmt.executeUpdate();
1 //Example 1 on PreparedStatement
2
3 /* This class is executed in the following manner :
4
5 if you want to create the table, you will execute as java JCreate table1
6 where table1 is the name of the table. The table table1 is created with the
7
8 following columns empid, empname, dept, joindate, salary */
9 import java.sql.*;
10
11 class JCreate {
12 public static void main(String args[]) throws SQLException {
13
14 JdbcCalls e = new JdbcCalls();
15 e.create(args);
16
17 }
18 }
19
20
21
22
1 import java.sql.*;
2 class ConnectionClass {
3 Connection con;
4 Connection connectionFactory()
5 {
6 try {
7 Class.forName("oracle.jdbc.driver.OracleDriver");
8 con=DriverManager.getConnection("Jdbc:Oracle:thin:
9 @localhost:1521:ORCL","scott","tiger");
10 }
11 catch(Exception e)
12 {
13 System.out.println(e);
14 }
15 return con;
16 }
17 }
18
19
20
21
22
1 class JdbcCalls {
2 Connection con;
3 JdbcCalls()
4 {
5 ConnectionClass x = new ConnectionClass();
6 con=x.connectionFactory();
7 }
8 void create(String[] args) throws SQLException
9 {
10 String tablename = args[0];
11 PreparedStatement pst = con.prepareStatement("Create
12 table"+tablename+" (empid number(4), empname varchar(20),
13 dept varchar2(10), joindate date, salary number(10,2))");
14 pst.executeUpdate();
15 System.out.println(“Table created successfully”);
16 }
17 }
18
19
20
21
22
Example 1 on PreparedStatement
(Contd..)
Example 1 on PreparedStatement
(Contd..)
1 //Example 2 on PreparedStatement
2 /* This class is executed in the following manner :
3 If you want to insert a row within the table, you will execute as
4 java JInsert jdbcdemotable 1001 anish admin 23-dec-2008 50000.00 */
5 import java.sql.*;
6 class JInsert {
7 public static void main(String args[]){
8 try {
9 JdbcCalls e = new JdbcCalls();
10 e.insert(args);
11 }
12 catch(SQLException e){
13 System.out.println(e.toString());
14 }
15 }
16 }
17 class JdbcCalls {
18 Connection con;
19 JdbcCalls() {
20 ConnectionClass x = new ConnectionClass();
21 con = x.connectionFactory();
22 }
1 void insert(String[] args) throws SQLException {
2 String tablename = args[0];
3 int empid = Integer.parseInt(args[1]);
4 String empname = args[2];
5 String dept = args[3];
6 String dat=args[4];
7 Float salary = Float.parseFloat(args[5]);
8 PreparedStatement pst = con.prepareStatement("insert into
9 "+tablename+" values(?,?,?,?,?)");
10 pst.setInt(1, empid);
11 pst.setString(2, empname);
12 pst.setString(3, dept);
13 pst.setString(4, dat);
14 pst.setFloat(5, salary);
15 pst.executeUpdate();
16 System.out.println(“Record inserted successfully”);
17 }
18
19
20
21
22
Example 2 on PreparedStatement
(Contd.).
Example 2 on PreparedStatement
(Contd.).
ResultSetMetaData Object
• ResultSetMetaData is an interface which contains methods to
get information about the types and properties of the columns
in the ResultSet object

• ResultSetMetaData object provides metadata, including:


• Number of columns in the result set
• Column type
• Column name
How to obtain ResultSetMetadata?
1. To get the ResultSetMetaData object

ResultSetMetaData rsmd = rset.getMetaData();

2. Use the object’s methods to get the metadata

ResultSetMetaData rsmd = rset.getMetaData();


for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String colname = rsmd.getColumnName(i);
int coltype = rsmd.getColumnType(i);
...
}
1 //Example on ResultSetMetaData
2
3 import java.sql.*;
4 class MakeConnection4
5 {
6 Connection conn;
7 Statement stmt;
8 ResultSet rs;
9 ResultSetMetaData rsmd;
10 MakeConnection4()
11 {
12 try{
13 Class.forName("oracle.jdbc.driver.OracleDriver");
14 conn = DriverManager.getConnection("Jdbc:Oracle:thin:
15 @localhost:1521:orcl","scott","tiger");
16 stmt = conn.createStatement();
17 rs = stmt.executeQuery("Select * from emp");
18
19
20
21
22
1 rsmd = rs.getMetaData();
2 int noc = rsmd.getColumnCount();
3 System.out.println("Number Of Columns : "+noc);
4 for(int i=1;i<=noc;i++){
5 System.out.print("Column "+i+"
6 ="+rsmd.getColumnName(i)+"; ");
7 System.out.print("Column Type =
8 "+rsmd.getColumnType(i)+"; ");
9 System.out.println("Column Type Name =
10 "+rsmd.getColumnTypeName(i)+";");
11 }
12 }
13 catch(Exception e){
14 e.printStackTrace();
15 }
16 }
17 }
18 public class RSMetaDataExample {
19 public static void main(String args[]) {
20 new MakeConnection4();
21 }
22 }
Example on ResultSetMetaData (Contd.).
DatabaseMetaData Object
To know which type of driver we are using and whether is it
compatable or JDBC complaint or not. It is used to know all details
about database provider as well.

Obtaining a DatabaseMetaData Instance

DatabaseMetaData databaseMetaData = connection.getMetaData();


DatabaseMetaData Object
Database Product Name and Version

int majorVersion = databaseMetaData.getDatabaseMajorVersion();


int minorVersion = databaseMetaData.getDatabaseMinorVersion();
String productName = databaseMetaData.getDatabaseProductName();
String productVersion = databaseMetaData.getDatabaseProductVersion();

Database Driver Version

int driverMajorVersion = databaseMetaData.getDriverMajorVersion();


int driverMinorVersion = databaseMetaData.getDriverMinorVersion();
1 //Example on DatabaseMetaData
2
3 import java.sql.Connection;
4 import java.sql.DatabaseMetaData;
5 import java.sql.DriverManager;
6 import java.sql.SQLException;
7 class Dbmd{
8 public static void main(String args[]){
9 try{
10 Class.forName("oracle.jdbc.driver.OracleDriver");
11 Connection con = DriverManager.getConnection
12 ("jdbc:oracle:thin:@localhost:1521:
13 xe","system","oracle");
14 DatabaseMetaData dbmd = con.getMetaData();
15 System.out.println("Driver Name: "+dbmd.getDriverName());
16 System.out.println("Driver Version: "+
17 dbmd.getDriverVersion());
18 System.out.println("UserName: "+dbmd.getUserName());
19
20
21
22
1 System.out.println("Database Product Name: "+
2 dbmd.getDatabaseProductName());
3 System.out.println("Database Product Version: "+
4 dbmd.getDatabaseProductVersion());
5
6 con.close();
7 }
8 catch(Exception e){
9 System.out.println(e);
10 }
11 }
12 }
13
14
15
16
17
18
19
20
21
22
Example on DatabaseMetaData (Contd.).

Result :

Output:Driver Name: Oracle JDBC Driver


Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production
THANK YOU

You might also like