Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Programs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

INDEX
Exp. NAME OF THE DATE Pg. Signa-
No. EXPERIMENT Performed Submitted Grade No. ture
1 1.Write a small program of
about 10 to 15 lines which
contains at least one if else
condition and a for loop?
2. Write a java program that
works as a simple calculator
for the +,-,*,/,% operations
2 using classes and objects in
java?
3. Write a java program to find
result of a given arithmetic
expression?
4. Write a program to
demonstrate the following
3 i)Single inheritance ii) Multi –
level inheritance
5. Write a program to
demonstrate the usage of
method overriding, calling
super class Constructor in
derived class.
6. Write a java program to
create an abstract class named
shape that contains two
integers and an empty method
named printarea(). Provide
4 three classes named
Rectangle, Triangle and Circle
such that each one of these
classes extends the class
Shape. Each one of the classes
contains only the method
printarea() that prints the area
of the given shape.
7. Write a program to
demonstrate method
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
overloading and constructor
overloading.
8. Write a program to
5 demonstrate polymorphism
using interface(interface in
package P1 and class in
package P2)

9. Develop an applet in java


that displays a simple
message?

10. Write a java program that


creates a user interface to
perform integer divisions. The
6 user enters two numbers in
the text fields, num1 and
Num2. The division of Num1
and Num2 is displayed in the
result fields when the division
button is clicked. If Num1 or
Num2 were not an integer,
the program should throw a
Number Format Exception. If
Num2 were Zero the program
should throw an Arithmetic
Exception. Display the
exception in a message dialog
box.
7 11.Write a java program that
implements a multi-thread
application that has three
threads. First thread generates
random integer every 1
second. if the generated value
is even , second thread
computes the square of the
number and prints. If the
generated value is odd, the
third thread will print the
value of cube of the number?
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
12. Write a java program to
demonstrate Generic class and
8 generic methods
13. Write a java to perform
string operations using sting
buffer class and its methods?
14.Write a java program that
simulates a traffic light. The
program lets the user select
one of three lights: red,
yellow, or green with radio
9 buttons. On selecting a
button, an appropriate
message with ―Stop‖ or
―ready‖ or ―Go‖ should
appear above the buttons in
selected color initially, there is
no message shown?
10 15. Write a java program that
loads names and phone
numbers from a text file
where the data is organized as
one line per record and each
field in a record are separated
by a tab(\t). it takes a name or
phone number as input and
prints the corresponding other
value from the hash table (hint
: use hash tables).
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

WEEK-1
1.Use Eclipse or Net bean platform and acquaint with the various menus. Create a
test project, add a test class, and run it. See how you can use auto suggestions, auto
fill. Try code formatter and code refactoring like renaming variables, methods, and
classes. Try debug step by step with a small program of about 10 to 15 lines which
contains at least one if else condition and a for loop?
import java.util.*;
class prime
{
int isprime(int n)
{
int i,t=0;
for(i=2;i<=n/2;i++)
if(n%i==0)
return 0;
return 1;
}
public static void main(String args[])
{
prime p=new prime();
int i,n;
Scanner s=new Scanner(System.in);
System.out.print("Enter n : ");
n=s.nextInt();
for(i=2;i<=n;i++)
{
int c=p.isprime(i);
if(c==1)
System.out.print(i+" ");
}
}
}
OUTPUT:-
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

WEEK-2
2.Write a java program that works as a simple calculator for the +,-,*,/,% operations
using classes and objects in java ?
import java.util.*;
class simple_calculator
{
int a,b;
char ch;
public void read()
{
Scanner s= new Scanner(System.in);
System.out.print("ENTER THE TWO NUMBERS FOR THE OPERATION:");
a = s.nextInt();
b = s.nextInt();
System.out.println("\nSELECT THE OPERATION:");
System.out.println(" 1.ADDITION(+)\t 2.SUBTRACTION(-)");
System.out.println(" 3.MULTIPLICATION(*)\t4.DIVISON(/)");
System.out.println(" 5.MOD OPERATOR(%)");
ch = s.next().charAt(0);
}
public void result()
{
switch(this.ch)
{
case '1': System.out.println("SUM:"+(this.a + this.b)); break;
case '2': System.out.println("DIFFERENCE:"+(this.a - this.b));break;
case '3': System.out.println("PRODUCT:"+(this.a * this.b));break;
case '4': System.out.println("QUOTIENT:"+(int)(this.a/this.b));break;
case '5': System.out.println("REMAINDER:"+(this.a % this.b));break;
default: System.out.println("INVALID OPERATOR");
}
}

}
public class week1_1
{
public static void main(String args[])
{
simple_calculator sc1 = new simple_calculator();
sc1.read();
sc1.result();
}
}
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
OUTPUT:-

