Lab Record
Lab Record
3
2014-2015
[Pick the date]
INDEX
S.NO PROGRAMME NAME P.NO.
I Basic Programs 4
7
4)Write java program to print the following o/p
8
5) Write a java program to print sum of Sum of Digits
6) Write a java Program for swapping two numbers 9
10) Write A Java Program to print Quadratic roots using command line 13
arguments
11) Write a java program to print the names in sorted order using arrays 14
II Method Overloading 18
3) Wajp to copy the values of one object into another using constructor. 26
IV Inheritence 28
3) Write a Java program to implement the following hierarchy and find area 31
and perimeter Abstract
V Method Overriding 35
VIII Packages: 48
2) write a java package for book class and then import and display the result. 50
3) write a java program to find the cube of a number for various data types 51
using package and then import and display the results.
IX Interfaces: 53
XI Exception handling: 57
XIII Multithreading 64
XIV) 73
File I/O and Streams
1)Wajp to Demonstration of FileOutputStream and PrintStream classes 74
XV Applets 79
XIV 87
AWT: 1 ) Wajp that prints a message by clicking on the button
using AWT events and applets 2) GUI with controls menus
and event handling.
I. Basic programs:
Importjava.util.*;
class Biggest3
{
public static void main(String args[])
{
int n1, n2, n3, big;
Scanner scan= new Scanner(System.in);
System.out.print("Please Enter No 1: ");
n1=scan.nextInt();
System.out.print("Please Enter No 2: ");
n2=scan.nextInt();
System.out.print("Please Enter No 3: ");
n3=scan.nextInt();
if(n1>n2 && n1>n3)
big=n1;
else if(n2>n1 && n2>n3)
big=n2;
else
big=n3;
System.out.println("Biggest No: " + big);
}
}
O/P:
o/p :
class Stars
{
Public static voidmain(String[]args)
{
int row, numberOfStars;
Output of program:
n res n sum
513 0
513%10 3 3
513/10 51 3
51%10 1 4
51/10 5 4
5%10 5 9
5/10 0 9
importjava.util.*;
classSumDigits
{
public static void main(String args[])
{
int n, res,sum=0;
Scanner scan= new Scanner(System.in);
System.out.print("Please Enter No. = ");
n=scan.nextInt();
System.out.print("Sum of digits of a number" +n+ "is = "); while(n>0)
{
res=n%10;
n=n/10;
sum=sum+res;
}
System.out.print(+sum);
}
}
o/p:
importjava.util.*;
class Swap
{
public static void main(String args[])
{
int n1, n2, temp;
Scanner scan= new Scanner(System.in);
System.out.print("Please Enter No 1:=");
n1=scan.nextInt();
System.out.print("Please Enter No 2: =");
n2=scan.nextInt();
temp=n1;
n1=n2;
n2=temp;
System.out.println("First No: " + n1);
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 9
Object Oriented Programming Through Java Laboratory Record
}
}
o/p:
importjava.util.*;
public class Prime
{
public static void main(String args[])
{
inti,j,p=1;
Scanner sc =new Scanner(System.in);
System.out.print("enter a number up to which u want print primes =");
int n=sc.nextInt();
for(i=2;i<=n;i++)
{
p=1;
for(j=2;j<i;j++)
{
if(i%j==0)
{
p=0;
}}
if(p==1)
System.out.println(j);
}
}
}
o/p:
importjava.util.*;
public class Palin
{
public static void main(String args[])
{
System.out.print("enter strings = ");
Scanner sc=new Scanner(System.in);
String s=sc.next();
StringBuffer tmp=new StringBuffer(s);
tmp.reverse();
String str2;
str2=new String(tmp);
if(s.equals(str2))
System.out.println("the given string " + s + " is palindrome");
else
System.out.println("the given string " + s + " is not palindrome");
}
}
O/P:
importjava.util.Scanner;
classSeriesfact
{
public static void main(String args[])
{
int i;
float sum=0,f=1;
System.out.println("enter number of terms in the series");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(i=1;i<=n;i++)
{ for(f=1;f<=i;f++)
{
f=f*i;
sum=sum + (float)1/f;
}
}
System.out.println("sum of" +n +"terms is = " +sum);
}
}
o/p:
10) Write A Java Program to print Quadratic roots using command line arguments
importjava.lang.*;
class Quadratic
{
public static void main(String args[])
{
inta,b,c,d;
double r1,r2;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[2]);
d=b*b-4*a*c;
if(d==0)
{
r1=r2=-(float)b/(2*a);
System.out.println("the roots are real equal =" +r1 + " and r2 = " +r2);
}
else if(d>0)
{
double t=Math.sqrt(d);
r1=(-b+t)/(2*a);
r2=(+b+t)/(2*a);
System.out.println("the roots are real and distict \n r=" +r1 +" and r2=" +r2);
}
else if(d<0)
{
System.out.println("the roots are imaginary and there is no real solution ");
}
}}
o/p:
11) Write a java program to print the names in sorted order using arrays
import java.lang.*;
class Stringsort
{
static String name[]={"Bombay" , "Madras" ,"Delhi" ,"Pune"};
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if ( name[j].compareTo(name[i])<0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
System.out.println("soted names are ");
for(int i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
o/p
import java.util.Scanner;
import java.io.*;
import java.lang.*;
class MatrixMul
{
public static void main(String[] args)
{
int i= 0,j=0,k=0,p,q,m,n;
int a[][] = new int[10][10];
int b[][] = new int[10][10],c[][] = new int[10][10];
Scanner sc = new Scanner(System.in);
System.out.print("Enter no of rows in the A matrix= ");
p=sc.nextInt();
System.out.print("Enter a no of columns in the A matrix = ");
q=sc.nextInt();
System.out.print("Enter no of rows in the B matrix= ");
m = sc.nextInt();
System.out.print("Enter no of columns in the B matrix= ");
n = sc.nextInt();
if(q==m)
{
System.out.print ("Enter A matrix values :");
for(i=0;i<p;i++)
{
for(j=0; j<q ;j++)
{
a[i][j] = sc.nextInt() ;
}
}
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 15
Object Oriented Programming Through Java Laboratory Record
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
System.out.print(" "+a[i][j]) ;
}
System.out.println();
}
System.out.println("Enter matrix B values :");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[i][j] = sc.nextInt() ;
}
}
for(i=0;i<p;i++)
{
for(j=0;j<n;j++)
{
System.out.print(" "+c[i][j]) ;
}
System.out.println();
}
}else
{
System.out.println("Matrix multiplication not possible");
}
}
}
O/P:
class Bubble
{
public static void main(String args[])
{
int[] nums={12,87,9,-4,76,34,890,543,77,02};
int a,b,t;
int size;
size=10;
System.out.print("original array is");
for (int i=0;i<size;i++)
System.out.print(" " +nums[i]);
System.out.println();
for(a=1;a<size;a++)
for(b=size-1;b>=a;b--)
{
if(nums[b-1]>nums[b])
{
t=nums[b-1];
nums[b-1]=nums[b];
nums[b]=t;
}
}
System.out.print("sorted array is ");
for(int i=0;i<size;i++)
System.out.print(" "+nums[i]);
System.out.println();
}
}
Output:
class Vehicle
{
int pass;
int fcapacity;
int speed;
}
class MainDemo
{
public static void main(String args[])
{
Vehicle carobj=new Vehicle();
Vehicle busobj=new Vehicle();
Vehicle vanobj=new Vehicle();
int distance;
carobj.pass=6;
carobj.fcapacity=26;
carobj.speed=60;
distance=carobj.fcapacity*carobj.speed;
System.out.println("car can carry: "+carobj.pass+" passengers with fuel capacity
Output:
Program:
class OverloadDemo
{
void max(float a, float b)
{
System.out.println("\nmax method with float argument invoked");
if(a>b)
System.out.println(a+" is Greater");
else
System.out.println(b+" is Greater");
}
void max(double a, double b)
{
o/p:
2)Write a java program to find the volume of a Box using method overloading with
different number of perameters.
class Box
int width,breadth,height;
width=breadth=height=length;
{ width=a;
breadth=height=b;
{ width=x;
breadth=y;
height=z;
int volume()
System.out.println(" ");
return width*breadth*height;
}}
class MainBox
{ int vol;
mybox1.getdata(10,20,30);
vol=mybox1.volume();
vol=mybox2.volume();
mybox3.getdata(5);
vol=mybox3.volume();
o/p:
}
static void vaTest(boolean ...v)
{
System.out.println();
System.out.print(" second method invoked:" +"no of args :" +v.length +" and the contents are :");
for(boolean x:v)
System.out.print(x+ " ");
System.out.println();
}
static void vaTest(String msg, int ...v)
{
System.out.println();
System.out.print(" third method invoked :" +"the message is :" +msg +"no of args :" +v.length +"
and the contents are :");
for(int x:v)
System.out.print(x+ " ");
System.out.println();
}
public static void main(String args[])
{
vaTest(1,2,3);
vaTest("testing : ",10,20);
vaTest(true,false,false);
}
}
Output:
Constructor is a special type of method which is having the same class name that is used to
initialize the object. Constructor is invoked at the time of object creation.
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
1) Write a java program to illustrate the concept of constructors and its overloading.
import java.lang.*;
class TestOl
{
int hrs,mins,scnds;
TestOl(int h,int m,int s)
{
hrs=h;
mins=m;
scnds=s;
}
public TestOl(int h)
{
hrs=h;
mins=0;
scnds=0;
}
public TestOl(int h,int m)
{
hrs=h;
mins=m;
scnds=0;
}
public TestOl()
{
hrs=0;
mins=0;
scnds=0;
}
void primetime()
{
System.out.println("hrs:"+hrs+"\t mins:"+mins+"\t scnds:"+scnds);
}
}
class COverLoad
{
public static void main(String args[])
{
Out Put :
2) Write a java program for Rectangle class using constructor overloading with different
no. of parameter list
class Rectangle
{
int length;
int width;
int area()
{
return length*width;
}
void perimeter()
{
int p=2*length+2*width;
System.out.println("perimeter of rectangle is " +p);
}
Rectangle()
{
length=2;
width=3;
}
Rectangle(int a)
{
length=width=a;
}
Rectangle(int a, int b)
{
length=a;
width=b;
}
}
class MainForRectangle
{
public static void main(String args[])
{
Rectangle r1= new Rectangle();
float area1= r1.area();
System.out.println("area of Rectangle 1 is :" +area1);
r1.perimeter();
System.out.println();
3)Write a java program for Subject class using constructor overloading with different no.
of parameter list
class Subject {
String name1,name2;
Subject()
{
System.out.println();
System.out.println("MCA first year subjects are as follows.");
System.out.println();
}
Subject(String t)
{
name1 = t;
}
Subject(String s1, String s2)
{
name1=s1;
name2=s2;
System.out.print(" "+ name1 +" " +name2);
}
void setName(String t)
{
name1 = t;
}
void getName()
{
System.out.print(" "+name1);
}
Output:
4) Wajp to copy the values of one object into another using constructor.
class Student
{
int id;
String name;
int age;
Student(int i,String n,int a)
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 33
Object Oriented Programming Through Java Laboratory Record
{
id = i;
name = n;
age=a;
}
Student(Student s)
{
id = s.id;
name =s.name;
age=s.age;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Kalpana",39);
Student s2 = new Student(s1); //copy contents from s1 in to s2
s1.display();
s2.display();
}
}
o/p:
IV) Inheritance is a mechanism in which one object acquires all the properties and behaviours
of parent object.
Simple Inheritance : When a subclass is derived simply from it's parent class then this
mechanism is known as simple inheritance.
Multilevel Inheritance: When a subclass is derived from a derived class then this
mechanism is known as the multilevel inheritance
Multiple Inheritance is achieved in java by using Interfaces.
int height;
void volume()
{
System.out.println("Volume of cuboid is " +(length*width*height));
}
}
class Simpleinheritance1
{
public static void main(String args[])
{
Rectangle r=new Rectangle();
Cuboid c=new Cuboid();
r.length=10;
r.width=5;
r.area();
c.length=15;
c.width=10;
c.height=5;
c.volume();
}
}
o/p:
class Name
{
String name="swathi";
int age=20;
}
class Mark extends Name
{
int m1=30,m2=30,m3=30;
}
class Student extends Mark
{
int total;
void calc()
{
total=m1+m2+m3;
}
void show()
{
o/p:
3) Write a Java program to implement the following hierarchy and find area and
perimeter Abstract
double calcar()
{
double arc=(3.14*r*r);
return arc;
}
double calcper()
{
double per=(2*3.14*r);
return per;
}}
class square extends shape
{
double a;
square(double s)
{
a=s;
}
void display()
{
System.out.println("\nside="+a);
}
double calcar()
{
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 40
Object Oriented Programming Through Java Laboratory Record
double ars=a*a;
return ars;
}
double calcper()
{
double per=4*a;
return per;
}}
class triangle extends shape
{
double b,h;
triangle(double p, double q)
{
b=p; h=q;
}
void display()
{
System.out.println("\nbreadth="+b+"\t height="+h);
}
double calcar()
{
double art=(0.5*b*h);
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 41
Object Oriented Programming Through Java Laboratory Record
return art;
}
double calcper()
{
return 0;
} };
class Classhierarchy
{
public static void main(String s[])
{
circle c=new circle(5.2f);
c.display();
System.out.println("\nArea of circle ="+c.calcar());
System.out.println("\nPerimeter of circle ="+c.calcper());
square sq=new square(2.3f);
sq.display();
System.out.println("\nArea of square ="+sq.calcar());
System.out.println("\nPerimeter of square ="+sq.calcper());
triangle t=new triangle(1.3f,4.5f);
t.display();
System.out.println("\nArea of triangle ="+t.calcar());
}}
o/p:
V) Method Overriding: When there are two methods with same name and prototypes in super
class and subclass then it is called Method overriding.
class Bank
{
int getRateOfInterest()
{
return 0;
}
}
class SBI extends Bank{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
class Test{
public static void main(String args[]){
SBI s=new SBI();
class Sup
{
int x;
Sup (int x) //constructor
{
this.x=x;
}
void display()
{
System.out.println("x in Super= "+x);
}}
class sub extends Sup
{
int y;
sub(int x,int y)
{
super(x);
this.y=y;
}
void display()
{
System.out.println("\nX in Super Class="+x);
System.out.println("Y in Sub Class="+y);
}}
class TestOverride
{
public static void main(String naren[])
{
sub obj=new sub(100,200);
obj.display();
}}
o/p:
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
class DynamicDispatch{
public static void main(String args[]){
Bank b1=new SBI();
Bank b2=new ICICI();
Bank b3=new AXIS();
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
Bank b=new Bank();
Bank r;
r=b;
r.getRateOfInTerest();
}
}
o/p:
VII) Abstract Class: Abstraction is the mechanism of exhibiting the necessary things by
hiding the unnecessary things.
An abstract class is a class that may have at least one abstract method.(ie without body)
we cannot create an object for abstract class. Abstract class may have reference variables
but may not have memory for it.
1) Write a Java program to implement a Vehicle Abstract class.
/* Write a Java program to implement an Vehicle Abstract class.*/
abstract class Vehicle
{
public abstract void wheels();
public abstract void seating();
public abstract void brakes();
}
class Car extends Vehicle
{
public void wheels()
{
System.out.println("\nCar Has Four Wheels");
}
public void seating()
{
System.out.println("Car Has Four Seating Capacity");
}
public void brakes()
{
System.out.println("Car Has Power Brakes\n");
}}
class Bike extends Vehicle
{
public void wheels()
{
System.out.println("Bike Has Two Wheels");
}
public void seating()
{
System.out.println("Bike Has Two Seating Capacity");
}
public void brakes()
{
System.out.println("Bike Has Disk Brakes");
}}
class VehicleDemo
{
public static void main(String args[])
{
Vehicle v=new Car();
Vehicle v1=new Bike();
v.wheels();
v.seating();
v.brakes();
v1.wheels();
v1.seating();
v1.brakes();
}}
o/p:
o/p:
VIII) Packages:
Package can be categorized in two form, built-in package and user-defined package.
Advantage of Package :
Package is used to categorize the classes and interfaces so that they can be easily
maintained.
Package provids access protection.
o/p:
2) write a java package for book class and then import and display the result.
1) // Save below file Book.java
package packagetest;
public class Book
{
int book_no,book_id,book_pages;
public Book(int a,int b, int c)
{
book_no=a;
book_id=b;
book_pages=c;
}
public void book_info()
{
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 57
Object Oriented Programming Through Java Laboratory Record
import packagetest.Book;
class BookReader
{
public static void main(String[] args)
{
Book b=new Book(12,15,86);
b.book_info();
}
}
o/p:
3) write a java program to find the cube of a number for various data types using package
and then import and display the results.
//1.program to create package
package mathematics;
public class Mathmethods
{
public static float Cube(float n)
{
return(n*n*n);
}
public static int Cube(int n)
{
return(n*n*n);
}
public static double Cube(double n)
{
return(n*n*n);
}
public static long Cube(long n)
{
return(n*n*n);
}
}
//2. program to import
import mathematics.Mathmethods;
//import java.io.*;
import java.util.Scanner;
class Cube
{
public static void main(String S[])
{
//int a=20;
Scanner m=new Scanner(System.in);
System.out.println("the given number is ");
int a=m.nextInt();
Mathmethods mm = new Mathmethods();
int b = Mathmethods.Cube(a);
System.out.println("cube is " +b);
}
}
o/p:
javac d . Mathmethods.java
javac Cube.java
java Cube
IX ) MultipleInheritance:
we cannot use multiple inheritance means one class cannot be inherited from more than one
classes. To use this process, Java provides an alternative approach known as Interface.
Interface:
An Interface is usually a kind of class. Interface contain only Abstract methods and Final
variable. A java class cannot be a sub class of more than one class, but a class can implements
more than one Interfaces.
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 60
Object Oriented Programming Through Java Laboratory Record
import java.lang.*;
import java.io.*;
interface Exam
{
void percent_cal();
}
class Student
{
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2)
{
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
}
void display()
{
System.out.println ("\nName of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("Marks of Subject 2: "+mark2);
}}
class Result extends Student implements Exam
{
Result(String n, int r, int m1, int m2)
{
super(n,r,m1,m2);
}
public void percent_cal()
{
int total=(mark1+mark2);
float percent=total*100/200;
System.out.println ("Percentage: "+percent+"%");
}
void display()
{
super.display();
}}
class MultipleInheritenceDemo
{
public static void main(String args[])
{
Result R = new Result("Anoop reddy",12,93,84);
R.display();
R.percent_cal();
}}
o/p:
}}
o/p:
import java.lang.*;
class Error2
int a=10;
int b=5;
int c=5;
int x,y;
try
x=a/(b-c);
catch (ArithmeticException e)
System.out.println("division by zero");
y=a/(b+c);
System.out.println("y=" +y);
o/p:
class ExcHandling
int a[]={5,10};
int b=5;
try
int x=a[2]/(b-a[0]);
catch(ArithmeticException e)
System.out.println("div by zero");
catch(ArrayIndexOutOfBoundsException e)
int y=a[1]/a[0];
o/p:
import java.lang.Exception;
class ExHan2
int invalid=0,number,count=0;
for(int i=0;i<args.length;i++)
try
number=Integer.parseInt(args[i]);
catch(NumberFormatException e)
invalid=invalid + 1;
continue;
count=count +1;
o/p:
InsufBalance(String s)
super(s);
class Mainbalance
int bal=5000;
try
int withdraw=Integer.parseInt(s[0]);
if(bal<withdraw)
throw i;
else
bal=bal-withdraw;
System.out.println("balance is "+bal);
catch(InsufBalance i)
System.out.println(i);
catch(Exception e)
System.out.println(e);
o/p:
1) Your Class name with main is the class name without .class exentension.
2) No extra spaces following the your class name with main.
Manifest-Version:1.0
Main-Class: YourClassNameWithMain
Created-by:1.2(Sun Microsystems Inc.)
On Command line : type the following
jar cvfm YourJarFileName.jar YourManifest.MF*
(or)
Drag-drop the YourJarFileName.jar to your desktop double click it, it runs if your p rogram only
has System.out.println(whatever); statements, it will displaynothing. The same will happen
when you run it using java at commandline.
Instructions for creating a .jar file. jar utility comes with your JDK1.2.2 It compresses your file
similar to zip utility, and more Java.
Put all your files turning in that directory. Be sure to put your html file, if there is one
At your dos prompt, while you are in the directory that you created , type in:
jar cvf Prj02.jar*
This will take ALL the files in the directory including subdirectories and place them in a .jar file
Prj02 that can be replaced by any of your desired jar file name.
To test it, you can extract the contents of jar file by typing:
jar xvf Prj02.jar
XIII) Multithreading:
int i;
for(i=0;i<5;i++);
System.out.println(this.getName()+" "+i);
d.setName("\nDAEMON THREAD");
d1.setName("NORMAL THREAD");
d.setPriority(Thread.MIN_PRIORITY);
d.start();
d1.start();
o/p:
class Addition
int a=99,b=1;
System.out.println("c="+(a+b));
try
Thread.sleep(3000);
System.out.println("After Sleep()");
catch (InterruptedException e)
Addition obj1;
public Synchro(Addition a)
obj1=a;
t1.start();
t2.start();
t3.start();
obj1.add();
System.out.println("ThreadNameis"+Thread.currentThread(). getName());
class TestSynchro
o/p:
for(int i=0;i<20;i++)
System.out.println(getName()+":"+i);
System.out.println("main started");
td.setName("Thread1");
td1.setName("Thread2");
td.start();
td1.start();
td.yield();
System.out.println("Main Exited");
o/p:
import java.util.StringTokenizer;
import java.io.*;
class StringTockenizerDemo
String str=br.readLine();
int a,sum=0;
String s;
while(st.hasMoreTokens())
s=st.nextToken();
a=Integer.parseInt(s);
sum=sum+a;
o/p:
import java.io.*;
System.out.println("Start A");
System.out.println("Exit A");
System.out.println("Start B");
System.out.println("Exit B");
System.out.println("Start C");
System.out.println("Exit C");
System.out.println("Start D");
System.out.println("Thread A l :"+l);
System.out.println("Exit D");
class threadtest
new A().start();
new B().start();
new C().start();
new D().start();
o/p:
A file is a collection of related records placed in a particular area on disk. Storing and managing
data using files is known as file processing which includes creating,updating files and
manipulation of data.Reading and writing of data in a file can be done at the level of bytes or
characters or fields.
Input refers to the flow of data into a program and output means the flow of data out of a
program. A stream in java is a path along which data flows. The java.io package contains a large
number of stream classes that provide capabilities for processing all type of data.
import java.io.*;
class FileOutput
try
{
// Create a new file output stream connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to the file myFile.txt");
}
}
}
o/p:
import java.io.*;
class WriteBytes
byte cities[]={'D','E','L','H','I','\n','C','H','E','N','N','A','I','\n','L','O','N','D','O','N','\n'};
FileOutputStream outfile=null;
try
outfile=new FileOutputStream("city.txt");
outfile.write (cities);
outfile.close( );
catch(IOException ioe)
System.out.println(ioe);
System.exit(-1);
o/p:
import java.io.*;
class CopyBytes
FileInputStream infile=null;
FileOutputStream outfile=null;
byte byteRead;
try
outfile=new FileOutputStream("out.dat");
do
byteRead=(byte)infile.read( );
outfile.write(byteRead);
while(byteRead !=-1);
catch(FileNotFoundException e)
catch(IOException e)
System.out.println(e.getMessage( ));
try
infile.close( );
outfile.close( );
catch(IOException e)
{ }
o/p:
Applets: Applets are small java programs that are primarily used in internet computing. They
can be transported over the internet from one computer to another and run using applet viewer or
any web browser.
Applets can perform arithmetic operations, display graphics, play sounds, accept user input ,
create animation, and play interactive games.
import java.awt.*;
import java.applet.*;
/*Coding of HTML File <applet code = abc1.class width= 200 height=200> </applet> */
Faculty name : G.kalpana Course: M.C.A Year/Sem : I st
year /2nd sem 85
Object Oriented Programming Through Java Laboratory Record
int a=100;
int b=200;
g.drawString( s, 200,100);
}}
o/p:
import java.awt.*;
import java.applet.*;
g.drawString("Hello World",20,20);
g.drawRect(40,40,30,50);
g.drawOval(150,150,40,50);
}}
o/p:
import java.awt.*;
import java.applet.*;
Thread t ;
boolean b;
setBackground(Color.gray);
setForeground(Color.yellow);
t = new Thread(this);
b = false; t.start();
char ch;
for( ; ; )
try
repaint();
Thread.sleep(250);
ch = str.charAt(0);
catch(InterruptedException e)
{}
g.drawRect(1,1,300,150);
g.setColor(Color.green);
g.fillRect (1,1,300,150);
g.setColor(Color.red);
g.drawString(str, 1, 150);
}}
o/p:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
class Ball
int x,y,radius,dx,dy;
Color BallColor;
this.x=x;
this.y=y;
this.radius=radius;
this.dx=dx;
this.dy=dy;
BallColor=bColor;
}}
Ball redBall;
redBall=new Ball(250,80,50,2,4,Color.red);
t.start();
g.setColor(redBall.BallColor);
setBackground(Color.pink);
//g.setcolor(redBall.BallColor);
g.drawLine(150,400,50,500);
g.drawLine(150,400,450,400);
g.drawLine(50,500,350,500);
g.drawLine(450,400,350,500);
g.drawRect(50,500,20,100);
g.drawRect(330,500,20,100);
g.drawLine(450,400,450,500);
g.drawLine(430,500,450,500);
g.drawLine(430,500,430,420);
{ while(true)
try
displacementOperation(redBall);
Thread.sleep(20);
repaint();
catch(Exception e)
ball.dy=-ball.dy; } ball.y=ball.y+ball.dy;
o/p:
Awt contains numerous classes and methods that allow you to create and manage
windows. A common use of the AWT is in applets , its is also used to sreate stand-alone windows
that run in a GUI environment , such as Windows.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<html>
<body>
</applet>
</body>
</html> */
Button b;
TextField tf;
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
tf.setText("Welcome");
output:
2) Write a Java program to demonstrate an application involving GUI with controls menus
and event handling.
import javax.swing.*;
public SwingMenu()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
filemenu.add(new JSeparator());
editmenu.add(new JSeparator());
fileItem3.add(new JSeparator());
editItem2.add(new JSeparator());
filemenu.add(fileItem1); filemenu.add(fileItem2);
filemenu.add(fileItem3); filemenu.add(fileItem4);
editmenu.add(editItem1);
editmenu.add(editItem2);
editmenu.add(editItem3);
editmenu.add(editItem4);
menubar.add(filemenu);
menubar.add(editmenu);
frame.setJMenuBar(menubar);
frame.setSize(400,400);
frame.setVisible(true);
}}
o/p: