0% found this document useful (0 votes)
4 views27 pages

Java Class and Object Examples

I want it for study more for my future job.

Uploaded by

saranranjith2005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views27 pages

Java Class and Object Examples

I want it for study more for my future job.

Uploaded by

saranranjith2005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Class and object

1.a) Book details using class and object


import [Link];
class book
{
String bname,aname;
int bid;
float price;
void get()
{
Scanner sc=new Scanner([Link]);
[Link]("Enter book name:");
bname=[Link]();
[Link]("Enter author name:");
aname=[Link]();
[Link]("Enter book id:");
bid=[Link]();
[Link]("Enter book price:");
price=[Link]();
[Link]();
}
void put()
{
[Link]("****BOOK DETAILS****");
[Link]("Book id :"+bid);
[Link]("Book name :"+bname);
[Link]("Author name :"+aname);
[Link]("Book price :"+price);
}
}
class bdetails
{
public static void main(String args[])
{
book bk=new book();
[Link]();
[Link]();
}
}
Output:
Z:\>javac [Link]
Z:\>java bdetails
Enter book name:
Programming in Java
Enter author name:
Balaguruswamy
Enter book id:
101
Enter book price:
250.50
****BOOK DETAILS****
Book id :101
Book name :Programming in Java
Author name :Balaguruswamy
Book price :250.5
1.b) Personal Details using class and object
import [Link].*;
class person
{
String pname;
int age;
long mob;
void get()
{
Scanner sc=new Scanner([Link]);
[Link]("Enter the person's name :");
pname=[Link]();
[Link]("Enter the age :");
age=[Link]();
[Link]("Enter the mobile number :");
mob=[Link]();
[Link]();
}
void put()
{
[Link]("****PERSONAL DETAILS****");
[Link]("Name :"+pname);
[Link]("Age :"+age);
[Link]("Mobile number:"+mob);
}
}
class pdetails
{
public static void main(String args[])
{
person pr=new person();
[Link]();
[Link]();
}
}
Output:
Z:\ >javac [Link]
Z:\ >java pdetails
Enter the person's name :
Ram
Enter the age :
20
Enter the mobile number :
9876543210
****PERSONAL DETAILS****
Name :Ram
Age :20
Mobile number:9876543210
1.c) To find the minimum value using static function
import [Link].*;
class minvalue
{
public static void main(String args[])
{
int n1,n2;
Scanner sc=new Scanner([Link]);
[Link]("Enter the first number:");
n1=[Link]();
[Link]("Enter the second number:");
n2=[Link]();
[Link]("The minimum of "+n1+" and "+n2+" is :"+min1(n1,n2));
[Link]();
}
public static int min1(int x,int y)
{
int min;
if(x<y)
{
min=x;
}
else
{
min=y;
}
return(min);
}
}
Output:
Z:\ >javac [Link]
Z:\ >java minvalue
Enter the first number:
12
Enter the second number:
10
The minimum of 12 and 10 is :10
2) Inheritance

[Link] Program using Single Inheritance


class employee
{
float salary;
employee()
{
[Link]=50000;
}
}
class programmer extends employee
{
float bonus;
programmer()
{
[Link]=2000;
}
public static void main(String args[])
{
programmer prg=new programmer();
float totsal=[Link]([Link],[Link]);
[Link]("Total salary for programmer is:"+totsal);
}
float getsalary(float basicsalary,float bonus)
{ return basicsalary+bonus; }
}
Output:
Z:\csus21057>javac [Link]
Z:\csus21057>java programmer
Total salary for programmer is:52000.0
[Link] Manipulation
3.a) Built-in Functions using String manipulation
import [Link];
class stringdemo
{
public static void main(String args[])
{
String s1=new String("national college");
String s2="NATIONAL COLLEGE";
[Link]("The string s1 is :"+s1);
[Link]("The string s2 is :"+s2);
[Link]("Length of the string s1 is :"+[Link]());
[Link]("First occurance of t is at the position :"+[Link]('t'));
[Link]("The String in upper case :"+[Link]());
[Link]("The string in lower case :"+[Link]());
[Link]("s1 equals to s2 :"+[Link](s2));
[Link]("s1 eqauls ignore case s2
:"+[Link](s2));
[Link]("Character at an index of 6 is :"+[Link](6));
String s3=[Link](4,12);
[Link]("Extracted string is :"+s3);
[Link]("After replacing o with j in s1 :"+[Link]('o','j'));
String s4="This is JAVA string program";
[Link]("The String s4 is :"+s4);
[Link]("After Trim() :"+[Link]());
}
}
Output:
Z:\ >javac [Link]
Z:\ >java stringdemo
The string s1 is :national college
The string s2 is :NATIONAL COLLEGE
Length of the string s1 is :16
First occurance of t is at the position :2
The String in upper case :NATIONAL COLLEGE
The string in lower case :national college
s1 equals to s2 :false
s1 eqauls ignore case s2 :true
Character at an index of 6 is :a
Extracted string is :onal col
After replacing o with j in s1 :natijnal cjllege
The String s4 is :This is JAVA string program
After Trim() :This is JAVA string program
3.b) User Defined Package using Interface
//Interface class
package pack;
import [Link].*;
public interface shape
{
public void read();
public void area();
public void print();
}
Output:
Z:\csus21057>cd pack