3. Write a java program to find result of a given arithmetic expression?(EX: if you


given arithmetic expression like 10+20-24*4/2-4.5= it should print 7.50)
import java.util.*;
public class week1_2
{
public static void main(String args[])
{
float a,b,sum=0;
char ch;
Scanner s = new Scanner(System.in);
a=s.nextFloat(); sum=a;
do
{
ch = s.next().charAt(0);
if(ch != '=')
{
b = s.nextFloat();
switch(ch)
{
case '+': sum += b; break;
case '-': sum -=b; break;
case '*': sum *= b; break;
case '/': sum /= b; break;
case '%': sum %=b; break;
}
}
}
while(ch != '=');
System.out.println(sum);
}
}
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

WEEK-3
4. Write a program to demonstrate the following:

i) Single inheritance
import java.util.*;
class student
{
String name,rno;
public void read1()
{
Scanner s = new Scanner(System.in);
System.out.print("ENTER THE NAME AND ROLLNO:");
name = s.next();
rno = s.next();
}
public void display1()
{
System.out.println("NAME:"+name+"\nROLLNO:"+rno);
}
}
class marks extends student
{
int m;
public void read2()
{
Scanner s = new Scanner(System.in);
System.out.print("ENTER THE MARKS OF "+this.name+":");
m = s.nextInt();
}
public void display2()
{
System.out.println("MARKS:"+m);
}
}
public class week2_1
{
public static void main(String args[])
{
marks m = new marks();
m.read1();
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
m.read2();
m.display1();
m.display2();
}
}
ii) Multi –level inheritance?
import java.util.*;
class student
{
String name,rno;
public void read1()
{
Scanner s = new Scanner(System.in);
System.out.print("ENTER THE NAME AND ROLLNO:");
name = s.next();
rno = s.next();
}
public void display1()
{
System.out.println("NAME:"+name+"\nROLLNO:"+rno);
}
}
class marks extends student
{
int m;
public void read2()
{
Scanner s = new Scanner(System.in);
System.out.print("ENTER THE MARKS OF "+this.name+":");
m = s.nextInt();
}
public void display2()
{
System.out.println("MARKS:"+m);
}
}
class grade extends marks
{
char c;
public void read3()
{
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
Scanner s = new Scanner(System.in);
System.out.print("ENTER THE GRADE OF "+this.name+":");
c = s.next().charAt(0);
}
public void display3()
{
System.out.println("GRADE:"+c);

}
}
public class week2_1
{
public static void main(String args[])
{
grade g = new grade();
g.read1();
g.read2();
g.read3();
g.display1();
g.display2();
g.display3();
}
}
5. Write a program to demonstrate the usage of method overriding, calling super
class Constructor in derived class?
import java.util.*;
class student
{
String name,rno;
student(String name,String rno)
{
this.name = name;
this.rno = rno;
}

public void display()


{
System.out.println("NAME:"+name+"\nROLLNO:"+rno);
}
}
class marks extends student
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
{
int m;
marks(String name,String rno,int m)
{
super(name,rno);
this.m = m;
}
public void display()
{
super.display();
System.out.println("MARKS:"+m);
}
}
public class week2_2
{
public static void main(String args[])
{
String name,rno;
int m;
Scanner s = new Scanner(System.in);
System.out.print("ENTER THE NAME AND ROLLNO:");
name = s.next(); rno = s.next();
System.out.print("ENTER THE MARKS OF "+name+":");
m = s.nextInt();
marks mt = new marks(name,rno,m);
mt.display();
}
}

