Java File
Java File
On
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 program to set and get the name of threads also set and
21
get the priority of threads.
Section ............ Branch ............ Semester ............ Class Roll No ............ Grade A B C
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
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
PRACTICAL 1
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() ;
}
OUTPUT
PRACTICAL 2
Que 2. Write a Java Program to demonstrate the working of a banking-system
Instance variables: name, account_no, amount
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
{
OUTPUT
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)) ;
}
OUTPUT
PRACTICAL 4
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 ") ;
OUTPUT
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() ;
}
OUTPUT
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));
//String Comparison
String s2 = "JAVA" ;
System.out.println("String S1 : "+s1);
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
OUTPUT
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);
OUTPUT
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() ;
}
}
OUTPUT
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++)
{
OUTPUT
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() ;
}
}
}
OUTPUT
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;
}
OUTPUT
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() ;
}
}
class Hdfc extends BankRateOfInt
{
void getROI()
{
System.out.println("Bank Interest in HDFC : 4.0");
}
OUTPUT
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)
{
return (a/b) ;
}
OUTPUT
PROGRAM 14
Que 14 : Write a program to divide two numbers with proper exception handlers.
Source Code :
import java.util.Scanner;
if(b==0){
throw new ArithmeticException("Dont Divide by Zero") ;
}
else{
System.out.println("Divide a/b : "+a/b);
}
}
}
OUTPUT
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;
b.deposit(bal);
b.withdrawl(amt);
}
}
OUTPUT
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
OUTPUT
Sample1.txt
Sample2.txt (Before)
Sample2.txt (After)
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
OUTPUT
Sample1.txt
Sample2.txt (Before)
Sample2.txt (After)
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) ;
}
}
}
OUTPUT
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() ;
}
}
OUTPUT
Sample1.txt (Before)
Sample1.txt(After)
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
}
}
OUTPUT
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) ;
}
}
}
class ThreadName
{
public static void main(String args[])
{
A a = new A() ; // New born state
B b = new B() ;
C c = new 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()) ;
//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);
OUTPUT
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)
{
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 ") ;
OUTPUT
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)
{
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 ") ;
OUTPUT
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){
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 ;
OUTPUT
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[])
{
Student s = new Student() ;
s.setSize(600,700);
s.setVisible(true) ;
}
}
OUTPUT
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) ;
}
}
OUTPUT
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);
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);
}
}
OUTPUT
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() ;
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);
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) ;
}
}
}
OUTPUT