Z:\ pack>set path="C:\Program Files\Java\jdk1.8.0_241\bin"

Z:\ pack>javac [Link]

Z:\csus21057\pack>cd..
// import Package
import [Link].*;
import [Link].*;
import [Link];
import [Link];
class rectangle implements shape
{
double a,l,b;
public void read()
{
Scanner sc=new Scanner([Link]);
[Link]("\n\t AREA OF THE RECTANGLE");
[Link]("\n\t*******************");
[Link]("Enter the length of the rectangle:");
l=[Link]();
[Link]("Enter the breadth of the rectangle:");
b=[Link]();
[Link]("The length of the rectangle:"+l);
[Link]("The breadth of the rectangle:"+b);
}
public void area()
{
a=l*b;
}
public void print()
{
[Link]("\n\n\t\t Area of the rectangle:"+a);
}
}
class shapedemo
{
public static void main(String args[])
{
[Link]("\n\t\t INTERFACE AND PACKAGES");
[Link]("\n\t*******************");
rectangle r=new rectangle();
[Link]();
[Link]();
[Link]();
}
}

Output:
Z:\ >javac [Link]
Z:\ >java shapedemo
INTERFACE AND PACKAGES
*******************
AREA OF THE RECTANGLE
*******************
Enter the length of the rectangle:
150
Enter the breadth of the rectangle:
100
The length of the rectangle:150.0
The breadth of the rectangle:100.0

Area of the rectangle:15000.0


4. Vector Manipulation

//Java program using Vector class


import [Link].*;
class vectordemo
{
public static void main(String args[])
{
Vector v1=new Vector();
[Link](1);
[Link](2);
[Link]("Apple");
[Link]("Vivo");
[Link]("Oppo");
[Link]("**********VECTOR MANIPULATION**********");
[Link]("\n The vector v1 contains");
[Link](v1);
[Link]("\n After replacement 1 by Samsung");
[Link](0,"Samsung");
[Link]("The new vector is:"+v1);
[Link]("After deleting 2 from vector");
[Link](1);
[Link](v1);
}
}
Output:
Z:\ >javac [Link]
Note: [Link] uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Z:\ >java vectordemo


**********VECTOR MANIPULATION**********

The vector v1 contains


[1, 2, Apple, Vivo, Oppo]

After replacement 1 by Samsung


The new vector is:[Samsung, 2, Apple, Vivo, Oppo]
After deleting 2 from vector
[Samsung, Apple, Vivo, Oppo]
5. Exception Handling

5.a)ArithmeticException
import [Link].*;
class arithematicdemo
{
public static void main(String args[])throws IOException
{
int x=50,y=0,z;
try
{
z=x/y;
[Link]("z="+z);
}
catch(ArithmeticException e)
{
[Link](e);
[Link]("Zero error");
}
[Link]("End of the program");
}
}
Output:
Z:\ >javac [Link]

Z:\ >java arithematicdemo