OUTPUT:-
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

WEEK-4
6. Write a java program to create an abstract class named shape that contains two
integers and an empty method named printarea(). Provide three classes named
Rectangle, Triangle and Circle such that each one of these classes extends the class
Shape. Each one of the classes contains only the method printarea() that prints the
area of the given shape.
import java.util.*;
abstract class shape
{
int x,y;
shape(int a,int b)
{
y=b;
x =a;
}
void printarea(){}
}
class Rectangle extends shape
{
Rectangle(int a,int b)
{
super(a,b);
}
void printarea()
{
double f = (super.x)*(super.y);
System.out.printf("Area of rectangle is:%.1f",f);
}
}
class circle extends shape
{
circle(int a,int b)
{
super(a,b);
}
void printarea()
{
double f = 3.14*(super.x)*(super.x);
System.out.printf("Area of circle is:%.1f\n",f);
}
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
}
class triangle extends shape
{
triangle(int a,int b)
{
super(a,b);
}
void printarea()
{
double f = 0.5*(super.x)*(super.y);
System.out.printf("Area of triangle is:%.1f",f);
}
}
public class week3_1
{
public static void main(String[] args)
{
int a,b;
Scanner s = new Scanner(System.in);
System.out.printf("ENTER THE RADIUS OF A CIRCLE:");
a = s.nextInt();
circle c = new circle(a,0);
c.printarea();
System.out.printf("ENTER THE HEIGHT & BASE OF A TRIANGLE:");
a = s.nextInt();
b= s.nextInt();
triangle t = new triangle(a,b);
t.printarea();
System.out.printf("\nENTER THE LENGTH & BREADTH OF A RECTANGLE:");
a = s.nextInt();
b= s.nextInt();
Rectangle r = new Rectangle(a,b);
r.printarea();
}
}
OUTPUT:-
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

WEEK-5
7. Write a program to demonstrate method overloading and constructor overloading?

import java.util.*;
class student
{
int m1,m2,m3,avg;
student()
{
m1=m2=m3=avg=0;
}
student(int m1,int m2,int m3)
{
this.m1=m1;
this.m2=m2;
this.m3=m3;
avg =(int) ( m1+m2+m3)/3;
}
student(student s)
{
m1=s.m1;
m2 = s.m2;
m3 = s.m3;
avg =(int) ( (s.m1)+(s.m2)+(s.m3))/3;
}
void display(String name)
{
System.out.println("AVERAGE MARKS OF "+name+" IS:"+this.avg);
}
void display(String name,char c)
{
System.out.println("AVERAGE MARKS OF "+name+" IS "+this.avg+" WITH GRADE "+c);
}
}
public class week4_1
{
public static void main(String[] args)
{
Scanner st = new Scanner(System.in);
int m1,m2,m3;
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
String s; char c;
System.out.print("ENTER THE NAME:");
s = st.next();
System.out.print("ENTER THE MARKS:");
m1 = st.nextInt(); m2 = st.nextInt(); m3 = st.nextInt();
System.out.print("ENTER THE GRADE:");
c = st.next().charAt(0);
student s1 = new student(m1,m2,m3);
student s2 = new student(s1);
s1.display(s);
s2.display(s,c);
}
}

OUTPUT:-

8. Write a program to demonstrate polymorphism using interface(interface in package


P1 and class in package P2)?

Interface (myinterface) is
successfully compiled and
imported into a Package P1;

package p2;
import P1.*;
import java.util.*;
class person implements myinterface
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
{
String name,loc;
public void getdata()
{
Scanner s = new Scanner(System.in);
System.out.print("ENTER THE NAME AND LOCATION:");
name = s.next(); loc=s.next();
}
public void display()
{
System.out.print("NAME:"+name+"\nLOCATION:"+loc);
}
}
class student extends person implements myinterface
{
String name,rno;
int m;
public void getdata()
{
Scanner s = new Scanner(System.in);
System.out.print("\nENTER THE NAME,ROLL.NO AND MARKS:");
name = s.next(); rno = s.next(); m = s.nextInt();
}
public void display()
{
System.out.print("NAME:"+name+"\nROLL.NO:"+rno+"\nMARKS:"+m);
}
}
public class polymorphism
{
public static void main(String[] args)
{
person p = new person();
person poly = new student(); //upcasting
p.getdata(); p.display();
// Runtime Polymorphism
poly.getdata(); poly.display();
}
}
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

