Practical Java Programs

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

 Develop programs to demonstrate use of if statements and its different forms

class big3
{
public static void main (String[] args)
{
int a=100;
int b=150;
int c=200;
System.out.println(“Value of A is "+a);
System.out.println(“Value of B is "+b);
System.out.println(“Value of C is "+c);
if (a>b && a>c)
{
System.out.println("A is bigger");
} else if(b>c)
{
System.out.println("B is biger");
} else
{
System.out.println("C is bigger");
}
}
}
 Develop programs to demonstrate use of- switch and conditional operator
Switch Case (a).
class week
{
public static void main(String[] args)
{
int a=3;
switch(a)
{
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Invalid Number");
}
}
}

Switch Case (b).


class sw1
{
public static void main(String[] s)
{
char ch='B';
switch (ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':System.out.println(ch+" is an Vowel");
break;
default:
System.out.println(ch+" is a Constant");
break;
}
}
}
 Develop programs to demonstrate use of Looping Statement 'for'
Nested Loop (Stat peramid)
class star
{
public static void main(String[] args)
{
for (int i=0;i<=4;i++)
{
for (int j=1;j<=i;j++)
{
System.out.print("* "); // “j” print 2nd pattern and “i” print 3rd pattern.
}
System.out.println();
}
}
}

Print Odd numbers from 1 to 9.


class odd
{
public static void main(String[] args)
{
System.out.println("Odd table is ");
for (int i=1;i<=10;i++)
{
System.out.println(i);
i=i+1;
}
}}

//Factorial
class Factorial
{
public static void main(String args[])
{
int fact=0;
for(int i=0;i<=5;i++)
{
fact=fact+i;
System.out.println(fact);
}
}
}
 Develop programs to demonstrate use of Looping Statement 'while' and 'do-while'
Print 1 to 10 counting (do while loop).
class count
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i++);
}
while (i<=10);
}
}

Print 1 to 10 counting (while loop).


class while1
{
public static void main(String[] args)
{
int i=1;
while (i<=10)
{
System.out.println(i++);
}
}
}

 Develop a program for implementation of explicit type conversion


class TypeCast
{
public static void main(String args[])
{
byte b;
int i=257;
double d = 100.78d;
float f=44.56f;

System.out.println("Convertion of int to byte:");


b=(byte)i;
System.out.println(b+" "+i);

System.out.println("Convertion of double to int:");


i=(int)d;
System.out.println(d+" "+i);

System.out.println("Convertion of double to Float:");


d=(double)f;
System.out.println(d+" "+f);

}
}
 Develop a program for implementation of Constructor.
class Person
{
String name;
int age;

Person(String n, int a)
{
name=n;
age=a;
}
void display()
{
System.out.println("Name="+name);
System.out.println("Age=" +age);
}
}
class Employee extends Person
{
String designation;
int salary;
Employee(String d,int s)
{
//super(n,a);
designation=d;
salary=s;
}
void display1()
{
//display();
System.out.println("Designation="+designation);
System.out.println("Salary=" +salary);
}

public static void main(String args[])


{
Employee e1=new Employee("Manager",30);
e1.display1();
}
}
 Develop a program for implementation of Arrays in Java

