Java Programs
Java Programs
Sample I/O
23
Addition of 2 and 3 is 5
*/
import java.util.Scanner;
class Addition
int a,b,c;
a=sc.nextInt();
b=sc.nextInt();
c=a+b;
Sample I/O:
65
23
After Swap:
23
65
*/
//write code here
import java.util.Scanner;
class SwapTest{
s1.input();
s1.process();
s1.output();
class Swap
int a,b,temp;
void input()
a=sc.nextInt();
b=sc.nextInt();
void process()
temp=a;
a=b;
b=temp;
void output()
{
System.out.println("After Swap:\n"+a+"\n"+b);
3. /* Program to read amount in rupees. If amount is >=300 print idly, vada, dosa and puri followed by glass of water.
sample I/O
sample 1
output:
400
Idly
Vada
Dosa
Puri
glass of water
sample 2
30
glass of water
*/
import java.util.Scanner;
class Tiffin
int amt;
void process()
{
if(amt>=300)
System.out.println("Idly");
System.out.println("Vada");
System.out.println("Dosa");
System.out.println("Puri");
System.out.println("glass of water");
class TiffinTest{
t.amt=s.nextInt();
t.process();
Sample I/O
15.50
Area of circle:754.7676350249478
Perimeter of circle:97.38937226128358
*/
import java.util.Scanner;
//create a class
class Circle{
double r;
double getArea()
return(Math.PI*r*r);
double getPerimeter()
return(Math.PI*2*r);
c.r=s.nextDouble();
};
5. /*Write a java program to read three subject marks and display pass or fail.
Sample I/O:
case 1:
60
20
50
Fail
case 2:
70
802
90
Pass
*/
class Result
p=a;
q=b;
r=c;
void process()
System.out.println("Pass");
else
System.out.println("Fail");
class ResultTest{
int m1,m2,m3;
m1=s.nextInt();
m2=s.nextInt();
m3=s.nextInt();
r1.process();
}
Sample Input
42
3.1415
true
Sample Output
Boolean: true
Double: 3.1415
Byte: 42
Sample I/O-2:
128
Value:"128" Radix:10
at java.util.Scanner.nextByte(Unknown Source)
at java.util.Scanner.nextByte(Unknown Source)
at Demo.main(Demo.java:23)
*/
import java.util.Scanner;
class DataType
byte a;
double b;
boolean c;
a=sc.nextByte();
b=sc.nextDouble();
c=sc.nextBoolean();
System.out.println("Boolean:"+" "+c);
System.out.println("Double:"+" "+b);
System.out.println("Byte:"+" "+a);
7. /*program to find the sum of the individual digits of the given number.
Sample I/O:
1234
Sum of digits: 10
*/
import java.util.Scanner;
class Demo{
s.input();
s.process();
s.output();
class SumOfDigits
void input()
{
n=c.nextInt();
void process()
while(n>=1)
m=n%10;
sum=sum+m;
n=n/10;
void output()
the properties customer name,account number & balance and a methods to deposit,
Charge a 5 penalty if an attempt is made to withdraw more money than available in the account.
Sample Output:
3000
1000
1000
2000
*/
import java.util.Scanner;
class Account
String name;
long num;
double balance;
this.name=name;
this.num=num;
this.balance=balance;
}
public void withdraw(double z)
z=sc.nextDouble();
if(z>balance)
balance=balance-5;
else
balance=balance-z;
z=sc.nextDouble();
balance=balance+z;
return(balance);
class TestAccount
double x;
b.withdraw(2500);
b.deposit(500);
56
*/
import java.util.Scanner;
class Area
return(3.14*a*a);
return(a*b);
class Overloading
int a,b,c;
a=s.nextInt();
b=s.nextInt();
10.Varargs Programs
import java.util.Scanner;
class Area
return(3.14*a*a);
return(a[0]*a[1]);
class Overloading
int a,b,c;
a=s.nextInt();
b=s.nextInt();
11. /*Write a Java program that prints the numbers from 1 to 50. But for multiples of three print "Fizz" instead of
the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and
SAMPLE OUTPUT:
Fizz
Buzz
Fizz
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
*/
class FizzBuzzTest
for(int i=1;i<=50;i++)
System.out.println("FizzBuzz");
System.out.println("Buzz");
System.out.println("Fizz");
else
System.out.println(i);
12. /* Write a Java Program To Calculate Sum Of First And Last Digit Of A Number
*/
import java.util.Scanner;
class Sum
int n=sc.nextInt();
int last=n%10;
int first=0;
while(n>=1)
{
first=n;
n=n/10;
13. /* Write a Java Program To Calculate Perfect Squares Between Two Numbers
Sample I/O:
*/
import java.util.*;
class Squares
int a,b;
a=sc.nextInt();
b=sc.nextInt();
for(int i=a;i<=b;i++)
if(i%Math.sqrt(i)==0)
System.out.println(i);
}
14. /*Java Program To Find All Pairs Of Elements In An Array Whose Sum Is Equal To A Given Number :
Sample Output :
4 + 6 = 10
5 + 5 = 10
-10 + 20 = 10
12 + 38 = 50
23 + 27 = 50
125 + -75 = 50
*/
static void findThePairs(int inputArray[],int inputNumber)// start writing the code here
for(int i=0;i<inputArray.length;i++)
for(int j=i+1;j<inputArray.length;j++)
if(inputArray[i]+inputArray[j]==inputNumber)
}
public static void main(String[] args)
findThePairs(new int[] {12, 23, 125, 41, -75, 38, 27, 11}, 50);
15. /*
Write a java program to find the no. of times each charecter repeated in a given String.
Sample Input/Output:
Example 1:
java
Example 2:
hello
*/
class RepetitionsInString
String a,temp="";
int i,j,cnt=0;
a=s.nextLine();
for(i=0;i<a.length();i++)
char c=a.charAt(i);
for(j=i;j<a.length();j++)
char c2=a.charAt(j);
cnt++;
if(temp.indexOf(c)==-1)
temp+=c;
cnt=0;
Sample Output:
*/
import java.util.*;
class CountTheWords
{
public static void main(String[] args)
String a;
int n;
a=s.nextLine();
n=ar.length;
17. /* Write a Java Program To Calculate Sum Of First And Last Digit Of A Number
SAMPLE INPUT/OUTPUT:
456
*/
import java.util.Scanner;
class Sum
int num;
num=sc.nextInt();
int last=num%10;
int first=0;
while(num>=1)
first=num;
num=num/10;
}
a house number,
a street,
a city,
a state and a
postal code.
Supply a print function that prints the address with the street on one line and the city,
Sample output:
Street: Narayanguda
*/
import java.util.*;
class Address
int hno,oan;
String str;
String city;
String state;
int pc;
Address()
}
Address(int oan)
str="Narayanguda";
city="Hyd";
state="Telengana";
pc=500021;
System.out.println("Street: "+str);
class Test
add.print("Narayanguda","Hyd","Telengana",500021);
19. /*Write a Java Program to define a class,define instance methods for setting and Retrieving values of
SAMPLE OUTPUT:
Name:smith
ID:1234
Address:narayanguda
*/
import java.util.*;
class empdemo
e.setData("smith",1234,"narayanguda");
e.putData();
class Employee
n="smith";
num=1234;
add="narayanguda";
void putData()
String nam="smith";
int nu=1234;
String addre="narayanguda";
System.out.println("Name:"+nam);
System.out.println("ID:"+nu);
System.out.println("Address:"+addre);
*/
import java.util.*;
class add_demo
obj.display(10,20);
obj.display2(10.2,20.2);
class Sum
i=10;
j=20;
int add=i+j;
y=10.2;
z=20.2;
double add=y+z;
}
21. /*Program to read person's age and display eligible to vote or not.
SAMPLE I/O:
CASE 1:
23
CASE 2:
16
*/
import java.util.Scanner;
class VoteTest{
int age;
age=s.nextInt();
v.process();
class Vote
int a;
Vote(int i)
a=i;
}
void process()
if(a>=18)
else
create a sub class Result with total and average and result.
Sample I/O:
Case 1:
Enter id:
Enter name:
abc
40
50
60
Student id:1
Name :abc
Subject1 :40
Subject2 :50
Subject3 :60
Total is :150
Average is:50.0
CASE 2:
Student id:2
Name :xyz
Subject1 :70
Subject2 :0
Subject3 :90
Total is :160
Average is:53.0
result is :Fail
CASE 3:
Student id:3
Name :mno
Subject1 :88
Subject2 :99
Subject3 :100
Total is :287
Average is:95.0
result is :Distinction
CASE 4:
Student id:4
Name :pqr
Subject1 :66
Subject2 :59
Subject3 :70
Total is :195
Average is:65.0
*/
import java.util.*;
class StudentInheritanceTest
int id,m1,m2,m3;
String name;
System.out.println("Enter id:");
id=s.nextInt();
System.out.println("Enter name:");
name=s.next();
m1=s.nextInt();
m2=s.nextInt();
m3=s.nextInt();
r.process();
r.output();
class Student
int id;
String name;
int m1,m2,m3;
this.id=id;
this.name=name;
this.m1=m1;
this.m2=m2;
this.m3=m3;
void output()
System.out.println("Student id:"+id);
System.out.println("Name :"+name);
System.out.println("Subject1 :"+m1);
System.out.println("Subject2 :"+m2);
System.out.println("Subject3 :"+m3);
int total;
double avg;
String result;
super(id,name,m1,m2,m3);
void process()
total=m1+m2+m3;
avg=total/3;
if(avg>=70)
result="Distinction";
else if(avg>=60 && avg<70)
result="First Division";
result="Second Division";
result="Third Division";
else
result="Fail";
void output()
super.output();
System.out.println("Total is :"+total);
System.out.println("Average is:"+avg);
System.out.println("result is :"+result);
Sample I/O:
*/
Shapes s[];
s=new Shapes[10];
s[0]=new Rectangle();
s[1]=new Triangle();
s[2]=new Circle();
for(int i=0;i<3;i++)
s[i].printArea(10,20);}
int a,b;
double c=3.14;
}
class Triangle extends Shapes
24. /* You are given a class Test with a main method to demonstrate static modifier.
Sample I/O:
*/
}
}
class Student
static
cnt=0;
String na;
long b,l;
na=a;
this.b=b;
this.l=l;
cnt++;
return cnt;
25. /*Q2) Read the content of the file ex2.txt, count and display number of characters,
younus shariff
tejaswitha)
Sample I/O:
*/
import java.io.*;
class CountCWL
int i=0,cnt1=0,cnt2=0,cnt=0;
while(true)
i=fp.read();
if(i==-1)
break;
cnt1++;
if((char)i=='\n')
cnt2++;
cnt++;
26. /*(Q)Copy the content of the file ex1.txt to abc.txt a byte at a time.
shivaram
Sample Output:
shivaram
*/
import java.io.*;
class FileCopy1
int ch;
while(true)
ch=fis1.read();
if(ch==-1)
break;
fos.write((char)ch);
// code for displaying the content of abc.txt file. is already given below
//Read characters from fis2 into ch and write onto the monitor,repeat this till end of the file is reached
while(true)
ch=fis2.read();
if(ch==-1)
break;
System.out.print((char)ch);
fis2.close();
Read all the numbers from file6.dat and write all even numbers into the file 'even.dat',
SAMPLE OUTPUT:
11 33 55
*/
import java.io.*;
import java.util.*;
class FileRW
int i,x;
dos.writeInt(22);
dos.writeInt(33);
dos.writeInt(44);
dos.writeInt(55);
dos.close();
while(dis.available()>0)
x=dis.readInt();
if(x%2==0)
dos1.writeInt(x);
else
dos2.writeInt(x);
dis.close();
dos1.close();
dos2.close();
// Code For Displaying the contents of the file 'odd.dat' is givenm below.
while(dis2.available()>0)
x=dis2.readInt();
System.out.print(x+" ");
dis2.close();
28. /*
Display the name of the student for the given roll number.
SAMPLE OUTPUT:
CASE 1:
15BD1A0503
STUDENT NAME=kiran
CASE 2:
15BD1A0508
*/
import java.io.*;
import java.util.*;
String rno;
String name;
this.rno=rno;
this.name=name;
class ObjectIO
// Writing the details of three students on to the file 'student1.dat' is given below
oos.writeObject(s1);
oos.writeObject(s2);
oos.writeObject(s3);
oos.close();
// write the code for Displaying the name of the student for the given roll number.
String r;
System.out.println("enter the student roll number:");
r=s.next();
if(r.equals(s1.rno))
System.out.println("STUDENT NAME="+s1.name);
else if(r.equals(s2.rno))
System.out.println("STUDENT NAME="+s2.name);
else if(r.equals(s3.rno))
System.out.println("STUDENT NAME="+s3.name);
else
29. /*create a thread that prints the multiplication table for number 5
Sample output:
5 *1 = 5
5 *2 = 10
5 *3 = 15
5 *4 = 20
5 *5 = 25
5 *6 = 30
5 *7 = 35
5 *8 = 40
5 *9 = 45
5 *10 = 50
*/
int f=5;
public void run()
for(int i=1;i<=10;i++)
class MyThread1
f.start();
30. /*Write a program that displays 5th and 6th mathematical tables.
SAMPLE I/O:
5 *1 = 5
5 *2 = 10
5 *3 = 15
5 *4 = 20
5 *5 = 25
5 *6 = 30
5 *7 = 35
5 *8 = 40
5 *9 = 45
5 *10 = 50
6 *1 = 6
6 *2 = 12
6 *3 = 18
6 *4 = 24
6 *5 = 30
6 *6 = 36
6 *7 = 42
6 *8 = 48
6 *9 = 54
6 *10 = 60
*/
for(int i=1;i<=10;i++)
class MultipleTables2
f.start();
f.join();
for(int i=1;i<=10;i++)
31. /*
Write a Java program that implements a multi-thread application that has three threads.
if the value is even,second thread computes the square of the number and prints.
If the value is odd, the third thread will print the value of cube of the number.
input/output:
--------------
case 1:
Enter x value :
X=4 SQUARE=16
case 2:
Enter x value :
X=5 CUBE=125
*/
import java.util.*;
int x;
Thread2(int a)
{
x=a;
System.out.println("X="+x+" SQUARE="+(x*x));
int x;
Thread3(int a)
x=a;
System.out.println("X="+x+" CUBE="+(x*x*x));
class Thread1
int x=sc.nextInt();
if(x%2==0)
t2.start();
else
{
t3.start();
32. /**
Producer is waiting...
Product3 is consumed.
Consumer is waiting...
Product4 is produced.
Producer is waiting...
Product4 is consumed.
Consumer is waiting...
Product5 is produced.
Producer is waiting...
Product5 is consumed.
Consumer is waiting...
Product6 is produced.
Producer is waiting...
Product6 is consumed.
Consumer is waiting...
Product7 is produced.
Producer is waiting...
Product7 is consumed.
Consumer is waiting...
Product8 is produced.
Producer is waiting...
Product8 is consumed.
Consumer is waiting...
Product9 is produced.
Producer is waiting...
Product9 is consumed.
Consumer is waiting...
Product10 is produced.
Product10 is consumed.
*/
class Buffer
int a;
if(produced)
System.out.println("Producer is waiting...");
try{
wait();
}catch(Exception e){
System.out.println(e);
a=x;
produced = true;
notify();
if(!produced)
{
System.out.println("Consumer is waiting...");
try
wait();
catch(Exception e){}
produced=false;
notify();
Buffer b;
public Producer(Buffer b)
this.b = b;
b.produce(i);
Buffer b;
Consumer(Buffer b)
this.b=b;
for(int count=1;count<=10;count++)
b.consume();
//starting threads.
p.start();
c.start();
class Test
f.setVisible(true);
//f.setSize(400,700);
//f.setLocation(100,100);
f.setBounds(500,100,300,400);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//DO_NOTHING,EXIT,HIDE
f.setTitle("KMIT");
import java.awt.Container;
import java.awt.Color;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.ImageIcon;
public Test()
setVisible(true);
//setSize(400,700);
//setLocation(100,100);
setBounds(500,100,800,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("KMIT");
//setResizable(false);
Container c=getContentPane();
c.setBackground(Color.yellow);
add(l);
setLayout(null);
l.setBounds(100,100,400,300);
l.setForeground(Color.blue);
l.setFont(f);
l.setToolTipText("This is label");
}
public static void main(String args[])
new Test();
import javax.swing.JPasswordField;
import javax.swing.JButton;
class Test
f.setSize(300,150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(null);
t1.setBounds(20,20,120,30);
f.add(t1);
b1.setBounds(75,60,80,50);
f.add(b1);
f.setVisible(true);
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JLabel;
class Test
f.setBounds(500,100,800,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Demo application");
f.setLayout(null);
l1.setBounds(10,10,80,25);
l2.setBounds(10,30,80,25);
f.add(l1);
f.add(l2);
t1.setBounds(100,10,160,25);
t2.setBounds(100,10,160,25);
f.add(t1);
f.add(t2);
p1.setBounds(100,40,160,25);
p2.setBounds(100,40,160,25);
f.add(p1);
f.add(p2);
b1.setBounds(10,80,80,25);
b2.setBounds(180,80,150,25);
f.add(b1);
f.add(b2);
f.setVisible(true);
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.FlowLayout;
class Test
f.setSize(500,150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
f.add(l);
f.add(t);
f.add(b);
f.setVisible(true);
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
Test()
setSize(300,150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(b);
setVisible(true);
@Override
new Test();
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
Test()
{
setSize(300,150);
setTitle("Event");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
setVisible(true);
@Override
setBackground(Color.yellow);
new Test();
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b;
Test()
setSize(500,150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
l3=new JLabel("Result");
t1=new JTextField(8);
t2=new JTextField(8);
t3=new JTextField(8);
b=new JButton("Divide");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b);
b.addActionListener(this);
setVisible(true);
@Override
try
int a=Integer.parseInt(t1.getText());
int b=Integer.parseInt(t2.getText());
float c=a/b;
t3.setText(""+c);
catch(ArithmeticException e1)
JOptionPane.showMessageDialog(null,e1.getMessage());
catch(NumberFormatException e2)
JOptionPane.showMessageDialog(null,e2.getMessage());
new Test();
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import java.awt.Container;
JLabel l;
JTextField t;
Container c;
Test()
f.setSize(700,150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
t=new JTextField(20);
f.add(l);
f.add(t);
c=f.getContentPane();
f.setVisible(true);
t.addActionListener(this);
@Override
String s=e.getActionCommand();
switch(s)
case "red":c.setBackground(Color.red);
break;
case "yellow":c.setBackground(Color.yellow);
break;
case "blue":c.setBackground(Color.blue);
break;
default:JOptionPane.showMessageDialog(null,"Wrong Input");
break;
new Test();
42.//PRACTICE LAB
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.awt.event.FocusListener;
import java.awt.event.FocusEvent;
import javax.swing.JButton;
JButton b;
JTextField t;
Test()
f.setSize(500,150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
t=new JTextField(20);
b=new JButton("Click");
f.add(t);
f.add(b);
f.setVisible(true);
t.addFocusListener(this);
@Override
t.setText(" ");
new Test();
}
43.//PRACTICE LAB
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JLabel;
JTextField t;
JLabel l;
Test()
f.setSize(500,150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
t=new JTextField(20);
l=new JLabel();
f.add(t);
f.add(l);
f.setVisible(true);
t.addKeyListener(this);
@Override
String ch=t.getText();
String word[]=ch.split("\\s");
new Test();
44.//PRACTICE LAB
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
JLabel l;
Test()
f.setSize(500,150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
l=new JLabel();
f.add(l);
l.setFont(new Font("Arieal",Font.BOLD,25));
//l.setColor(Color.blue);
f.setVisible(true);
f.addMouseListener(this);
f.addMouseMotionListener(this);
@Override
l.setText("Mouse Entered");
l.setText("Mouse Exited");
l.setText("Mouse Pressed");
l.setText("Mouse Released");
l.setText("Mouse Clicked");
l.setText("Mouse Dragging");
l.setText("Mouse Moving");
new Test();
}
}
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
//import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
JLabel l;
Test()
f.setSize(500,150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
l=new JLabel();
f.add(l);
l.setFont(new Font("Arieal",Font.BOLD,25));
//l.setColor(Color.blue);
f.setVisible(true);
f.addMouseListener(this);
@Override
l.setText("Mouse Entered");
l.setText("Mouse Released");
}
l.setText("Mouse Clicked");
new Test();
46.