WEEK-6
9. Develop an applet in java that displays a simple message?
import java.awt.*;
import java.applet.*;
/*
<applet code="sim" width=300 height=300>
</applet>
*/
public class sim extends Applet
{
String msg=" ";
public void init()
{
msg+="init()--->";
setBackground(Color.orange);
}
public void start()
{
msg+="start()--->";
setForeground(Color.blue);
}
public void paint(Graphics g)
{
msg+="paint()--->";
g.drawString(msg,200,50);
}
}

10. Write a java program that creates a user interface to perform integer divisions.
The user enters two numbers in the text fields, num1 and Num2. The division of
Num1 and Num2 is displayed in the result fields when the division button is clicked. If
Num1 or Num2 were not an integer, the program should throw a Number Format
Exception. If Num2 were Zero the program should throw an Arithmetic Exception.
Display the exception in a message dialog box.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class A extends JFrame implements ActionListener
{
JLabel l1,l2,l3;
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
JTextField tf1,tf2,tf3;
JButton b1;
A()
{
setLayout(new FlowLayout());
JLabel l=new JLabel("welcome");
add(l);
setSize(800,400);
l1=new JLabel("enter number1");
add(l1);
tf1=new JTextField(10);
add(tf1);
l2=new JLabel("enter number2");
add(l2);
tf2=new JTextField(10);
add(tf2);
l3=new JLabel("result");
add(l3);
tf3=new JTextField(10);
add(tf3);
b1=new JButton("Division");
add(b1);
b1.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
try
{
int a=Integer.parseInt(tf1.getText());
int b=Integer.parseInt(tf2.getText());
if(b==0)
throw new ArithmeticException("division by Zero");
float c=(float)a/b;
tf3.setText(String.valueOf(c));
}
catch(NumberFormatException ex)
{
JOptionPane.showMessageDialog(this,ex.getMessage());
}
catch(ArithmeticException ex)
{
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
JOptionPane.showMessageDialog(this,ex.getMessage());
}
}
}
class week6_2
{
public static void main(String[] args)
{
A a=new A();
}
}
OUTPUT:-
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

