Java Programming Exercises With Solutions PDF

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 44

https://masterprogramming.

in/

Index
Q .no. Questions Page no. Remark
1 Write a program that implement the concept of Encapsulation. 03-04
Write a program to demonstrate the concept of function overloading of
2
Polymorphism.
05-06

Write a program to demonstrate concept of construction overloading of


3
Polymorphism.
07-08

Write a program the use Boolean data type and print the prime number
4
series up to 50.
09

Write a program to print first 10 number of the following Series


5
using Do-while Loops 0,1,1,2,3,5,8,11..
10

6 Write a program to check the given number is Armstrong or not 11-12


7 Write a program to find the factorial of any given number. 13
Write a program to sort the element of One Dimensional Array in
8 14
Ascending order
9 Write a program for matrix multiplication using input/output Stream. 15-16
10 Write a program for matrix addition using input/output Stream. 17-18
11 Write a program for matrix transpose using input/output stream class. 19-20
Write a program to add the element of Vectors as arguments of main
12
method(Run time ) and rearrange them, and copy it into an array.
21-22

13 Write a program to check that the given String is palindrome or not. 23-24
14 Write a program to arrange the String in alphabetical order. 25-26
Write a program for StringBuffer class which perform the all methods
15 27-28
of that class.
16 Write a program to calculate Simple interest using the Wrapper class. 29
Write a program to calculate Area of various geometrical figures using
17 30-31
the abstract class.
Write a program where Single class implements more than one
18 interfaces and with help of interface reference variable user call the 32-33
methods.
WAP that use the multiple catch statements within the try-catch
19
mechanism.
34

WAP where user will create a self- Exception using the “throw”
20 35
keyword.
Write a program for multithread using is Alive(), join() and
21
synchronized() methods of thread class
36-37

Write a program to create a package using command and one package


22
will import another package.
38-39

Write a program for JDBC to insert the values into the existing table by
23 40-41
using prepared statement.
WAP for JDBC to display the records from the existing table.
24 42-43
25 WAP for demonstrate of switch statement ,continue and break. 44-45

1
https://masterprogramming.in/

Q1) Write a program that implement the concept of Encapsulation.


Ans :-

// Java program to demonstrate encapsulation


class Encapsulate {
// private variables declared
// these can only be accessed by public methods of class
private String Name;
private int Roll;
private int Age;

// get methods for age, name and roll


//to access private variables
public int getAge() { return Age; }
public String getName() { return Name; }
public int getRoll() { return Roll; }

// set methods for age, name and roll


//to access private variable Age
public void setAge(int newAge) { Age = newAge; }
public void setName(String newName) { Name = newName; }
public void setRoll(int newRoll) { Roll = newRoll; }
}

public class TestEncapsulation {


public static void main(String[] args)
{ Encapsulate obj = new Encapsulate();
// setting values of the variables
obj.setName("manish");
obj.setAge(21);
obj.setRoll(5527);

// Displaying values of the variables


System.out.println("Student's name: " +
obj.getName());
System.out.println("Student's age: " + obj.getAge());
System.out.println("Student's roll: " +
obj.getRoll());

// Direct access of Roll is not possible


// due to encapsulation
// System.out.println("Student's roll: " + obj.Name);
}
}
Output :-

2
https://masterprogramming.in/

Figure 1

3
https://masterprogramming.in/

Q2) Write a program to demonstrate the concept of function overloading


of Polymorphism.

Ans :-

// Java program to demonstrate concept of function overloading of


Polymorphism
class Adder{
//Method Overloading: changing no. of arguments
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}

//Method Overloading: changing data type of arguments


static double add(double a, double b){return a+b;}

static String add(String a, String b)


{String str = "Four"; return str; }

//Method Overloading: Sequence of data type of arguments


static void disp(String c, int num)
{System.out.println(c +" "+ num);}

static void disp(int num, String c)


{System.out.println(num +" "+ c);}
}
class TestOverloading{
public static void main(String[] args){
//Method Overloading: changing no. of arguments
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));

//Method Overloading: changing data type of arguments


System.out.println(Adder.add(12.3,12.6));
System.out.println(Adder.add("One","Three"));

//Method Overloading: Sequence of data type of


arguments Adder.disp("manish",5527);
Adder.disp(9399,"hello");
}
}

4
https://masterprogramming.in/

Output:

5
https://masterprogramming.in/

Q3) Write a program to demonstrate concept of construction


overloading of Polymorphism.

Ans :-