[Link]: / by zero
Zero error
End of the program
5.b)Array Index out of Bounds Exception
import [Link].*;
class exceptionarray
{
public static void main(String args[])
{
try
{
int a[]={1,2,3,4};
for(int i=1;i<=4;i++)
{
[Link]("a["+i+"]="+a[i]+"\n");
}
}
catch(Exception e)
{
[Link]("Error: "+e);
}
}
}
Output:
Z:\>javac [Link]

Z:\ >java exceptionarray


a[1]=2

a[2]=3

a[3]=4

Error: [Link]: 4
5.c)Invalid Age Exception
import [Link].*;
class invalidageexception extends Exception
{
public invalidageexception(String str)
{ super(str); }
}
public class testexceptdemo
{
static void validate(int age)throws invalidageexception
{ if(age<18)
{ throw new invalidageexception("Age is not valid to vote"); }
else
{ [Link]("Welcome to vote"); }
}
public static void main(String args[])
{
try
{ validate(13); }
catch(invalidageexception ex)
{
[Link]("Caught the exception");
[Link]("Exception occured:"+ex);
}
finally
{ [Link]("Rest of the code"); }
}
}
Output:
Z:\ >javac [Link]

Z:\ >java testexceptdemo


Caught the exception
Exception occured:invalidageexception: Age is not valid to vote
Rest of the code
[Link]
6.a)Smiley Face using Applet
import [Link];
import [Link].*;
public class Smiley extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](20,20,150,150); // For face
[Link]([Link]);
[Link](50,60,15,25); // Left Eye
[Link](120,60,15,25); // Right Eye
int x[] = {95,85,106,95};
int y[] = {85,104,104,85};
[Link](x, y, 4); // Nose
[Link](55,95,78,50,0,-180); // Smile
[Link](50,126,60,116); // Smile arc1
[Link](128,115,139,126); // Smile arc2
}
}

/* <applet code="[Link]" width="200" height="200">


</applet>*/

Output:
D:\java\javac [Link]
D:\java\appletviewer [Link]
6.b)Java Program to Create a ColorBars using Applet
import [Link].*;
import [Link].*;

/* <applet code="[Link]" height=400 width=400>


</applet> */

public class ColorBar extends Applet


{
Color colors[]={ [Link], [Link], [Link], [Link], [Link],
[Link], [Link], [Link], [Link], [Link],
[Link], [Link]
};

public void paint(Graphics g)


{
Dimension d = getSize();
int x = [Link]/[Link];
setBackground([Link]);
for (inti=0; i<[Link] ; i++ )
{
[Link](colors[i]);
[Link](0, i*x , [Link], (i+1) * x);
}
}
}

Output:
E:\java>javac [Link]
E:\java>appletviewer [Link]
6.c) Java Program to Create a Pie Chart using a Frame
import [Link].*;
import [Link].*;

/*<applet code = "[Link]" width=500 height=500>


</applet>*/

public class PieChart extends Applet


{
int[] data_values;
Color[] data_clr;
int total;
//Function to create a data set
public void init()
{
setBackground([Link]);
//Create a data set to represent in pie-chart
data_values=new int[]{10,25,12,15,15,18,5};
data_clr=new Color[]{[Link],[Link],[Link],[Link],
[Link],[Link],[Link]};
}
//Function to get the sum of all data values
public void start()
{
int n = data_values.length;
inti;
total=0;

for(i=0;i<n;i++)
{
total+=data_values[i];
}
}
//Function to draw the pie chart
public void paint(Graphics g)
{
int i;
int start_angle = 0;
for(i=0;i<data_values.length;i++)
{
int arc_angle = (int)(data_values[i]*360 / total);
[Link](100,100,300,300,start_angle,arc_angle);
[Link](data_clr[i]);
[Link](100,100,300,300,start_angle,arc_angle);
start_angle+=arc_angle;
} } }

Output:
E:\java>javac [Link]
E:\java>appletviewer [Link]
7. MultiThreading Concept

7.a)Display a Table using SimpleThread


class Table implements Runnable
{
public void run()
{
[Link]("Thread Started its execution....");
for(inti=1;i<=10;i++)
{ [Link](i+" * 6 ="+(i*6)); }
[Link]("Thread completed its execution....");
}
}
public class FirstThread
{
public static void main(String args[])
{ Table r=new Table();
Thread t=new Thread(r);
[Link]();
}
}

Output:
D:\java>cd BCA
D:\java>set path="D:\jdk1.8.0\bin"
D:\java>javac [Link]
D:\java>java FirstThread
Thread Started its execution....
1 * 6 =6
2 * 6 =12
3 * 6 =18
4 * 6 =24
5 * 6 =30
6 * 6 =36
7 * 6 =42
8 * 6 =48
9 * 6 =54
10 * 6 =60
Thread completed its execution....
7.b) Fibonacci Series using MultiThread Concept
class MultiThread extends Thread
{ public void run()
{ float t=15/0;
[Link](t);
}
}
class Fibbo extends Thread
{ public void run()
{ [Link]("2 ndThread:Fibonacci Series started..");
int f=0, s=1, t,i,MAX=10;
[Link](f+"\n"+s);
for(i=2;i<MAX;i++)
{ try{
if (i==7)
{[Link]("Second Thread is sleeping for 10 Sec.");
[Link](10000);
[Link]("Second Thread is resumes its
execution...");
}
}catch(Exception e)
{ [Link]("An Exception has occured...."+e);
}
t=f+s;
[Link](t);

f=s; s=t;
}
} }
public class MultithreadDemo
{
public static void main(String args[])
{
MultiThread m1=new MultiThread();
[Link]();
Fibbo f1=new Fibbo();
[Link]();
}
}
Output:
D:\java\javac [Link]
D:\java\>java multithreaddemo
Exception in thread "Thread-0" Second Thread : Fibonacci Series started..
0
1
1
2
3
5
8
Second Thread is sleeping for 10 Sec.
[Link]:
/ by zero at [Link]([Link])

Second Thread is resumes its execution...


13
21
34
[Link] COMPONENTS

8.a)Border Layout Using AWT


import [Link].*;
import [Link].*;

/*<applet code="[Link]" width=400 height=400>


</applet>*/

public class Layoutdemo extends Applet {


public void init() {
setLayout(new BorderLayout());

Button topButton = new Button("Top");


add(topButton, [Link]);

Button bottomButton = new Button("Bottom");


add(bottomButton, [Link]);

Button rightButton = new Button("Right");


add(rightButton, [Link]);

Button leftButton = new Button("Left");


add(leftButton, [Link]);

Button middleButton = new Button("Middle");


add(middleButton, [Link]);
}
}

Output:
D:\java\javac [Link]
D:\java\appletviewer [Link]
8.b)MouseEvents Using AWT
import [Link].*;
import [Link];
import [Link].*;

/*<applet code="[Link]" width=400 height=400>


</applet>*/

public class MouseDemo extends Applet implements MouseListener


{
public void init()
{ addMouseListener(this); }
public void mouseClicked(MouseEvent e)
{
setBackground([Link]);
showStatus("Mouse Clicked.....");
repaint();
}
public void mouseEntered(MouseEvent e)
{
setBackground([Link]);
showStatus("Mouse Entered....");
repaint();
}
public void mouseExited(MouseEvent e)
{
setBackground([Link]);
showStatus("Mouse Exited....");
repaint();
}
public void mousePressed(MouseEvent e)
{
setBackground([Link]);
showStatus("Mouse Pressed....");
repaint();
}
public void mouseReleased(MouseEvent e)
{
setBackground([Link]);
showStatus("Mouse Released....");
repaint();
}
}

Output:
D:\java\javac [Link]
D:\java\appletviewer [Link]
8.c)Painting Using AWT
import [Link].*;
import [Link].*;
import [Link].*;

/*<applet code="[Link]" width="300" height="300">


</applet> */

public class Painting extends Applet implements MouseMotionListener


{
public void init ()
{
addMouseMotionListener (this);
setBackground ([Link]);
}
public void mouseDragged (MouseEvent me)
{
Graphics g = getGraphics ();
[Link] ([Link]);
[Link] ([Link] (), [Link] (), 5, 5);
}
public void mouseMoved (MouseEvent me)
{
}
}

Output:
D:\java\javac [Link]
D:\java\appletviewer [Link]

You might also like