0% found this document useful (0 votes)
3 views

Java File

The document is a term work report on Java Programming Language submitted by Akash Yadav to Dr. Prateek Srivastava at Graphic Era Hill University. It includes a series of programming tasks ranging from creating classes and methods to implementing banking systems, exception handling, multithreading, and GUI applications. Each task is accompanied by source code and expected outputs, demonstrating various Java programming concepts and techniques.

Uploaded by

dishantkhati2003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java File

The document is a term work report on Java Programming Language submitted by Akash Yadav to Dr. Prateek Srivastava at Graphic Era Hill University. It includes a series of programming tasks ranging from creating classes and methods to implementing banking systems, exception handling, multithreading, and GUI applications. Each task is accompanied by source code and expected outputs, demonstrating various Java programming concepts and techniques.

Uploaded by

dishantkhati2003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Term Work

On

Java Programming Language


(PCS 408)

Submitted to: Submitted by:


Dr. Prateek Srivastava Akash Yadav
Associate Professor University Roll. No.: 2018123
GEHU, D. Dun Class Roll No./Section: 04/A

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

GRAPHIC ERA HILL UNIVERSITY, DEHRADUN

Akash Yadav 2018123 A


Table of Contents
Program
Program Name Page No.
No.
Create a class “Student” having following instance variables
and methods.
1
Instance variables: ID, Name, Branch and university
Method: setDetails() and showDetails().

Write a Java Program to demonstrate the working of a


banking-system

2 Instance variables: name, account_no, amount

Instance methods: deposit(), withdraw(), checkBalance(),


insert() and display().

Write a program to sum two numbers. Here inputs are provided


3
through command line argument.

Create class Employee with following attributes and methods


ID, name, department and salary.
The setDetails() method sets the values of ID, name,
4
department and salary.
And showDetails() method shows the value of each field.

Re-write program 1 with better memory management


approach.
5
Note: use of static keyword

Apply following functions on the String "Java".


(i) Try to concat "Welcome" and write down your observation.
6
(ii) Find character at index 1
(iii) Find index of first 'a'.

Akash Yadav 2018123 A


(iv) Find index of second 'a'
(v) Compare "Java" to "JAVA"
(vi) Compare "Java" to "JAVA" ignoring the case
(vii) Find the index of first 'a' from last

Apply following functions on StringBuffer object "HELLO"


(i) Append "Java"
(ii) Insert "Java" at index 1
7 (iii) Replace with "Java" with characters between index 1 to 2
(iv) Delete characters between index 1 and 2
(v) Reverse the string "HELLO"

Create a class “Student” having following instance variables


and methods.
Instance variables: ID, Name, Branch, city and university
8
While creating constructors with one, two, three, four and five
arguments reuse the constructors by constructor chaining.

Create two dimensional integer array and insert, search and


9 traverse this array.
Note: Use Scanner class to insert data

Create a jagged array having three rows. Where 1st row


10 contains 3 columns, 2nd row contains 4 columns and 3rd row
contains 2 columns. Insert and traverse it.

Create a class “Shape” having area() method to calculate area.


11 Overload the area() method for shapes like triangle, rectangle
and circle.

Create a class “Bank” having method getRateOfInterest().


Create child classes as HDFC, SBI and PNB and override
12 getRateOfInterest() and return interest rates as 4.0, 4.5 and 5%
correspondingly.
Use concept of Upcasting to implement this scenario.

Create a package pack1 having one class C1 and one interface


I1. Class C1 has two methods int sum(int, int) and int
sub(int, int). The I1 has one method int division(int, int).
13
Create another package pack2 having class C2. Reuse C1 and
I1 in C2 and show the results.
Note: Use appropriate Access Modifiers as required.

Akash Yadav 2018123 A


Write a program to divide two numbers with proper exception
14 handlers.

Create LowBalanceException that occurs when user tries to


withdraw some amount that is greater than his current bank
15
balance. To withdraw you have to write a void withdrawal(int
amount) method.

Write a program that reads from a text file byte by byte and
16 writes in some another file. Write this program in an efficient
way.

Write a program that reads from a text file char by char and
17 writes in some another file. Write this program in an efficient
way

Write a program that reads from a text file line by line and
18 writes on console.

Write a program that take your name from keyboard and writes
19 in some text file.

Write a multithreaded program where three threads are there


20 and printing the numbers from 1 to 10 concurrently.

Write a program to set and get the name of threads also set and
21
get the priority of threads.

Akash Yadav 2018123 A


Write a class Display having void wish(String name) methods
that wishes hello to given string name. Between printing hello
and provided string name apply delay of 500 milliseconds.
22 Suppose multiple threads are there and they are trying to access
this wish() method concurrently on same object then irregular
output will be there. Write this application in such a way so
that output becomes regular.

Write a class Display having synchronized void wish(String)


methods that wishes hello to given string name. Between
printing hello and provided string name apply delay of 500
23 milliseconds. Suppose multiple threads are there and they are
trying to access this wish() method concurrently on different
objects then irregular output will be there. Write this
application in such a way so that output becomes regular.

Write a class Customer having balance as a property and void


withdrawal(int amount), and void deposit(int amount) as
instance methods. There are two threads, the first thread wants
to withdrawal some amount and second thread wants to deposit
24
some amount. Apply inter thread communication where, if
withdrawal amount is higher than current balance then first
thread will wait for second thread to deposit then resume the
withdrawal.

Create a GUI for student’s information system. A GUI that


25
asks all the relevant information’s related to a student.

