Cat 2 STS
Cat 2 STS
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?
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
If the length of the string is > 2 then call user defined function splitString()
and print the split string along with index.
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.
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.
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.
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
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.
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:
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
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
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.
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.
Java Program
Java Compiler
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
• 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
• 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
D) Compilation error
Question 2
What is not the advantage of Reflection?
A) obj.getClass().getDeclaredMethod()
B) obj.getClass().getDeclaredField()
C) obj.getClass().getMethod()
D) obj.getClass().getObject()
THANK YOU
SQL:
➢ 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 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
➢ DML statements are used for managing data with in schema objects
Procedural DML’s
Declerative DML’s
TCL
➢ 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
Syntax:
CREATE DATABASE DatabaseName;
DROP DATABASE:
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
• java.awt
• java.awt.event
• javax.swing
Class Hierarchy:
java.lang.Object
Java.awt.component
Java.awt.container
Javax.swing.jComponent
➢ 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:
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) 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
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.*;
Class.forName("oracle.jdbc.driver.OracleDriver");
Process
results
Close
Establish a connection
Make the connection :
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
jdbc:odbc:datasource:odbcoptions
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
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:
Close
The ResultSet Object
• ResultSet is an object that contains the results of executing a SQL
statement
• 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()) { ... }
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
• 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);
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
Result :