// Java program to illustrate Constructor Overloading


class Box
{ double width, height, depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{ width = w; height = h; depth = d; }

// constructor used when no dimensions specified Box()


{width = height = depth = 0;}

// constructor used when cube is created


Box(double len){width = height = depth = len;}

// compute and return volume


double volume() {return width * height * depth;}
}
public class Test
{ public static void main(String args[])
{ // create boxes using the various constructors
Box mybox1 = new Box(12, 21, 13);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
}
}

6
https://masterprogramming.in/

Output:-

7
https://masterprogramming.in/

Q4) Write a program the use Boolean data type and print the prime
number series up to 50.

Ans :-

// Java program to print the prime number series up to 50


public class PrimeNumber
{
public static void main(String []args)
{
int num=50,i;

System.out.println("\n Prime numbers upto 50 :\n");


for(i=2;i<=num;i++)
{
boolean a=true;
for(int j=2;j<=i-1;j++)
{
if(i%j==0)
{ a=false;
break;
}
}
if(a==true)
{ System.out.print(" "+i);
}
}
System.out.println();
}
}

Output:-

8
https://masterprogramming.in/

Q5) Write a program to print first 10 number of the following Series


using Do-while Loops 0,1,1,2,3,5,8,11.

Ans :-

// Java program to print the Fibonacci number series up to 50


public class Fibonacci
{
public static void main(String []args)
{
// Function to print N Fibonacci Number
int N=10,b=-1,c=1,sum,i=1;

do
{
sum=b+c;
System.out.print(" "+sum);
// Swap
b=c;
c=sum;
i++;
}
// Iterate till i is N
while(i<=N);

System.out.println();
}
}

Output:-

9
https://

Q6) Write a program to check the given number is Armstrong or not.

Ans :-

// Java program to find Nth Armstrong Number


import java.util.Scanner;
public class Armstrong
{
public static void main(String []args)
{ int n,sum=0,count=0;

Scanner input= new Scanner(System.in); System.out.print("\


nEnter a number to check Armstrong or not : ");
int number =input.nextInt();
int num=number;
// Find total digits in num
while(num!=0)
{ num=num/10;
count++;
}
//Copy the value for number in num
num=number;

// Calculate sum of power of digits


while (num != 0)
{ n=num%10; sum=sum+
(int)Math.pow(n,count);
num=num/10;
}
if (number == sum )
System.out.println("\n"+number + " is an Armstrong
number ");
else
System.out.println("\n"+number + " is not an
Armstrong number ");
}
}

1
https://
Output:-

1
https://

Q7) Writea program to find the factorial of any given number.

Ans :-

// Java program to find factorial of given number


import java.util.Scanner;
class Test
{
// Method to find factorial of given number
static int factorial(int n)
{
int res = 1, i;
for (i=2; i<=n; i++)
res *= i;
return res;
}

// Driver method
public static void main(String[] args)
{
Scanner input=new Scanner(System.in); System.out.print("\
nEnter a number to find factorial : "); int
num=input.nextInt();

System.out.println("Factorial of "+ num + " is " +


factorial(num));
}
}

Output:-

1
https://

Q8) Write a program to sort the element of One Dimensional Array in


Ascending order
Ans :-

// Java Program to Sort Array of Integers using Arrays.sort() Method


import java.util.Scanner;
import java.util.Arrays;

public class ArraySort{

public static void main(String args[]){

int []arr = new int[7];


Scanner enter = new Scanner(System.in);
System.out.println("\nPlease! Enter 7 numbers to perform
sorting:");
for(int i=0; i<arr.length; i++)
{
arr[i]=enter.nextInt();
}

// Applying sort() method over to above array


// by passing the array as an argument
Arrays.sort(arr);

System.out.println("\nSorting in Ascending order :\n");


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

Output:-

1
https://

Q9) Write a program for matrix multiplication using input/output Stream.


Ans :-

// Java Program for matrix multiplication using input/output Stream


import java.util.Scanner;
public class MatrixMultiplication{
public static void main(String []args)
{
Scanner input=new Scanner(System.in);
System.out.print("Enter number of rows : ");
int r=input.nextInt();
System.out.print("Enter number of columns : ");
int c=input.nextInt();

if(r!=c)
{
System.out.println("\nSorry! matrix multiplication cannot
be performed..!");
System.exit(0);
}
else
{ int m1[][]=new int[r][c];
int m2[][]=new int[r][c];
int m3[][]=new int[r][c];
int sum;

System.out.println("Enter the elements of First


matrix row wise: ");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{ m1[i][j]=input.nextInt();
}
}

System.out.println("Enter the elements of second


matrix row wise: ");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{ m2[i][j]=input.nextInt();
}
}

for(int i=0;i<r;i++)
{

1
https://
for(int j=0;j<c;j++)
{ sum=0;

for(int k=0;k<r;k++)
{ sum=sum + m1[i][k]*m2[k][j];
}
m3[i][j]=sum;
}

System.out.println("Product of two matrices : ");


for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(" "+ m3[i][j]);
}
System.out.println();
}
input.close();
}

}
}

Output:-

1
https://

Q10) Write a program for matrix addition using input/output Stream.

