Java Programs
Java Programs
Java Programs
[1]
Experiment 2
AIM: Write a JAVA program to perform various arithmetic operations using switch-case statement.
import java.util.Scanner;
public class airthmetic
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter numbers");
int a=s.nextInt();
int b=s.nextInt();
System.out.println("entered numbers are:"+a+"and"+b);
System.out.println("enter your choice");
int ch=s.nextInt();
switch(ch)
{
case 1: int h=a+b;
System.out.println("addition is:"+h);
break;
case 2: int q=a/b;
System.out.println("division is:"+q);
break;
case 3: int w=a*b;
System.out.println("mutiplication is:"+w);
break;
case 4: int e=a-b;
System.out.println("subtraction is:"+e);
break;
}}}
[2]
Experiment 3
if ( number1 == number2 )
System.out.printf( "%d == %d\n", number1, number2 );
if ( number1 != number2 )
System.out.printf( "%d != %d\n", number1, number2 );
[3]
if ( number1 > number2 )
System.out.printf( "%d > %d\n", number1, number2 );
[4]
Experiment 4
import java.util.Scanner;
[5]
System.out.println("Product of A and B is");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
[6]
Experiment 5
AIM: write a JAVA program to implement Tower of Hanoi using recursion with three disks.
if ( nDisks == 1 )
{
return fromPeg + " -> " + toPeg + "\n";
}
else
{
helpPeg = 6 - fromPeg - toPeg; // Because fromPeg + helpPeg + toPeg = 6
return mySol;
}
}
public static void main (String[] args)
[7]
{
int n = 3;
String StepsToSolution;
System.out.println(StepsToSolution);
}
}
[8]
Experiment 6
import java.io.*;
class complex
{
int r,i;
complex()
{
r =0;
i=0;
}
void sum(complex c,complex d)
{
complex a=new complex();
a.r=c.r+d.r;
a.i=c.i+d.i;
System.out.println("The sum is "+a.r+"+"+a.i+"i");
}
void read()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nEnter the real part");
r=Integer.parseInt(br.readLine());
System.out.println("\nEnter the imaginary part");
i=Integer.parseInt(br.readLine());
System.out.println("\nYou have entered : "+r+"+"+i+"i");
}
public static void main(String s[])throws IOException
{
[9]
complex c=new complex();
complex d=new complex();
System.out.println("First number");
c.read();
System.out.println("\nSecond number");
d.read();
d.sum(c,d);
}
}
[10]
Experiment 7
class employee
{
private int eno;
private String ename;
public void setemp(int no,String name)
{
eno = no;
ename = name;
}
public void putemp()
{
System.out.println("Empno : " + eno);
System.out.println("Ename : " + ename);
}
}
class department extends employee
{
private int dno;
private String dname;
public void setdept(int no,String name)
{
dno = no;
dname = name;
}
public void putdept()
{
System.out.println("Deptno : " + dno);
[11]
System.out.println("Deptname : " + dname);
}
public static void main(String args[])
{
department d = new department();
d.setemp(100,"aaaa");
d.setdept(20,"Sales");
d.putemp();
d.putdept();
}
}
[12]
Experiment 8
[13]
}
class finaltot extends marks
{
private int total;
public void calc()
{
total = mark1 + mark2;
}
public void puttotal()
{
System.out.println("Total : " + total);
}
public static void main(String args[])
{
finaltot f = new finaltot();
f.setstud(100,"Nithya");
f.setmarks(78,89);
f.calc();
f.putstud();
f.putmarks();
f.puttotal();
}
}
[14]
Experiment 9
[15]
System.out.println("i in I1 : "+i);
System.out.println("j in I2 : "+j);
System.out.println("l in I3 : "+l);
System.out.println("k in I4 : "+k);
}
[16]
Experiment 10
//B.java
class B extends A
{
void DisplayB()
{
System.out.println("I am in B");
}
}
//c.java
class C extends A
{
void DisplayC()
{
System.out.println("I am in C");
}
}
//MainClass.java
[17]
public class hierarchical
{
public static void main(String args[])
{
System.out.println("Calling for subclass C");
C c = new C();
c.DisplayA();
c.DisplayC();
[18]
Experiment 11
[19]
Experiment 12
[20]
Experiment 13
AIM: write a JAVA program to create a package, import it in a class which check whether a string is
palindrome or not.
package mypackage;
public class Palindrome
{
public boolean test(String str)
{
char givenstring[];
char reverse[] = new char[str.length()];
boolean flag = true;
int count = 0, ctr = 0;
givenstring = str.toCharArray();
for(count = str.length() - 1; count >= 0; count--)
{
reverse[ctr] = givenstring[count];
ctr++;
}
for(count = 0; count < str.length(); count++)
{
if(reverse[count] != givenstring[count])
flag = false;
}
return flag;
}
}
/* Save the code as Palindrome.java in the current working directory. Compile the program using the
following command:
javac -d . Palindrome.java
[21]
*/
// class using above package
import mypackage.*;
class Palintest
{
public static void main(String args[])
{
String s=args[0];
Palindrome objPalindrome = new Palindrome();
System.out.println(objPalindrome.test(s));
}
}
[22]
Experiment 14
AIM: write a JAVA program to read a file called temp.txt and output the file line by line on the
console.
import java.io.*;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
[23]
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
[24]
Experiment 15
AIM: Write a java program that creates a file called temp.txt and writes some lines of text to it.
import java.io.*;
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
[25]
catch(IOException ex) {
System.out.println("Error writing to file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
[26]
Experiment 16
/*
<applet code="LifeCycle.class" width=300 height=300></applet>
*/
import java.applet.Applet;
import java.awt.*;
[27]
printOutput();
}
[28]
Experiment 17
/*
<applet code="Polygon.class" width=3000 height=800></applet>
*/
import java.applet.*;
import java.awt.*;
[29]
Experiment 18
class Language {
String name;
Language() {
System.out.println("Constructor method called.");
}
Language(String t) {
name = t;
}
cpp.setName("C++");
java.getName();
cpp.getName();
}
void setName(String t) {
name = t;
}
void getName() {
System.out.println("Language name: " + name);
}}
[30]
Experiment 19
import java.io.*;
class Charextract
{
public static void main(String args[])
{
String s,str,substr;
int extract,start,len,check;
try{
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String : ");
System.out.flush();
str=obj.readLine();
len=str.length();
[31]
System.out.print("Enter how many characters you want to extract : ");
System.out.flush();
s=obj.readLine();
extract=Integer.parseInt(s);
check=extract+start;
if(check<0 || check>len )
{
System.out.println("TRYING TO EXTRACT INVALID POSITION");
System.exit(1);
}
substr=str.substring(start,check);
System.out.println("\nEXTRACTED STRING IS "+substr);
}
catch(Exception e) {}
}
}
[32]
Experiment 20
import java.util.Scanner;
class Comparestrings
{
public static void main(String args[])
{
String s1, s2;
Scanner in = new Scanner(System.in);
if ( s1.compareTo(s2) > 0 )
System.out.println("First string is greater than second.");
else if ( s1.compareTo(s2) < 0 )
System.out.println("First string is smaller than second.");
else
System.out.println("Both strings are equal.");
}
}
[33]
Experiment 21
String word;
[34]
//5. print out the beginning character using charAt()
System.out.println("first character: " + word.charAt(0));
[35]
Experiment 22
class Sample
{
int addition(int i, int j)
{
return i + j ;
}
String addition(String s1, String s2)
{
return s1 + s2;
}
double addition(double d1, double d2)
{
return d1 + d2;
}
}
class Methodoverload
{
public static void main(String args[])
{
Sample sObj = new Sample();
System.out.println(sObj.addition(1,2));
System.out.println(sObj.addition("Hello ","World"));
System.out.println(sObj.addition(1.5,2));
}
}
[36]
Experiment 23
AIM: Write a JAVA program for implementing method overriding with the help of super keyword.
class Superclass {
[37]
Experiment 24
//hoursInDay=12;
}
}
[38]
Experiment 25
[39]
System.out.println("You are using triangle class");
}
}
class Abstract
{
public static void main(String args[])
{
Shape sobj = new Circle();
sobj.display();
[40]
Experiment 26
AIM: Write a JAVA program for demonstrating use of access control and static keyword.
class student {
student() {
acc_details(); //Accessed only within the class
}
public static void stu_details() //static method can be called without the object
{
System.out.println("Name:XXXX");
System.out.println("Roll No:123456");
count++;
//count1++;here it cannot be used because non static member could not be used in the static function
}
private void acc_details() //non static method can be called only with the object
{
System.out.println("Entered into Private Access Specifiers");
System.out.println("Password:*******");
count++;
count1++;
}
protected void att_details() //non static method can be called only with the object
{
[41]
System.out.println("Attendance Details");
count++;
count1++;
}
}
protected static void sta_details()//static method can be called without the object
{
count++;
//count1++; here it cannot be used because non static member could not be used in the static function
System.out.println("Name:YYYY");
}
}
protected static void hod_details() //static method can be called without the object
{
count++;
//count1++; here it cannot be used because non static member could not be used in the static function
System.out.println("Name:ZZZ");
}
}
[42]
class college extends hod {
[43]
s1.att_details();//staff can also view the student attendance details because it is inherited so it has an
//access over protected details.
s2.att_details();//staff can also view the student attendance details because it is inherited so it has an
//access over protected details.
//acc_details() cannot not be viewed by any of the classes like staff,hod and college becuase it is in
//private mode.
student s = new student();
//s.acc_details(); it cannot be called because private mode function only accessed within the function.
s.stu_details();
s.att_details();
System.out.println("Count value without object:" + count);//count variable can be called without an
//object
//System.out.println("Count1 Value:" + count1); count1 variable cannot be called without an
object //because it is non-static
System.out.println("Count value with object of class student:" + s.count);
System.out.println("Count value with object of class staff:" + s1.count);
System.out.println("Count value with object of class hod:" + s2.count);
System.out.println("Count1 value with object of class student:" + s.count1);
System.out.println("Count1 value with object of class staff:" + s1.count1);
System.out.println("Count1 value with object of class hod:" + s2.count1);
}
}
[44]
Experiment 27
class ThreadTest1
{
public static void main(String args[])
{
MyThread thread1 = new MyThread("thread1: ");
MyThread thread2 = new MyThread("thread2: ");
thread1.start();
thread2.start();
boolean thread1IsAlive = true;
boolean thread2IsAlive = true;
do {
if (thread1IsAlive && !thread1.isAlive()) {
thread1IsAlive = false;
System.out.println("Thread 1 is dead.");
}
if (thread2IsAlive && !thread2.isAlive()) {
thread2IsAlive = false;
System.out.println("Thread 2 is dead.");
}
} while(thread1IsAlive || thread2IsAlive);
}
}
[45]
public MyThread(String id)
{
super(id);
}
void randomWait()
{
try {
sleep((long)(3000*Math.random()));
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
}
[46]
Experiment 28
class ThreadSynchronization
{
public static void main(String args[])
{
MyThread thread1 = new MyThread("thread1: ");
MyThread thread2 = new MyThread("thread2: ");
thread1.start();
thread2.start();
boolean thread1IsAlive = true;
boolean thread2IsAlive = true;
do {
if (thread1IsAlive && !thread1.isAlive()) {
thread1IsAlive = false;
System.out.println("Thread 1 is dead.");
}
if (thread2IsAlive && !thread2.isAlive()) {
thread2IsAlive = false;
System.out.println("Thread 2 is dead.");
}
} while(thread1IsAlive || thread2IsAlive);
}
}
[47]
public MyThread(String id)
{
super(id);
}
void randomWait()
{
try {
sleep((long)(3000*Math.random()));
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
}
class SynchronizedOutput
{
public static synchronized void displayList(String name,String list[])
{
for(int i=0;i<list.length;++i) {
MyThread t = (MyThread) Thread.currentThread();
t.randomWait();
System.out.println(name+list[i]);
}
}}
[48]
Experiment 29
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//<applet code="cal" width=500 height=500></applet>
public class cal extends Applet implements ActionListener
{
int a,b,c;
TextField t1;
Button
b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16;
String s,s1,s2,s3,s4;
public void init()
{
setLayout(null);
t1=new TextField(10);
t1.setBounds(80,200,260,40);
add(t1);
b1=new Button("0");
b2=new Button("1");
b3=new Button("2");
b4=new Button("3");
b5=new Button("4");
b6=new Button("5");
b7=new Button("6");
b8=new Button("7");
b9=new Button("8");
[49]
b10=new Button("9");
b11=new Button("+");
b12=new Button("-");
b13=new Button("*");
b14=new Button("/");
b15=new Button("=");
b16=new Button("CLR");
b1.setBounds(90,260,40,30);
add(b1);
b2.setBounds(140,260,40,30);
add(b2);
b3.setBounds(190,260,40,30);
add(b3);
b4.setBounds(240,260,40,30);
add(b4);
b5.setBounds(290,260,40,30);
add(b5);
b6.setBounds(90,300,40,30);
add(b6);
b7.setBounds(140,300,40,30);
add(b7);
b8.setBounds(190,300,40,30);
add(b8);
b9.setBounds(240,300,40,30);
add(b9);
b10.setBounds(290,300,40,30);
add(b10);
b11.setBounds(90,340,40,30);
add(b11);
b12.setBounds(140,340,40,30);
add(b12);
[50]
b13.setBounds(190,340,40,30);
add(b13);
b14.setBounds(240,340,40,30);
add(b14);
b15.setBounds(290,340,40,30);
add(b15);
b16.setBounds(90,380,70,20);
add(b16);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b10.addActionListener(this);
b11.addActionListener(this);
b12.addActionListener(this);
b13.addActionListener(this);
b14.addActionListener(this);
b15.addActionListener(this);
b16.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
s=ae.getActionCommand();
if(s.equals("0") || s.equals("1") || s.equals("2")||
[51]
s.equals("3") || s.equals("4") || s.equals("5")||s.equals
("6")||s.equals("7")||s.equals("8")||s.equals("9"))
{
s1=t1.getText()+s;
t1.setText(s1);
}
if(s.equals("+"))
{
s2=t1.getText();
t1.setText("");
s3="+";
}
if(s.equals("-"))
{
s2=t1.getText();
t1.setText("");
s3="-";
}
if(s.equals("*"))
{
s2=t1.getText();
t1.setText("");
s3="*";
}
if(s.equals("/"))
{
[52]
s2=t1.getText();
t1.setText("");
s3="/";
}
if(s.equals("="))
{
s4=t1.getText();
a=Integer.parseInt(s2);
b=Integer.parseInt(s4);
if(s3.equals("+"))
c=a+b;
if(s3.equals("-"))
c=a-b;
if(s3.equals("*"))
c=a*b;
if(s3.equals("/"))
c=a/b;
t1.setText(String.valueOf(c));
}
if(s.equals("CLR"))
{
t1.setText("");
[53]
public void paint(Graphics g)
{
setBackground(Color.green);
g.drawRect(80,200,260,200);
showStatus("ASHUSOFTECH");
g.drawString("CALCULATER",200,50);
}
}
[54]
Experiment 30
class jump
{
public static void main(String args[])
{
for(int count=1;count <= 10;count++)
{
System.out.print(count + " ");
if (count==5)
continue;
System.out.println("");
}
}
}
[55]
Experiment 31
AIM: write a JAVA program to print numbers from 1 to 10 using while statement.
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
[56]
Experiment 32
AIM: write a JAVA program for printing numbers from 1 to 10 using do-while loop.
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
[57]
Experiment 33
AIM: write a JAVA program for implementing exception handling using throw and finally.
// Demonstrate finally.
class FinallyDemo {
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
[58]
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
[59]
[60]