WEEK-7
11.Write a java program that implements a multi-thread application that has three
threads. First thread generates random integer every 1 second. if the generated value
is even , second thread computes the square of the number and prints. If the
generated value is odd, the third thread will print the value of cube of the number?
import java.util.*;
public class Multithreading
{
public static void main(String args[])
{
sample s = new sample();
s.start();
}
}
class even extends Thread
{
public int x;
public even(int num)
{ x=num; }
public void run()
{
System.out.println("New thread "+x+" is even and square of "+x+" is : "+(x*x));
}
}
class odd extends Thread
{
public int x;
public odd(int num)
{ x=num; }
public void run()
{
System.out.println("New thread "+x+" is odd and cube of "+x+" is : "+(x*x*x));
}
}
class sample extends Thread
{
int num=0;
public void run()
{
Random r=new Random();
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
for(int i=1;i<=6;i++)
{
num=r.nextInt(200);
System.out.println("Main thread and generated number is "+num);
try
{
if(num%2==0)
{
even e=new even(num);
e.start();
}
else
{
odd o=new odd(num);
o.start();
}
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("-------------------");
}
}
}
OUTPUT:-
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

WEEK-8
12.Write a java program to demonstrate Generic class and generic methods?
public class Test<T>
{
T obj;
Test(T obj)
{
this.obj=obj;
}
public T getobject()
{
return this.obj;
}
public static <T> void printArray(T[] inputArray)
{
for(T element:inputArray)
System.out.print(element+" ");
System.out.println();
}

public static void main(String args[])


{
Test<Integer> iobj=new Test<Integer>(15);
System.out.println(iobj.getobject());
Test<String> sobj=new Test<String>("CMRCET");
System.out.println(sobj.getobject());
Integer[] intArray={1,2,3,4,5};
printArray(intArray);
Double[] doubleArray={1.1,2.2,3.3,4.4,5.5};
printArray(doubleArray);
Character[] charArray={'h','e','l','l','o'};
printArray(charArray);
}
}
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

13. Write a java to perform string operations using sting buffer class and its methods?

import java.io.*;
public class stringbuffer
{
public static void main(String args[])
{
StringBuffer s=new StringBuffer("CMRCET");
s.insert(6,"COLLEGE");
System.out.println(s);
s.insert(0,5);
System.out.println(s);
s.insert(3,true);
System.out.println(s);
s.append("JAVA");
System.out.println(s);
char s_arr[]={'C','S','E'};
s.insert(0,s_arr);
System.out.println(s);
s.reverse();
System.out.println(s);
s.delete(0,5);
System.out.println(s);
s.deleteCharAt(7);
System.out.println(s);
s.replace(5,8,"are");
System.out.println(s);
}
};
OUTPUT:-
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

WEEK-9
14.Write a java program that simulates a traffic light. The program lets the user select
one of three lights: red, yellow, or green with radio buttons. On selecting a button, an
appropriate message with ―Stopǁ or ―readyǁ or ―Goǁ should appear above the
buttons in selected color initially, there is no message shown?
//Program for implementing Traffic Signals
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="Signals" width=400 height=250></applet>*/
public class Signals extends Applet implements ItemListener
{
String msg="";
Checkbox stop,ready,go;
CheckboxGroup cbg;
public void init()
{
cbg = new CheckboxGroup();
stop = new Checkbox("Stop", cbg, false);
ready = new Checkbox("Ready", cbg, false);
go= new Checkbox("Go", cbg, false);
add(stop);
add(ready);
add(go);
stop.addItemListener(this);
ready.addItemListener(this);
go.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg=cbg.getSelectedCheckbox().getLabel();
g.drawOval(165,40,50,50);
g.drawOval(165,100,50,50);
g.drawOval(165,160,50,50);
if(msg.equals("Stop"))
{
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
g.setColor(Color.red);
g.fillOval(165,40,50,50);
}
else if(msg.equals("Ready"))
{
g.setColor(Color.yellow);
g.fillOval(165,100,50,50);
}
else
{
g.setColor(Color.green);
g.fillOval(165,160,50,50);
}
}
}
OUTPUT:-
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY

WEEK-10
15. Write a java program that loads names and phone numbers from a text file where
the data is organized as one line per record and each field in a record are separated
by a tab(\t). it takes a name or phone number as input and prints the corresponding
other value from the hash table (hint : use hash tables)?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
public class HashTab
{
public static void main(String[] args)
{
HashTab prog11 = new HashTab();
Hashtable<String, String>hashData = prog11.readFromFile("HashTab.txt");
System.out.println("File data into Hashtable:\n"+hashData);
prog11.printTheData(hashData, "vbit");
prog11.printTheData(hashData, "123");
prog11.printTheData(hashData, "----");
}
private void printTheData(Hashtable<String, String>hashData, String input)
{
String output = null;
if(hashData != null)
{
Set<String> keys = hashData.keySet();
if(keys.contains(input)) {
output = hashData.get(input);
}
else
{
Iterator<String> iterator = keys.iterator();
while(iterator.hasNext()) {
String key = iterator.next();
String value = hashData.get(key);
if(value.equals(input))
{
output = key;
break;
}}}}
System.out.println("Input given:"+input);
CMR COLLEGE OF ENGINEERING AND TECHNOLOGY
if(output != null)
{
System.out.println("Data found in HashTable:"+output);
}
else {
System.out.println("Data not found in HashTable");
}}
private Hashtable<String, String>readFromFile(String fileName) {
Hashtable<String, String> hashData = new Hashtable<String, String>();
try {
File f = new File("D:\\java\\"+fileName);
br = new BufferedReader(new FileReader(f));
String line = null;
while((line = br.readLine()) != null) {
String[] details = line.split("\t");
hashData.put(details[0], details[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); }
return hashData; } }

HashTab.txt
vbit 123
abc 345
edrf 567

OUTPUT:-

You might also like