Ans :-

// Java Program for matrix addition using input/output Stream


import java.util.Scanner;
public class MatrixAddition{
public static void main(String []args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter number of rows : ");
int r=input.nextInt();
System.out.println("Enter number of columns : ");
int c=input.nextInt();

int m1[][]=new int[r][c];


int m2[][]=new int[r][c];
int m3[][]=new int[r][c];

System.out.println("Enter the elements of First matrix


row wise:");
for(int i=0;i<r;i++)
{ for(int j=0;j<c;j++)
{
m1[i][j]=input.nextInt();
}
}

System.out.println("Enter the elements of second matrix


row wise:");

for(int i=0;i<r;i++)
{ for(int j=0;j<c;j++)
{
m2[i][j]=input.nextInt();
}
}
for(int i=0;i<r;i++)
{ for(int j=0;j<c;j++)
{
m3[i][j]=m1[i][j]+m2[i][j];
}
}

System.out.println("Sum of two matrices : ");

1
https://
for(int i=0;i<r;i++)
{ for(int j=0;j<c;j++)
{
System.out.print(" " +m3[i][j]);
}
System.out.println();
}
input.close();
}
}

Output: -

1
https://

Q11) write a program for matrix transpose using input/output stream


class.

Ans :-
// Java Program for matrix transpose using input/output stream class.
import java.util.Scanner;
public class MatrixTranspose{
public static void main(String[] args)
{ Scanner input = new
Scanner(System.in); int original[][]=new
int[3][3] ;
System.out.println("Enter the elements of matrix: ");
for(int row = 0; row<3; row++)
{
for(int col = 0; col<3; col++)
{ original[row][col] = input.nextInt();
}
}
int transpose[ ][ ] = new int[3][3];
for(int row = 0; row<3; row++)
{
for(int col = 0; col<3; col++)
{
transpose[row][col] = original[col][row];
}
}
System.out.println("Transpose of matrix : \n");
for(int row = 0; row<3; row++)
{ for(int col = 0; col<3; col++)
{
System.out.print(" "+ transpose[row][col] );
}
System.out.print("\n");
}
}
}

1
https://
Output:-

1
https://

Q12) Write a program to add the element of Vectors as arguments of main


method(Run time ) and rearrange them, and copy it into an array.

Ans :-

// Java Program to Demonstrate Working of Vector via Creating and