public class Array {

public static void main(String[] args) {


int[] array = {1, 2, 3, 4, 5};

for (int element: array) {


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

 Develop a program for implementation of Vectors in Java

 Develop a program for implementation of Wrapper Class to convert primitive into


object.
class IntegerWrapper
{
public static void main(String args[])
{

int b = 55;
String str= "45";
// Construct two Integer objects

int a=Integer.parseInt(str);
Integer x = new Integer(b);
Integer y = new Integer(str);

System.out.println("toString(b) = " + Integer.toString(b));


System.out.println("toHexString(b) =" + Integer.toHexString(b));
System.out.println("toOctalString(b) =" + Integer.toOctalString(b));
System.out.println("toBinaryString(b) =" + Integer.toBinaryString(b));
System.out.println(a);

}
 Develop a program for implementation of Wrapper Class to convert object into
primitive
public class IntegerObjectWrapper
{
public static void main(String args[])
{
Byte b=1;
Integer i = 5;
Double d = 5.99;
Character c = 'A';
Short s=123;

System.out.println(i.intValue());
System.out.println(d.doubleValue());
System.out.println(c.charValue());
System.out.println(b.byteValue());
System.out.println(s.shortValue());
}
}
 Write a program to make use of Character Wrapper class methods.
public class CharacterWrapper {

public static void main(String[] args) {

System.out.println("isLetter");
System.out.println(Character.isLetter('A'));
System.out.println(Character.isLetter('0'));

System.out.println("isWhitespace");
System.out.println(Character.isWhitespace('A'));
System.out.println(Character.isWhitespace(' '));
System.out.println(Character.isWhitespace('\n'));
System.out.println(Character.isWhitespace('\t'));

System.out.println("isUpperCase");
System.out.println(Character.isUpperCase('A'));
System.out.println(Character.isUpperCase('a'));

System.out.println("LowerCase");
System.out.println(Character.isLowerCase('A'));
System.out.println(Character.isLowerCase('a'));
System.out.println("toUpperCase");
System.out.println(Character.toUpperCase('a'));
System.out.println(Character.toUpperCase(97));

System.out.println("toLowerCase");
System.out.println(Character.toLowerCase('A'));
System.out.println(Character.toLowerCase(65));

System.out.println("toString");
System.out.println(Character.toString('x'));
System.out.println(Character.toString('Y'));
}
}

 Define a class student with int id and string name as data members and a method
void SetData ( ). Accept and display the data for five students.-4 Mark [Methods
2-Marks & 2-Marks Program]
public class student
{
int id;
string name;

public void setdata()


{
Scanner s1=new Scanner(System.in);
System.out.println("student name=");
name=s1.next();
System.out.println("student id=");
id=s1.nextInt();
}
public void display()
{
student s1=new student[5];
int i;
for(i=0;i<5;i++);
{
s[i]=new student();
}
for(i=o;i<5;i++);
{
s[i].setdata();
}
for(i=0;i<5;i++)
{
s[i].display();
}
}
}

 Define a class employee with data members 'empid , name and salary. Accept
data for three objects and display it

class employee
{
int empid;
String name;
double salary;
void getdata()
{
BufferedReader obj = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter Emp number : ");
empid=Integer.parseInt(obj.readLine());
System.out.print("Enter Emp Name : ");
name=obj.readLine();
System.out.print("Enter Emp Salary : ");
salary=Double.parseDouble(obj.readLine());
}
void show()
{
System.out.println("Emp ID : " + empid);
System.out.println(“Name : " + name);
System.out.println(“Salary : " + salary);
}
}
classEmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[3];
for(inti=0; i<3;i++)
{
e[i] = new employee();
e[i].getdata();
}
System.out.println(" Employee Details are : ");
for(inti=0; i<3;i++)
{
e[i].show();
}
}

 Develop a program for implementation of try, catch and finally block.


class ExceptionHandling
{
public static void main (String[] args)
{
// array of size 4.
int[] arr = new int[4];

try
{
int i = arr[4];
// this statement will never execute
// as exception is raised by above statement
System.out.println("Inside try block");
}

catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Exception caught in catch block");
}

finally
{
System.out.println("finally block executed");
}

// rest program will be executed


System.out.println("Outside try-catch-finally clause");
}
}

 Program to throw an exception ”Authentication Failure” if password is


incorrect.
import java.util.*;
class PasswordException extends Exception
{
PasswordException(String msg)
{
super(msg);
}
}
class PassCheck
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
try
{
System.out.println("Enter Password : ");
if(sc.nextLine().equals("vvp"))
{
System.out.println("Authenticated ");
}
else
{
throw new PasswordException("Authentication failure");
}
}
catch(PasswordException e)
{
System.out.println(e);
}

}
}

 The Program calculates sum of two numbers inputted as command line


arguments when will it give an exception.
class TwoNumber

{
public static void main (String[] args)
{
try
{
int m1=Integer.parseInt(args[0]);
int m2=Integer.parseInt(args[1]);
int m=m1+m2;
System.out.println(“Sum is:”+m);
}
catch(NumberFormatException ex)
{
System.out.println(ex);
}
finally
{
System.out.println(“Your inputted a correct integer number”);
}

}
}

 /*Develop a program to create two threads such that one thread will print odd
numbers and the other will print even numbers between 1 to 20 numbers.*/

import java.io.*;
import java.lang.Thread;
class Even extends Thread
{
public void run()
{
for(int i=1;i<=20;i++)
{
if(i%2==0)
{
System.out.println("Even Thread i="+i);
}
}
System.out.println("Exit from Even");
}
}

class Odd extends Thread


{
public void run()
{
for(int j=1;j<=20;j++)
{
if(j%2!=0)
{
System.out.println("Odd Thread j="+j);
}
}
System.out.println("Exit from Odd");
}
}
class EvenOddThread
{
public static void main(String args[])
{
Even ThEven=new Even();
Odd ThOdd=new Odd();
ThOdd.start();
ThEven.start();
}
}

 Define a package names let_me_calculate include class named as calculator and a


method named add to add two integer numbers. Import let_me_calculate
package in another program named Demo to add two numbers.
package let_me_calculate;
public class Calculator
{
public void add(int a,int b)
{
System.out.println("Addition="+(a+b));
}
}
import let_me_calculate.*;
class Demo
{
public static void main(String args[])
{
Calculator cl=new Calculator();
cl.add(12,5);
}
}

 Develop program to calculate room area and volume using Single inheritance
class Room
{
int length,width,height;
Room(int l,int w,int h)
{
length=l;
width=w;
height=h;
}
void display()
{
System.out.println("Length="+length);
System.out.println("Width="+width);
System.out.println("Height="+height);
}
}
class AreaVolume extends Room
{
AreaVolume(int l,int w,int h)
{
super(l,w,h);
}
void calculate()
{
System.out.println("Area of room="+length*width);
System.out.println("Volume of room="+length*width*height);
}
}
class RoomDemo
{
public static void main(String args[])
{
AreaVolume av=new AreaVolume(50,40,30);
av.display();
av.calculate();
}
}

 Program to find area of rectangle and circle using interfaces.


interface Area
{
float pi=3.14F;
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute (float x, float y)
{
return(x*y);
}
}
class Circle implements Area
{
public float compute(float x, float y)
{
return(pi*x*x);
}
}
classRCArea
{
public static void main(String args[])
{
Rectangle rect=new Rectangle();
Circle cir=new Circle();
Area a;
a=rect;
System.out.println("Area of rectangle : "+a.compute(5,10));
a=cir;
System.out.println("Area of circle : "+a.compute(5,0));
}
}

 Develop program which implements the concept of overriding.


class Bank
{
intgetRateOfInterest(){return 0;}
}
class SBI extends Bank
{
intgetRateOfInterest(){return 8;}
}
class ICICI extends Bank
{
intgetRateOfInterest(){return 7;}
}
class AXIS extends Bank
{
intgetRateOfInterest(){return 9;}

classBankInterestRate
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

 /*Define an Exception called “NoMatchException” that is thrown when a string


is not equal to “India”. Write a program that uses this exception.*/

class NoMatchException extends Exception


{
String m;
NoMatchException(String message)
{
m = message;
}
void printmsg()
{
System.out.println(m);
}
}
class NoMatch
{
public static void main(String args[])
{
if(args.length!=1)
{
System.out.println("\nEnter only one String argument");
}
else
{
try
{
if(args[0].compareTo("India") == 0)
{
System.out.println("\nString is equal to 'India'.");
}
else
{
throw new NoMatchException("Arguments is not equal to 'India'.");
}
}
catch(NoMatchException e)
{
System.out.println("\nException Caught: ");
e.printmsg();
}
}
}
}

 //Write a program to input name and age of person and throws user defined
exception, if entered age is negative.
import java.util.*;
class Negative extends Exception
{
Negative(String msg)
{
super(msg);
}
}
class Negativedemo
{
public static void main(String ar[])
{
int age=0;
String name;
Scanner sc=new Scanner(System.in);
System.out.println("enter age and name of person");
try
{
age=sc.nextInt();
name=sc.nextLine();

if(age<0)
throw new Negative("age is negative");
else
throw new Negative("age is positive");
}
catch(Negative n)
{
System.out.println(n);
}
}
}
 Program to display string in applet
import java.applet.*;
import java.awt.*;
public class WelcomeToApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Welcome to the World of Applet", 25, 50);
}
}
/* <applet code="WelcomeToApplet.class" width=400 height=200></applet> */