26 Create a canvas having smiley face.

Write a JFrame having three textfields. The first two textfields


refers to two numbers on which sum or subtraction will
happen. The third textfield will show the result. There are two
27
buttons “SUM” and “SUBTRACTION”. Once user will click
on sum or subtraction buttons then the corresponding result
will be displayed in result field.

Akash Yadav 2018123 A


Write a Java program that interacts with database. It enables
to-
(a) Inserts the student name and roll number to database.
28 (b) Fetch records from table
(c) Modify the records
(d) Delete the records

Akash Yadav 2018123 A


DEPARTMENT OF CSE
STUDENT LAB REPORT SHEET
Name of Student .................................................... Mob. No ......................................
Photograph
Address Permanent ..................................................................................................... Passport Size

Father’s Name ........................... Occupation ...................... Mob. No .........................

Mother’s Name ........................... Occupation ...................... Mob. No .......................

Section ............ Branch ............ Semester ............ Class Roll No ............ Grade A B C

Local Address ................................... Email ............................................ Marks 5 3 1

S.No. Practical D.O.P. Date of Grade Grade Total Student’s Teacher’s


Submissi (Viva) (Report Marks Signature Signatur
on File) (out of e
10)
1 Program-01

2 Program-02

3 Program-03

4 Program-04

5 Program-05

6 Program-06

7 Program-07

8 Program-08

9 Program-09

10 Program-10

11 Program-11

12 Program-12

Akash Yadav 2018123 A


13 Program-13

14 Program-14

15 Program-15

16 Program-16

17 Program-17

18 Program-18

19 Program-19

20 Program-20

21 Program-21

22 Program-22

23 Program-23

24 Program-24

25 Program-25

26 Program-26

27 Program-27

28 Program-28

Akash Yadav 2018123 A


-1-

PRACTICAL 1

Question: 1. Create a class “Student” having following instance variables and


methods.
Instance variables: ID, Name, Branch and university
Method: setDetails() and showDetails().
Source Code:

class Students
{
int roll ;
String name , branch , uname = "Gehu" ;
void set()
{
roll = 4 ;
name = "Akash" ;
branch = "CSE" ;
}
void show()
{
System.out.println("\t\t Students Details ") ;
System.out.println("Name : "+name) ;
System.out.println("Roll No. : "+roll) ;
System.out.println("Branch : "+branch) ;
System.out.println("University : "+uname) ;
}
public static void main(String Args[])
{
Students s = new Students() ;
s.set() ;
s.show() ;
}

Akash Yadav 2018123 A


-2-

OUTPUT

Akash Yadav 2018123 A


-3-

PRACTICAL 2
Que 2. Write a Java Program to demonstrate the working of a banking-system
Instance variables: name, account_no, amount

Instance methods: deposit(), withdraw(), checkBalance(), insert() and display().

Source Code :
// Que 2
// Akash Yadav
class BankingSystem
{
int acc ;
String name ;
float amt ;
void insert(int account,String n , float bal)
{
acc = account ;
name = n ;
amt = bal;
System.out.println("Account Created Successfully ") ;
}
void deposit(float d)
{
System.out.println("Amount Credited : "+d) ;
amt = amt + d ;
System.out.println("New Balance : "+amt) ;
}
void withdraw(int w)
{
if(w<=amt)
{
System.out.println("Amount Debited : "+w) ;
amt = amt-w ;
System.out.println("New Balance : "+amt) ;
}
else
{

Akash Yadav 2018123 A


-4-

System.out.println("In Sufficient Balance ") ;


System.out.println("Account Balance : "+amt) ;
System.out.println("Amount to be Debited : "+w) ;
}
}
void check()
{
System.out.println("Amount = "+amt) ;
}
void display()
{
System.out.println("Account Number = "+acc) ;
System.out.println("Name Holder = "+name) ;
System.out.println("Account Balance = "+amt) ;
}

public static void main(String Args[])


{
BankingSystem obj = new BankingSystem() ;
//Creating Account
obj.insert(360303,"Akash",3000) ;
//Depositing Amount
obj.deposit(10000) ;
//Ckecking Balance
obj.check();
//Withdrawing Amount>Balance
obj.withdraw(15000) ;
//Withdrawing Amount<=Balance
obj.withdraw(5000) ;
//Checking Balance
obj.check();
//Display Details
obj.display();
}

Akash Yadav 2018123 A


-5-

OUTPUT

Akash Yadav 2018123 A


-6-

PRACTICAL 3
Que 3 : Write a program to sum two numbers. Here inputs are provided
through command line argument.

Source Code :
// 5 March 2022 LAB
// JAVA
// Command Line Argument
class Sum
{
public static void main(String args[])
{
int x = Integer.parseInt(args[0]) ;
int y = Integer.parseInt(args[1]) ;
System.out.println("The Sum is : "+(x+y)) ;
}

Akash Yadav 2018123 A


-7-

OUTPUT

Akash Yadav 2018123 A


-8-

PRACTICAL 4

Que 4 : Create class Employee with following attributes and methods


ID, name, department and salary.
The setDetails() method sets the values of ID, name, department and salary.
And showDetails() method shows the value of each field.
Note: (i) Values must be entered through Scanner class.

Source Code :
// Lab 26March2022
// Count Number of Objects

import java.util.Scanner ;
class Employee
{
int id ;
String dept ;
String name ;
float salary;
Employee()
{
dept = "CSE ";
}
void setDetails(String name,int id,float salary) // setting the
variables data
{
this.name = name ;
this.id = id ;
this.salary = salary ;
}
void showDetails()
{
System.out.println("\t\t Employee Details ") ;

Akash Yadav 2018123 A


-9-

System.out.println("Id No. : "+this.id) ;


System.out.println("Name : "+this.name) ;
System.out.println("Department : "+this.dept) ;
System.out.println("Salary : "+this.salary) ;
}
public static void main(String args[])
{
Employee e1 = new Employee() ;
String name ;
int id ;
float salary;
Scanner sc = new Scanner(System.in) ;
System.out.println("Enter Your Name ") ;
name = sc.nextLine() ;
System.out.println("Enter Your Id Number ") ;
id = sc.nextInt() ;
sc.nextLine() ; // for consuming \n
System.out.println("Enter Your Salary ") ;
salary = sc.nextFloat() ;
sc.nextLine() ;
e1.setDetails(name,id,salary) ;
e1.showDetails() ;
}

Akash Yadav 2018123 A


- 10 -

OUTPUT

Akash Yadav 2018123 A


- 11 -

PRACTICAL 5
Que 5 : . Re-write program 1 with better memory management approach.
Note: use of static keyword.

Source Code :
class Students
{
int roll ;
String name , branch , uname = "Gehu" ;
void set()
{
roll = 4 ;
name = "Akash" ;
branch = "CSE" ;
}
void show()
{
System.out.println("\t\t Students Details ") ;
System.out.println("Name : "+name) ;
System.out.println("Roll No. : "+roll) ;
System.out.println("Branch : "+branch) ;
System.out.println("University : "+uname) ;
}
public static void main(String Args[])
{
Students s = new Students() ;
s.set() ;
s.show() ;
}

Akash Yadav 2018123 A


- 12 -

OUTPUT

Akash Yadav 2018123 A


- 13 -

PRACTICAL 6
Que 6 : Apply following functions on the String "Java".
(i) Try to concat "Welcome" and write down your observation.
(ii) Find character at index 1
(iii) Find index of first 'a'.
(iv) Find index of second 'a'
(v) Compare "Java" to "JAVA"
(vi) Compare "Java" to "JAVA" ignoring the case
(vii) Find the index of first 'a' from last

Source Code :

// Que 6
class Str
{
public static void main(String Args[])
{
String s1 = "Java" ;// literal
//Concate
System.out.println("String S1 Before Concatenation : "+s1);
// S1 Does not change b/c strings are immutable
System.out.println("s1.concat : "+s1.concat("Welcome")) ;
System.out.println("String S1 After Concatenation : "+s1);
// S1 Does not change b/c strings are immutable

//Character at index
System.out.println("s1.charAt1 : "+s1.charAt(1));

//IndexOf first 'a'


int ind = s1.indexOf('a') ;
System.out.println("Index of First 'a' is : "+ind);
int sind = s1.indexOf('a',ind+1) ;
System.out.println("Index of Second 'a' is : "+sind);

//String Comparison
String s2 = "JAVA" ;
System.out.println("String S1 : "+s1);

Akash Yadav 2018123 A


- 14 -

System.out.println("String S2 : "+s2);
System.out.println("is s1.equalss2 : "+s1.equals(s2)) ;
System.out.println("Ignore Case : "+s1.equalsIgnoreCase(s2));
System.out.println("is s1==s2 : "+s1==s2); //Compares Objects

//Index of first 'a' from last


System.out.println("String S1 : "+s1);
int last = s1.lastIndexOf('a') ;
System.out.println("Index of first 'a' from Last : "
+s1.lastIndexOf('a',last-1));

Akash Yadav 2018123 A


- 15 -

OUTPUT

Akash Yadav 2018123 A


- 16 -

PRACTICAL 7
Que 7 : Apply following functions on StringBuffer object "HELLO"
(i) Append "Java"
(ii) Insert "Java" at index 1
(iii) Replace with "Java" with characters between index 1 to 2
(iv) Delete characters between index 1 and 2
(v) Reverse the string "HELLO"

Source Code :
class StrBuffer
{
public static void main(String args[])
{
//Append()
System.out.println("\t\t String Append ");
StringBuffer s1 = new StringBuffer("Java") ; // Mutable
System.out.println("String s1 Before Append : "+s1) ;
s1.append(" Welocme") ;
System.out.println("String s1 After Append : "+s1) ;

//charAt()
System.out.println("\t\t Character at Index");
System.out.println("Character at Index 1 : "+s1.charAt(1)) ;

//index of 'a'
System.out.println("\t\t Index of Character ");
int ind = s1.indexOf("a") ;
System.out.println("Index of First 'a' is : "+ind);
int sind = s1.indexOf("a",ind+1) ;
System.out.println("Index of Second 'a' is : "+sind);

//comparison
StringBuffer s2 = new StringBuffer("JAVA");
StringBuffer s3 = new StringBuffer("java");
System.out.println("\t\t String Comparison ");
System.out.println("String s2 : "+s2);
System.out.println("String s3 : "+s3);

Akash Yadav 2018123 A


- 17 -

System.out.println("Is s2.equalsIgnoreCase s3: "+ s2.equals(s3)) ;

//Index of first 'a' from last


System.out.println("\t\t Index of first 'a' from last ");
System.out.println("String s3 : "+s3);
int last = s3.lastIndexOf("a") ;
System.out.println("Index of first 'a' from Last : "+ s3.lastIndexOf("a",last-
1)) ;

Akash Yadav 2018123 A


- 18 -

OUTPUT

Akash Yadav 2018123 A


- 19 -

PRACTICAL 8
Que 8 : . Create a class “Student” having following instance variables and
methods.
Instance variables: ID, Name, Branch, city and university
While creating constructors with one, two, three, four and five arguments reuse
the constructors by constructor chaining
Source Code :
class ConstructorChaining
{
int x , y , z ;
ConstructorChaining(int x)
{
this.x = x ;
}
ConstructorChaining(int x,int y)
{
this(x) ;
this.y = y ;
}
ConstructorChaining(int x,int y,int z)
{
this(x,y) ;
this.z = z ;
}
void show()
{
System.out.println("\t\t Constructor Chaining ");
System.out.println("Value of x = "+this.x);
System.out.println("Value of y = "+this.y);
System.out.println("Value of z = "+this.z);
}
public static void main(String args[])
{
ConstructorChaining obj = new ConstructorChaining(5,6,7) ;
obj.show() ;
}
}

Akash Yadav 2018123 A


- 20 -

OUTPUT

Akash Yadav 2018123 A


- 21 -

PRACTICAL 9
Que 9 : Create two dimensional integer array and insert, search and traverse this
array.
Note: Use Scanner class to insert data

Source Code :

import java.util.Scanner ;
class ArrayMD
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in) ;
int m , n ;
System.out.println("Enter Order of Array mXn ") ;
System.out.println("Enter Value of M ") ;
m = sc.nextInt() ;
sc.nextLine() ;
System.out.println("Enter Value of N ") ;
n = sc.nextInt() ;
sc.nextLine() ;
int arr[][] = new int[m][n] ;
int i , j ;
System.out.println("Enter Elements in Array") ;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
arr[i][j] = sc.nextInt() ;
sc.nextLine() ;
}
}
System.out.println("Array is ") ;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{

Akash Yadav 2018123 A


- 22 -

System.out.print(arr[i][j] +" ") ;


}
System.out.println() ;
}
System.out.println() ;
}
}

Akash Yadav 2018123 A


- 23 -

OUTPUT

Akash Yadav 2018123 A


- 24 -

PRACTICAL 10
Que 10 : Create a jagged array having three rows. Where 1st row contains 3
columns, 2nd row contains 4 columns and 3rd row contains 2 columns. Insert and
traverse it.

Source Code :
class JaggedArray
{
public static void main(String args[])
{
// Jagged Array
int arr[][] = new int [3][] ;
arr[0] = new int[3] ;
arr[1] = new int[4] ;
arr[2] = new int[2] ;

int i , j ;
int c = 0 ;
for(i=0;i<arr.length;i++)
{
for(j=0;j<arr[i].length;j++)
{
arr[i][j] = c++ ;
}
}
System.out.println("Jagged Array is ") ;
for(i=0;i<arr.length;i++)
{
for(j=0;j<arr[i].length;j++)
{
System.out.print(arr[i][j] +" ") ;
}
System.out.println() ;
}
}
}

Akash Yadav 2018123 A


- 25 -

OUTPUT

Akash Yadav 2018123 A


- 26 -

PRACTICAL 11
Que 11 : Create a class “Shape” having area() method to calculate area.
Overload the area() method for shapes like triangle, rectangle and circle.

Source Code :
class Shape
{
int area(int x,int y) // Rectangle
{
int area =x*y;
return area;
}

int area(int x) // Square


{
int area = x*x;
return area;
}

float area(float x) // Circle


{
float area = (float)(3.14*x*x);
return area;
}

float area(float x,float y) // Triangle


{
float area = (float)(0.5*x*y);
return area;
}

public static void main(String args[])


{
System.out.println("\t\t Function Overloading ");
Shape s = new Shape();
int area_r = s.area(4,5);
System.out.println("Area of Rectangle l = 4 , b = 5 : "+area_r);

Akash Yadav 2018123 A


- 27 -

int area_s= s.area(4);


System.out.println("Area of Square s = 4 : "+area_s);
float area_c=s.area(4.5f);
System.out.println("Area of Circle r = 4.5 : "+area_c);
float area_t=s.area(4.5f,5.5f);
System.out.println("Area of Traingle b=4.5 , h =5.5 : "+area_t);
}
}

Akash Yadav 2018123 A


- 28 -

OUTPUT

Akash Yadav 2018123 A


- 29 -

PRACTICAL 12
Que 12 : Create a class “Bank” having method getRateOfInterest(). Create child
classes as HDFC, SBI and PNB and override getRateOfInterest() and return
interest rates as 4.0, 4.5 and 5% correspondingly.
Use concept of Upcasting to implement this scenario.

Source Code :
class BankRateOfInt
{
void getROI()
{
System.out.println("Bank Interest : 2.0");
}
public static void main(String args[])
{
System.out.println("\t\t Upcasting ");
BankRateOfInt obj= new BankRateOfInt();
obj.getROI() ;
obj = new Sbi(); // Upcasting
obj.getROI() ;

obj = new Pnb(); //Upcasting


obj.getROI();

obj = new Sbi(); //Upcasting


obj.getROI();
obj = new Hdfc(); //Upcasting
obj.getROI();

}
}
class Hdfc extends BankRateOfInt
{
void getROI()
{
System.out.println("Bank Interest in HDFC : 4.0");
}

Akash Yadav 2018123 A


- 30 -

class Sbi extends BankRateOfInt


{
void getROI()
{
System.out.println("Bank Interest in SBI : 4.5");
}
}
class Pnb extends BankRateOfInt
{
void getROI()
{
System.out.println("Bank Interest in PNB : 5");
}
}

Akash Yadav 2018123 A


- 31 -

OUTPUT

Akash Yadav 2018123 A


- 32 -

PRACTICAL 13
Que 13 : Create a package pack1 having one class C1 and one interface I1. Class
C1 has two methods int sum(int, int) and int sub(int, int). The I1 has one method
int division(int, int). Create another package pack2 having class C2. Reuse C1
and I1 in C2 and show the results.
Note: Use appropriate Access Modifiers as required.

Source Code :
package pack1 ;

public class C1
{
public int sum(int a,int b)
{
return (a+b) ;
}
public int mult(int a,int b)
{
return (a*b) ;
}
};

package pack1;

public interface I1
{
public float div(int a,int b) ;
};

package pack2 ;
import pack1.C1 ;
import pack1.I1 ;
import java.util.Scanner ;
class C2 extends C1 implements I1
{
public float div(int a,int b)
{

Akash Yadav 2018123 A


- 33 -

return (a/b) ;
}

public static void main(String args[])


{
C2 obj = new C2() ;
Scanner sc = new Scanner(System.in) ;
int a, b ;
System.out.print("Enter Value of A : ") ;
a = sc.nextInt() ;
sc.nextLine() ;
System.out.print("Enter Value of B : ") ;
b = sc.nextInt() ;
sc.nextLine() ;
//Calling methods()
System.out.println("Sum is : "+ obj.sum(a,b)) ;
System.out.println("Multiplication is : "+ obj.mult(a,b)) ;
System.out.println("Division is : "+ obj.div(a,b)) ;
//System.out.println("Multiplication is : "+ I1.mult(a,b)) ;
}
}

Akash Yadav 2018123 A


- 34 -

OUTPUT

Akash Yadav 2018123 A


- 35 -

PROGRAM 14
Que 14 : Write a program to divide two numbers with proper exception handlers.

Source Code :
import java.util.Scanner;

public class Exp {


public static void main(String args[]) {
int a , b ;

Scanner sc = new Scanner(System.in) ;


System.out.print("Enter A : ");
a = sc.nextInt() ;
sc.nextLine() ;
System.out.print("Enter B : ");
b = sc.nextInt() ;
sc.nextLine() ;

if(b==0){
throw new ArithmeticException("Dont Divide by Zero") ;
}
else{
System.out.println("Divide a/b : "+a/b);
}
}
}

Akash Yadav 2018123 A


- 36 -

OUTPUT

Akash Yadav 2018123 A


- 37 -

PROGRAM 15
Que 15 : Create LowBalanceException that occurs when user tries to
withdraw some amount that is greater than his current bank balance. To
withdraw you have to write a void withdrawal(int amount) method .

Source Code :
import java.util.Scanner;

class LowBalanceException extends RuntimeException{


LowBalanceException(String s){
super(s) ;
}
}
class Bank{
int bal ;
void deposit(int amt){
this.bal = amt ;
}
void withdrawl(int amt){
if(amt>this.bal){
throw new LowBalanceException("Insufficient Balance ") ;
}
else{
this.bal = this.bal - amt ;
System.out.println("Amount Debited ");
}
}
public static void main(String args[]) {
int bal, amt ;
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter Balance : ");
bal = sc.nextInt() ;
sc.nextLine() ;
System.out.print("Enter Wirhdrawl Amount : ");
amt = sc.nextInt() ;
sc.nextLine() ;
Bank b = new Bank() ;

Akash Yadav 2018123 A


- 38 -

b.deposit(bal);
b.withdrawl(amt);
}
}

Akash Yadav 2018123 A


- 39 -

OUTPUT

Akash Yadav 2018123 A


- 40 -

PROGRAM 16
Que 16 : Write a program that reads from a text file byte by byte and writes in
some another file. Write this program in an efficient way.

Source Code :
import java.io.* ;
class ByteStream{
public static void main(String args[]) throws Exception{
int x ;
// Using Char Stream
FileInputStream fis = new FileInputStream("sample1.txt") ;
FileOutputStream fos = new FileOutputStream("sample2.txt") ;
//Reading Single character by character and Writing in file

// Using Buffer Stream


System.out.println("Reading Full File and Writing in Another File
Using Char Stream") ;
BufferedInputStream bis = new BufferedInputStream(fis) ;
BufferedOutputStream bos = new BufferedOutputStream(fos) ;
while( (x=bis.read())!=-1 ){
bos.write((char) x) ;
}
bis.close() ;
bos.close() ;
fis.close() ;
fos.close() ;
}
}

Akash Yadav 2018123 A


- 41 -

OUTPUT

Sample1.txt

Sample2.txt (Before)

Sample2.txt (After)

Akash Yadav 2018123 A


- 42 -

PROGRAM 17
Que 17 : Write a program that reads from a text file char by char and writes in
some another file. Write this program in an efficient way
Source Code :
import java.io.* ;
class ReadText{
public static void main(String args[]) throws Exception{
int x ;
// Using Byte Stream
FileReader fr = new FileReader("sample1.txt") ;
FileWriter fw = new FileWriter("sample2.txt") ;
//Reading Single character by character and Writing in file

// Using Buffer Stream


System.out.println("Reading Full File and Writing in Another File
Using Using Char Buffered ") ;
BufferedReader br = new BufferedReader(fr) ;
BufferedWriter bw = new BufferedWriter(fw) ;
// returns -1 when End of file Occur
while( (x=br.read())!=-1 ){
bw.write((char) x) ;
}
br.close() ;
bw.close() ;
fr.close() ;
fw.close() ;
}
}

Akash Yadav 2018123 A


- 43 -

OUTPUT

Sample1.txt

Sample2.txt (Before)

Sample2.txt (After)

Akash Yadav 2018123 A


- 44 -

PROGRAM 18
Que 18 : Write a program that reads from a text file line by line and writes on
console.

Source Code :
import java.io.*;

class LineByLine {
public static void main(String args[]) throws Exception {

String s ;
System.out.println("Reading Line by Line Using Char Buffered ") ;
FileReader fr = new FileReader("sample1.txt") ;
BufferedReader br = new BufferedReader(fr) ;
System.out.println("Content is -");
while( (s=br.readLine())!=null ) {
System.out.print(s) ;
}
}
}

Akash Yadav 2018123 A


- 45 -

OUTPUT

Akash Yadav 2018123 A


- 46 -

PROGRAM 19
Que 19 : Write a program that take your name from keyboard and writes in
some text file.

Source Code :
import java.io.*;
import java.util.Scanner;
class Name
{
public static void main(String[] args) throws Exception
{
System.out.println("Writing Name in File");
FileWriter fw = new FileWriter("sample1.txt") ;
BufferedWriter bw = new BufferedWriter(fw) ;
String name ;
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter Your Name : ");
name = sc.nextLine() ;
// writing in to File
bw.write(name);
bw.close() ;
fw.close() ;
}
}

Akash Yadav 2018123 A


- 47 -

OUTPUT

Sample1.txt (Before)

Sample1.txt(After)

Akash Yadav 2018123 A


- 48 -

PROGRAM 20
Que 20 : Write a multithreaded program where three threads are there and
printing the numbers from 1 to 10 concurrently.

Source Code :
class Ab extends Thread
{
public void run()
{
int i ;
for(i=0;i<11;i++)
{
System.out.println(i) ;
}
}
}
class MyThread
{
public static void main(String args[])
{
Ab c = new Ab() ; // New born state
c.start() ; // runnable mode
}
}

Akash Yadav 2018123 A


- 49 -

OUTPUT

Akash Yadav 2018123 A


- 50 -

PROGRAM 21
Que 21 : Write a program to set and get the name of threads also set and get the
priority of threads.

Source Code :
class A implements Runnable
{
public void run()
{
int i ;
for(i=0;i<2;i++)
{
System.out.println("From Thread A : "+i) ;
}
}
}
class B implements Runnable
{
public void run()
{
int i ;
for(i=0;i<2;i++)
{
System.out.println("From Thread B : "+i) ;
}
}
}
class C implements Runnable
{
public void run()
{
int i ;
for(i=0;i<2;i++)
{
System.out.println("From Thread C : "+i) ;
}
}

Akash Yadav 2018123 A


- 51 -

}
class ThreadName
{
public static void main(String args[])
{
A a = new A() ; // New born state
B b = new B() ;
C c = new C() ;

// Creating object of thread


Thread t1 = new Thread(a) ;
Thread t2 = new Thread(b) ;
Thread t3 = new Thread(c) ;

// ThreadName
System.out.println("Default Thread Names ") ;
System.out.println("Thread A : "+t1.getName()) ;
System.out.println("Thread B : "+t2.getName()) ;
System.out.println("Thread C : "+t3.getName()) ;

t1.start() ;// runnable mode


t2.start() ;
t3.start() ;

//Changing thread name


t3.setName("MyThread");
System.out.println("Changing Thread C Name ") ;
System.out.println("Thread C : "+t3.getName()) ;

//Priority Name
System.out.println("Priority of Threads ") ;
System.out.println("Thread A Priority : "+t1.getPriority()) ;
System.out.println("Thread B Priority : "+t2.getPriority()) ;
System.out.println("Thread C Priority : "+t3.getPriority()) ;

//Changing Priority
t3.setPriority(7);

Akash Yadav 2018123 A


- 52 -

System.out.println("Changing Thread C Priority ") ;


System.out.println("Thread C Priority : "+t3.getPriority()) ;
}
}

Akash Yadav 2018123 A


- 53 -

OUTPUT

Akash Yadav 2018123 A


- 54 -

PROGRAM 22
Que 22 : Write a class Display having void wish(String name) methods that
wishes hello to given string name. Between printing hello and provided string
name apply delay of 500 milliseconds. Suppose multiple threads are there and
they are trying to access this wish() method concurrently on same object then
irregular output will be there. Write this application in such a way so that output
becomes regular.

Source Code :
import java.util.Scanner;
class Disp
{
public void wish(String s)
{
for(int i=0;i<10;i++)
{
System.out.print("Hello : ") ;
// Adding timed delay
try
{
Thread.sleep(500) ; // time in milliseconds
}
catch(Exception e)
{
System.out.println(e) ;
}
System.out.println(s) ;
}
}
}
class MyThread extends Thread
{
Disp d ;
String name ;
// Constructor
MyThread(Disp d,String name)
{

Akash Yadav 2018123 A


- 55 -

this.d = d ;
this.name = name ;
}
public void run()
{
d.wish(name) ; // calling wish() function
}
}

class Demo
{
public static void main(String args[])
{
Disp d = new Disp() ;
System.out.println("Shared Resource ") ;

// for Input Names


Scanner sc = new Scanner(System.in) ;
String s1 ,s2 ;
System.out.print("Enter Name 1 ") ;
s1 = sc.nextLine() ;
System.out.print("Enter Name 2 ") ;
s2 = sc.nextLine() ;

// Creating Shared objects


MyThread t1 = new MyThread(d,s1) ;
t1.start() ;

MyThread t2 = new MyThread(d,s2) ;


t2.start() ;
}
}

Akash Yadav 2018123 A


- 56 -

OUTPUT

Akash Yadav 2018123 A


- 57 -

PROGRAM 23
Que 23 : Write a class Display having synchronized void wish(String)
methods that wishes hello to given string name. Between printing hello and
provided string name apply delay of 500 milliseconds. Suppose multiple threads
are there and they are trying to access this wish() method concurrently on
different objects then irregular output will be there. Write this application in
such a way so that output becomes regular.

Source Code :
import java.util.Scanner;
class Disp
{
public synchronized void wish(String s) // Synchronized Method
{
for(int i=0;i<10;i++)
{
System.out.print("Hello : ") ;
// Adding timed delay
try
{
Thread.sleep(1000) ; // time in milliseconds
}
catch(Exception e)
{
System.out.println(e) ;
}
System.out.println(s) ;
}
}
}
class MyThread extends Thread
{
Disp d ;
String name ;
// Constructor
MyThread(Disp d,String name)
{

Akash Yadav 2018123 A


- 58 -

this.d = d ;
this.name = name ;
}
public void run()
{
d.wish(name) ; // calling wish() function
}
}

class DemoSolution
{
public static void main(String args[])
{
Disp d = new Disp() ;
System.out.println("Shared Resource ") ;

// for Input Names


Scanner sc = new Scanner(System.in) ;
String s1 ,s2 ;
System.out.print("Enter Name 1 : ") ;
s1 = sc.nextLine() ;
System.out.print("Enter Name 2 : ") ;
s2 = sc.nextLine() ;

// Creating Shared objects


MyThread t1 = new MyThread(d,s1) ;
t1.start() ;

MyThread t2 = new MyThread(d,s2) ;


t2.start() ;
}
}

Akash Yadav 2018123 A


- 59 -

OUTPUT

Akash Yadav 2018123 A


- 60 -

PROGRAM 24
Que 24 : Write a class Customer having balance as a property and void
withdrawal(int amount), and void deposit(int amount) as instance methods.
There are two threads, the first thread wants to withdrawal some amount and
second thread wants to deposit some amount. Apply inter thread communication
where, if withdrawal amount is higher than current balance then first thread will
wait for second thread to deposit then resume the withdrawal.

Source Code :
import java.util.Scanner;
class Customer
{
int bal = 10000 ;
public synchronized void withdrawl(int amt)
{
if(this.bal<amt)
{
System.out.println("Less Balance Wait......");
try{
wait() ;
}
catch(Exception e){
System.out.println(e);
}
}
this.bal = this.bal - amt ;
System.out.println("Amount Debited ");
}
public synchronized void deposit(int amt)
{
System.out.println("Going to Deposit....");
this.bal = this.bal + amt ;
System.out.println("Amount Credited");
try{
notify();
}
catch(Exception e){

Akash Yadav 2018123 A


- 61 -

System.out.println(e);
}
}
}
class MyThread1 extends Thread
{
Customer c ;
MyThread1(Customer c){
this.c = c ;
}
public void run()
{
c.withdrawl(15000);
}
}
class MyThread2 extends Thread
{
Customer c ;
MyThread2(Customer c){
this.c = c ;
}
public void run()
{
c.deposit(8000);
}
}
class BankDemo
{
public static void main(String args[])
{
Customer c = new Customer() ;
Scanner sc = new Scanner(System.in) ;
int amt , dep ;

System.out.print("Enter Amount to Withdrawl : ");


amt = sc.nextInt() ;
sc.nextLine() ;

Akash Yadav 2018123 A


- 62 -

MyThread1 t1 = new MyThread1(c) ;

MyThread2 t2 = new MyThread2(c) ;


t1.start();
t2.start();
}
}

Akash Yadav 2018123 A


- 63 -

OUTPUT

Akash Yadav 2018123 A


- 64 -

PROGRAM 25
Que 25 : Create a GUI for student’s information system. A GUI that asks all
the relevant information’s related to a student.

Source Code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Student extends JFrame
{
Student()
{
JLabel l1 = new JLabel("Name : ");
JLabel l2 = new JLabel("Student Id : ");
JLabel l3 = new JLabel("Univ Roll No. : ");
JLabel l4 = new JLabel("Branch : ");
JLabel l5 = new JLabel("Sem : ");
JTextField tf1 = new JTextField(15) ;
JTextField tf2 = new JTextField(15) ;
JTextField tf3 = new JTextField(15) ;
JTextField tf4 = new JTextField(15) ;
JTextField tf5 = new JTextField(15) ;
JButton b1 = new JButton("Submit") ;
setLayout(new FlowLayout());
add(l1) ;
add(tf1) ;
add(l2) ;
add(tf2) ;
add(l3) ;
add(tf3) ;
add(l4) ;
add(tf4) ;
add(l5) ;
add(tf5) ;
add(b1) ;
}
public static void main(String args[])

Akash Yadav 2018123 A


- 65 -

{
Student s = new Student() ;
s.setSize(600,700);
s.setVisible(true) ;
}
}

Akash Yadav 2018123 A


- 66 -

OUTPUT

Akash Yadav 2018123 A


- 67 -

PROGRAM 26
Que 26 : Create a canvas having smiley face.

Source Code :
import javax.swing.*;
import java.awt.*;
class Smiley extends Canvas{
public void paint(Graphics g)
{
g.setColor(Color.GREEN);
//g.drawArc(10, 20, 30, 30, 0, 360);
g.fillArc(100, 50, 200, 200, 0, 360);
g.setColor(Color.RED);
g.fillArc(130, 100, 40, 30, 0, 360);
g.fillArc(220, 100, 40, 30, 0, 360);
//g.setColor(Color.BLACK);
//g.drawLine(175, 175, 190, 190);
g.setColor(Color.PINK);
g.fillArc(150, 150, 100, 70, 0, -180);

}
public static void main(String[] args)
{
Smiley d = new Smiley() ;
JFrame f = new JFrame() ;
f.setSize(600,700);
f.setVisible(true);
f.add(d) ;

}
}

Akash Yadav 2018123 A


- 68 -

OUTPUT

Akash Yadav 2018123 A


- 69 -

PROGRAM 27
Que 27 : Write a JFrame having three textfields. The first two textfields refers
to two numbers on which sum or subtraction will happen. The third textfield will
show the result. There are two buttons “SUM” and “SUBTRACTION”. Once
user will click on sum or subtraction buttons then the corresponding result will
be displayed in result field.

Source Code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Calculator extends JFrame implements ActionListener{
JTextField tf1 , tf2 , tf3 ;
Calculator(){
JLabel l1 = new JLabel("Number 1 : ") ;
JLabel l2 = new JLabel("Number 2 : ") ;
JLabel l3 = new JLabel("Result : ") ;
JButton b1 = new JButton("SUM") ;
JButton b2 = new JButton("SUBTRACT") ;
JButton b3 = new JButton("MUL") ;
JButton b4 = new JButton("DIV") ;
tf1 = new JTextField(10) ;
tf2 = new JTextField(10) ;
tf3 = new JTextField(10) ;

setLayout(new FlowLayout());
add(l1) ;
add(tf1) ;
add(l2) ;
add(tf2) ;
add(b1) ;
add(b2) ;
add(b3) ;
add(b4) ;
add(l3) ;
add(tf3) ;
b1.addActionListener(this);

Akash Yadav 2018123 A


- 70 -

b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);

}
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand() ;
int res = 0 ;
if( s.equals("SUM") ){
res = Integer.parseInt(tf1.getText()) + Integer.parseInt(tf2.getText()) ;
}
if( s.equals("SUBTRACT") ){
res = Integer.parseInt(tf1.getText()) - Integer.parseInt(tf2.getText()) ;
}
if( s.equals("MUL") ){
res = Integer.parseInt(tf1.getText()) * Integer.parseInt(tf2.getText()) ;
}
if( s.equals("DIV") ){
res = Integer.parseInt(tf1.getText()) / Integer.parseInt(tf2.getText()) ;
}
tf3.setText(Integer.toString(res)) ;
}
public static void main(String[] args) {
Calculator d = new Calculator() ;
d.setSize(600,700);
d.setVisible(true);

}
}

Akash Yadav 2018123 A


- 71 -

OUTPUT

Akash Yadav 2018123 A


- 72 -

PROGRAM 28
Que 28 : Write a Java program that interacts with database. It enables to-
(a) Inserts the student name and roll number to database.
(b) Fetch records from table
(c) Modify the records
(d) Delete the records

Source Code :
import java.sql.*;
import java.util.Scanner;
class Jdbc
{
public static void main(String args[])
{
Connection con = null ;
try{
Class.forName("com.mysql.cj.jdbc.Driver") ;
}
catch(Exception e){
System.out.println(e) ;
}
try
{

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Akash",
"root", "Akashyadav7@");
}
catch(Exception e){
System.out.println("Connection NOT Established") ;
}
// Create Statement
Scanner sc = new Scanner(System.in) ;
int id ;
String name ;
System.out.print("Enter Id : ");
id = sc.nextInt() ;
sc.nextLine() ;

Akash Yadav 2018123 A


- 73 -

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


name = sc.nextLine() ;
try
{
System.out.println("Insert in to Table") ;
PreparedStatement ps = con.prepareStatement("insert into emp(id,name)
values(?,?)") ;
ps.setInt(1,id) ;
ps.setString(2,name);
ps.executeUpdate();

System.out.println("Fetching Records ") ;


Statement st = con.createStatement() ;
ResultSet rs = st.executeQuery("select * from emp") ;
while(rs.next())
{
System.out.print(rs.getInt(1)+" ") ;
System.out.println(rs.getString(2)) ;
}

System.out.println("Update in to Table") ;
PreparedStatement ps1 = con.prepareStatement("update emp set Name =?
where id= ?") ;
ps1.setString(1,"Goblin") ;
ps1.setInt(2,id);
ps1.executeUpdate();
ResultSet rs1 = st.executeQuery("select * from emp") ;
while(rs1.next())
{
System.out.print(rs1.getInt(1)+" ") ;
System.out.println(rs1.getString(2)) ;
}

System.out.println("Deletion in to Table") ;
PreparedStatement ps2 = con.prepareStatement("DELETE FROM emp
WHERE id=?") ;
ps2.setInt(1,id);

Akash Yadav 2018123 A


- 74 -

ps2.executeUpdate();
ResultSet rs2 = st.executeQuery("select * from emp") ;
while(rs2.next())
{
System.out.print(rs2.getInt(1)+" ") ;
System.out.println(rs2.getString(2)) ;
}
}
catch(Exception e)
{
System.out.println(e) ;
}
}
}

Akash Yadav 2018123 A


- 75 -

OUTPUT

Akash Yadav 2018123 A

You might also like