Using It
// Importing required classes
import java.io.*;
import java.util.*;
class VectorExample{
public static void main(String[] args)
{ // Size of the Vector
int n = 5;
Scanner input = new Scanner(System.in);
// Declaring the Vector with initial size n
Vector<Integer> list = new Vector<Integer>(n);

// Appending new elements at the end of the vector


try{ for(int i=0;i<5;i++)
list.add(Integer.parseInt(args[i]));

// Printing elements of list System.out.println("\


n"+list);

// Remove element at index 3


list.remove(3);

//Displaying the vector after deletion


System.out.println(list);

// iterating over vector elements usign for loop


System.out.println("Printing the list using list.get() --
---");
for (int i = 0; i<list.size(); i++)
// Printing elements one by one
System.out.print(" "+list.get(i));

// Creating the array and using toArray()


Object[] arr = list.toArray();
System.out.println("\nPrinting the list using Array() ---
--");
for (int i = 0; i<arr.length; i++)
System.out.print(" "+arr[i]);
System.out.println();

2
https://
}
catch(Exception e)
{ System.out.println("\nProgram ended...............");
System.out.println("Exception : "+e.getMessage());
}
}
}

Output:-

2
https://

Q13) write a program to check that the given String is palindrome or not.

Ans :-

// Java Program to check that the given String is palindrome or not.


import java.util.Scanner;
public class Palindrome{
// Function that returns true if str is a palindrome
static boolean isPalindrome(String str)
{
// Pointers pointing to the beginning and the end of the string
int i = 0, j = str.length() - 1;

// While there are characters to compare


while (i < j)
{
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;

// Increment first pointer and decrement the other


i++; j--;
}
// Given string is a palindrome
return true;
}

public static void main(String[] args)


{
Scanner input= new Scanner(System.in);
System.out.print("\nEnter a string to check : ");
String str=input.nextLine();

if (isPalindrome(str))
System.out.println(str + " is a palindrome.");
else
System.out.println(str + " is not a
palindrome.");
}
}

2
https://
Output:-

2
https://

Q14) write a program to arrange the String in alphabetical order.

Ans :-

// Java Program to arrange the String in alphabetical order


import java.util.Scanner;
public class StringArrange{
public static void main(String[] args)
{ int count;
String temp;
Scanner scan = new Scanner(System.in);

//User will be asked to enter the count of strings


System.out.print("\nEnter number of strings you
would like to enter:");
count = scan.nextInt();

String str[] = new String[count];


Scanner scan2 = new Scanner(System.in);

//User is entering the strings and they are stored


in an array
System.out.println("Enter the Strings one by one:");
for(int i = 0; i < count; i++)
{
str[i] = scan2.nextLine();
}
scan.close();
scan2.close();

//Sorting the strings


for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++)
{
if (str[i].compareTo(str[j])>0)
{ temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
//Displaying the strings after sorting them based on
alphabetical order
System.out.println("\nStrings in Sorted Order : ");

2
https://
for (int i = 0; i <= count - 1; i++)
{
System.out.print(str[i] + ", ");
}
System.out.println();
}
}

Output:-

2
https://

Q15) write a program for StringBuffer class which perform the all methods
of that class.

Ans :-

// Java Program for StringBuffer class which perform the all methods
of that class
import java.util.*;
public class StringBufferExample{

public static void main(String args[]){

//initialized StringBuffer object


StringBuffer sb = new StringBuffer("Good
Morning...");
System.out.println("\n"+sb);
//append to String1
sb.append(" Hello!!");
//prints "Good Morning... Hello!!" after appending
System.out.println(sb);
//insert Namste!! with begining position 0
sb.insert(0,"Namste!! ");
//prints "Namste!! Good Morning... Hello!!"
System.out.println(sb);
// replace Morning with Evening
sb.replace(13,20," Evening");
//prints "Namste!! Good Morning... Hello!!"
System.out.println(sb);
//delete string begining with position 0 to 3
sb.delete(0,8);
//prints "Good Morning... Hello!!"
System.out.println(sb);
//StringBuffer reverse() Method
sb.reverse();
System.out.println(sb);
//prints capacity of buffer
System.out.println("capacity of buffer is: " +
sb.capacity());
}
}

2
https://
Output:-

2
https://

Q16) write a program to calculate Simple interest using the Wrapper class.

Ans :-

// Java Program to calculate Simple interest using the Wrapper class.


import java.util.Scanner;
class SimpleInterest{

public static void main(String args[])

{ int principleAmount, rate, time

,si;
Scanner input = new Scanner(System.in);

System.out.print("\nEnter principle amount : ");


String p = input.nextLine();

System.out.print("Enter rate : ");


String r = input.nextLine();

System.out.print("Enter time : ");


String t = input.nextLine();

principleAmount = Integer.parseInt(p);
rate = Integer.parseInt(r);
time = Integer.parseInt(t);

si = (principleAmount * rate * time )/100;


System.out.println("Simple Interest is : " + si );
}
}

Output:-

2
https://

Q17) write a program to calculate Area of various geometrical figures


using the abstract class.

Ans :-

// Java Program to calculate Simple interest using the Wrapper class.


import java.util.*;
//abstract class
abstract class Shape{
//abstract method declaration, Abstract method (does not
have a body)
abstract public void areaCalcultion();
abstract public void readData();
}

class Rectangle extends


Shape{ private int a,b;
//method overriding
public void readData(){
System.out.print("\n\nEnter two sides of Rectangle : ");
Scanner sidein = new Scanner(System.in);
a = sidein.nextInt();
b = sidein.nextInt();
}
public void areaCalcultion(){
int area;
area = a * b;
System.out.println("Area of Rectangle is : " + area);
System.out.println("\n<--------------------------------------------->");
}
}

class Circle extends