 Program to use control loops in applet


import java.awt.*;
import java.applet.*;
/* <applet code= loopsinapplet.class width=100 height=100></applet>*/
public class loopsinapplet extends Applet
{
public void paint(Graphics g)
{
int row;
int col;
int x,y;
for ( row = 0; row < 5; row++ )
{
for ( col = 0; col < 5; col++)
{
x = col * 20;
y = row * 20;
if ( (row % 2) == (col % 2) )
{
g.setColor(Color.white);
}
else
{
g.setColor(Color.black);
}
g.fillRect(x, y, 20, 20);
}
}
}
}

 Develop a program to write Bytes to file.


import java.io.FileOutputStream;
import java.io.IOException;

class ByteToFile
{
public static void main(String args[])
{

try
{
FileOutputStream fout= new FileOutputStream("Output.txt");

String s= "Welcome to JAVA Programming! This is an example of Java program to write Bytes
using ByteStream. into file";

byte b[] = s.getBytes();

fout.write(b);
System.out.print("Copied Successfully");

fout.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
}
Output:
Copied Successfully

 Develop a program to copy one file to another using Byte Stream.


import java.io.*;
class CopyByte
{
public static void main(String args[])
{
try
{ FileInputStream fis=new FileInputStream("Input.txt");
FileOutputStream fos=new FileOutputStream("Output.txt");

int b=0;
while(b!=-1)
{
b=fis.read();
fos.write(b);
}
System.out.println("File copied Successfully");
fis.close();
fos.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
File copied Successfully

 Develop a program to copy one file to another using Character Stream.


import java.io.*;
class CopyChar
{
public static void main(String args[])
{
try
{
FileReader fr=new FileReader("Input.txt");
FileWriter fw=new FileWriter("Output.txt");

int ch=0;
while(ch!=-1)
{
ch=fr.read();
fw.write((char)ch);
}
System.out.println("File copied Successfully");
fr.close();
fw.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
File copied Successfully

 Develop a program to draw


a. Square Inside a Circle
b. Circle inside a square
import java.awt.event.*;
import java.applet.Applet;
import java.awt.Graphics;

public class GraphicsExcercise extends Applet {

public void paint(Graphics g) {

g.drawRect(80,80,100,100);
g.drawOval(100, 100, 60, 60);

g.drawOval(200,80,100,100);
g.drawRect(220,100,60,60);
}
}

/* <applet code="GraphicsExcercise.class" width="320" height="320">


</applet>
*/
 Applet program to draw a cone,cylinder and cube

import java.io.*;
import java.awt.*;;
import java.applet.*;

//<Applet code="Cone" WIDTH="800" HEIGHT="400"></Applet>

public class Cone extends Applet


{
public void paint(Graphics g)
{
setBackground(Color.yellow);
g.setColor(Color.black);

/* To draw an cone*/
g.drawOval(200,80,200,50);
g.drawLine(200,100,300,500);
g.drawLine(400,100,300,500);

/* To draw a cyclinder*/
g.drawOval(500,60,200,50);
g.drawLine(500,80,500,300);
g.drawLine(700,80,700,300);
g.drawOval(500,280,200,50);

/* To draw a cube*/
g.drawRect(500,400,100,100);
g.drawRect(550,450,100,100);
g.drawLine(500,400,550,450);
g.drawLine(500,500,550,550);
g.drawLine(600,400,650,450);
g.drawLine(650,550,600,500);
}
}

 Program to draw polygon in applet


import java.applet.*;
import java.awt.Graphics;

public class DrawFillPolygon extends Applet


{
int xCoords[] = { 50, 200, 300, 150, 50, 50 };
int yCoords[] = { 100, 0, 50, 300, 200, 100 };
int xFillCoords[] = { 450, 600, 700, 550, 450, 450 };
public void paint(Graphics g)
{
g.drawPolygon(xCoords, yCoords, 6);
g.fillPolygon(xFillCoords, yCoords, 6);
}
}
/* <applet code=DrawFillPolygon width=300 height=300> </applet> */

You might also like