Shape{ private double
radius;
//method overriding
public void readData(){
System.out.print("\nEnter Radius of circle : ");
Scanner radiusin = new Scanner(System.in);
radius= radiusin.nextDouble();
}
public void areaCalcultion(){
double area = (22/7) * radius * radius;
System.out.println("Area of circle is : " + area);
}
}

2
https://

public class AbstractArea{


public static void main(String args[]){
//Reference variable of Shape
Shape s;

s= new Rectangle(); // Creating object of abstract class


s.readData();
s.areaCalcultion();

s=new Circle(); // Creating object of abstract class


s.readData();
s.areaCalcultion();

}
}

Output:-

3
https://

Q18) write a program where Single class implements more than one
interfaces and with help of interface reference variable user call the
methods.
Ans :-

// Java Program to calculate Simple interest using the Wrapper class.


import java.util.*;
//interface
interface CircleArea{
final static float pi = 3.14F;
float compute(float x); //interface method
}
interface RectangleArea{
int calculate(int l,int w); //interface method
}
//Test implements interface CirclArea and RectangleArea
class Test implements CircleArea,RectangleArea
{ //the body of compute provided here
public float compute(float x) { return(pi*x*x); }

//the body of calculate provided here


public int calculate(int l,int w) { return(l*w); }

}
class Interface{

public static void main(String args[])


{ CircleArea cir;
RectangleArea rect;

//Creates a Test object


Test Area = new Test();
cir = Area;
System.out.println("\nArea of circle : "+
cir.compute(49));

rect = Area;
System.out.println("Area of Rectangle : " +
rect.calculate(5,20));

}
}

3
https://
Output:-

3
https://

Q19) write a program that use the multiple catch statements within the try-
catch mechanism.

Ans :-

//Java Program for Multiple Catch Exceptions


public class MultipleCatch {

public static void main(String[] args) {

try
{ int a[]=new int[5];
a[5]=30/0;
}
//Arithmetic Exception occurs
catch(ArithmeticException e)
{
System.out.println("\nArithmetic Exception
occurs");
}
//Array Index Out Of Bounds Exception occurs
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception
occurs");
}
//Other Exception occurs
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Output:-

3
https://

Q20) write a program where user will create a self- Exception using the
“throw” keyword.

Ans :-
//Java Program for user will create a self- Exception using the
“throw” keyword
import java.lang.Exception;
class Throw{
public static void main(String args[])
{ int balance=5000;
int withdrawlAmount=6000;
try
{ if(balance< withdrawlAmount)
{ throw new
ArithmeticException("Insufficient balance");
}
balance=balance-withdrawlAmount;
System.out.println("Transaction successfully
completed");
}
catch(ArithmeticException e)
{ System.out.println("\nException: "+ e.getMessage());
}
finally
{ System.out.println("Program continue...........");
}
}
}

Output:-

3
https://

Q21) write a program for multithread using is Alive(), join() and


synchronized() methods of thread class

Ans :-

//Java Program for multithread using is Alive(), join() and


// synchronized() methods of thread class
class Booking
{ int total_seats=20;

//Synchronized function
synchronized void bookseat(int seats)
{
if(total_seats>=seats)
{ System.out.println("\nSeat Book Successfull...!!");
total_seats=total_seats-seats;
System.out.println("Total seat Left : "+total_seats);
}
else
{ System.out.println("\nSeat cannot be Booked");
System.out.println("Only "+total_seats + "
available");
}
}
}

//Extending thread class


class cutomer extends Thread
{
static Booking b1=new Booking();
int seat;
public void run()
{
try
{ b1.bookseat(seat);
}

catch(NullPointerException e)
{ e.printStackTrace();
}
}
}

public class Synchro


{ public static void main(String[] args)

3
https://
{
cutomer C1=new cutomer();
cutomer C2=new cutomer();
C2.seat=19;
C1.seat=8;

C1.start();
C2.start();
//isAlive() method
System.out.println(C1.isAlive());
try
{
//Thread sleep() and join method
C2.sleep(2000);
C1.join();
}
catch (Exception e)
{
System.out.println("Exception : "+e.getMessage());
}
}
}

Output:-

3
https://

Q22) write a program to create a package using command and one package
will import another package.

Ans :-

//Java Program to create a package using command


// Save by ArithmeticOperations.java and
//compile as > javac –d . ArithmeticOperations.java
package Pack1; //Creating package
import java.util.Scanner;
public class ArithmeticOperations
{ private Scanner input = new Scanner(System.in);
public int Addition(){
int a = input.nextInt();
int b = input.nextInt();
return a+b;
}
public int Subtract(){
int a = input.nextInt();
int b = input.nextInt();
return a-b;
}
public int Multiplication(){
int a = input.nextInt();
int b = input.nextInt();
return a*b;
}
public float Division(){
float a = input.nextFloat();
float b = input.nextFloat();
return a/b;
}
}

3
https://
//Main class and method
//Save by ExamplePackage.java
import Pack1.ArithmeticOperations; //Importing Pack1.
ArithmeticOperations class
class ExamplePackage
{ public static void main(String args[])
{ ArithmeticOperations obj = new ArithmeticOperations();
System.out.print("\nAddition : Enter Two Number - ");
float result = obj.Addition();
System.out.println("Result is :"+result);

System.out.print("\nSubtraction : Enter Two Number - ");


result = obj.Subtract();
System.out.println("Result is :"+ result);

System.out.print("\nMultiplication : Enter Two Number -


");
result = obj.Multiplication();
System.out.println("Result is :"+result);

System.out.print("\nDivision : Enter Two Number - ");


result = obj.Division();
System.out.println("Result is :"+result);
}
}

Output:-

3
https://

Q23) write a program for JDBC to insert the values into the existing table
by using prepared statement.

Ans :-
//Java Program to insert the values into the existing table by using
prepared statement.
import java.io.*;
import java.sql.*;
import java.util.*;
public class Database{
public static void main(String args[])
{ int roll;
String name,city, str;
try{ //step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:
1521:xe","bhupendra","dbms@12"); System.out.println("\
nDatabase connection is done !");

//step3 create the statement object


Statement stmt = con.createStatement();

//step4 execute query


System.out.println("\n<---STUDENT table is selected ---
>");
InputStreamReader input= new InputStreamReader(System.in);

BufferedReader buffer = new BufferedReader(input);

System.out.print("\nEnter rollno : " );


str = buffer.readLine();
roll = Integer.parseInt(str);

System.out.print("Enter name : " );


name = buffer.readLine();

3
https://
System.out.print("Enter Address : " );
city = buffer.readLine();

int count = stmt.executeUpdate("Insert into Students


values("+roll+",'"+name+"','"+city+"')");

if (count>0)
System.out.println("\n<-----Data inserted
successfully-------->\n");
else
System.out.println("Data insertion failed!!!!!!!");

//step5 close the connection object


con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:-

4
https://

Q24) write a program for JDBC to display the records from the existing
table.
Ans :-

//Java Program for JDBC to display the records from the existing
table.
import java.lang.*;
import java.sql.*;
public class OracleCon{
public static void main(String args[])
{ String sname,city;
int id;

try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:
1521:xe","bhupendra","dbms@12"); System.out.println("\
nDatabase connection done");

//step3 create the statement object


Statement stmt = con.createStatement();

//step4 execute query


ResultSet rs = stmt.executeQuery("select * from
Students");
while(rs.next())
{ id = rs.getInt("S_ID");
sname = rs.getString("S_NAME");
city = rs.getString("S_ADDRESS");

System.out.println("\t|"+id+"\t| "+sname+" \t| "+city+"\


t|");
}
//step5 close the connection object
con.close();
}

4
https://
catch(Exception e)
{ System.out.println("Exception occur : ");
System.out.println(e);
}

}
}

Output:-

4
https://

Q25) write a program for demonstrate of switch statement ,continue and


break.

Ans :-

//Java Program to demonstrate the example of Switch statement


import java.util.*;
public class SwitchExample {
public static void main(String[] args) {

Scanner input=new Scanner(System.in);


System.out.print("\nEnter number of day :");
int Day = input.nextInt();
switch (Day) {
case 7:
System.out.println("Today is Sunday");
break;
case 1:
System.out.println("Today is Monday");
break;
case 2:
System.out.println("Today is Tuesday");
break;
case 3:
System.out.println("Today is Wednesday");
break;
case 4:
System.out.println("Today is Thursday");
break;
case 5:
System.out.println("Today is Friday");
break;
case 6:
System.out.println("Today is Saturday");
break;
}
System.out.println("\n<<------------------------------->>\n");
System.out.println("Java program to demonstrates the
continue");
for (int i = 0; i < 10; i++)
{ // If the number is 2 skip and continue
if (i == 2)
continue;

System.out.print(i + " ");

4
https://
}
System.out.println();
}
}

Output:-

You might also like