Professional Documents
Culture Documents
Simple Java Program Aim
Simple Java Program Aim
AIM:
To write a java program to find area of Rectangle by using an instance of a class.
ALGORITHM:
1. Declare the class Rectangle.
2. Declare data members height & width and a method area() to calculate area.
3. Declare another class example.
4. Create an object to Rectangle class and access the area() metod.
5. Print the output.
PROGRAM:
import java.util.Scanner;
class Rectangle // class which contains attributes and
methods {
int height,width;
void area() // method to calculate area
{
int a = height*width;
System.out.println("The Area of Rectangle is :" +a);
}
}
public class example // class which contains
main() {
public static void main(String args[])
{
Rectangle r = new Rectangle(); //creating object for Rectangle class
Scanner s = new Scanner(System.in); // Scanner class to receive input from keyboard.
System.out.println("Enter height of the Rectangle:");
r.height = s.nextInt(); // nextInt() method to get integer type value from keyboard.
System.out.println("Enter width of the Rectangle:");
r.width = s.nextInt(); // nextInt() method to get integer type value from keyboard.
r.area(); // invoking area() method of Rectangle class
}
}
OUTPUT:
C:\> cd vec
RESULT:
Thus the java program to find the area of rectangle was created, executed and output
was verified successfully.
HANDLING STRINGS IN JAVA
AIM:
To write a java program to perform various operations using string function.
ALGORITHM:
1. Start
2. Declare the class called stringUse
3. Initialize two strings and using the two strings manipulate string operation
4. Perform the operation like concat(),length(),chatAt(),startsWith(),endsWith(),etc
5. Display the result
PROGRAM:
import java.util.*;
public class stringUse
{
public static void main (String args [])
{
Scanner scanner = new Scanner (System. in); // Scanner class to receive input from keyboard.
System.out.println ("Enter the First Name :");
String fname=scanner.nextLine(); // nextLine () method to get integer type value from keyboard.
System.out.println ("Enter the Last Name :");
String lname=scanner.nextLine(); // nextLine () method to get integer type value from keyboard.
String name= fname+lname; // concatenates two strings
int len = name.length(); // Returns the length of string
System.out.println ("First Name: " + fname);
System.out.println ("Last Name: " + lname);
System.out.println ("Length of Name: " + len);
String cname =name; // copying string to another string
System.out.println ("Copied Name:" + cname);
System.out.println ("Name in Lowercase: "+ name.toLowerCase()); // Converts all the char(s) to lower case
System.out.println ("Name in Uppercase: " + name.toUpperCase()); // Converts all the char(s) to upper case
char c = name. charAt(0); // Returns the character at the specified index
System.out.println ("Character at position 0:" + c);
boolean b=fname.startsWith("v"); // Tests the string starts with the specified character.
System.out.println ("Checks First name starts with character v :"+b);
if(cname == name) // checks ‘name’ and ‘cname’ shares the same location
{
System.out.println ("Same memory location = true");
}
else
System.out.println ("Same memory location = false");
String substr= cname.substring (0, 3); // It returns new String containing the substring of the
given
string from specified startIndex to endIndex(exclusive).
System.out.println ("Substring: " + substr);
boolean b1=name.equals(cname); // Compares string by considering case
System.out.println ("Name equality with case checking:" + b1);
boolean b2=name.equalsIgnoreCase(cname); // Compares string by ignoring case
System.out.println ("Name equality without case checking:" + b2);
}
}
OUTPUT:
C:\> cd vec
RESULT:
Thus a java program for handling strings was created, executed and output was verified
successfully.
SIMPLE PACKAGE CREATION
AIM:
To write a java program to create a package.
ALGORITHM:
1. Start
2. Declare the class called Balance and two methods read(), show() in a file
3. Declare the class called AccountBalance and create an object in another file
4. Import the package and invoke the method show() using the object of class
Balance.
5. Display the result
PROGRAM: Instructions:
1. Create a folder named mypackage
Balance.java
package mypackage; 2. Go to the folder mypackage
public class Balance 3. Create a java program - Balance.java
{
String name; 4. Create a java program - AccountBalance.java and save
int bal; it under the vec folder.
public void read(String n, int b) 5. Open the command prompt
{ StartÆRunÆcmd
name = n;
bal = b; 6. C:\vec> set PATH=”C:\jdk1.7\bin”;
} 7. C:\vec> set CLASSPATH=”C:\jdk1.7\lib”;
public void show() 8. C:\vec\javac mypackage\Balance.java
{ (Balance.class file will be created in mypackage folder)
if(bal>0)
{ 9. C:\vec>javac AccountBalance.java
System.out.println(name +":$"+bal); (AccountBalance.class file will be created)
} 10. C:\vec>java AccountBalance
} 11. Now the output will be displayed.
}
AccountBalance.java
import mypackage.Balance;
class AccountBalance
{
public static void main(String arg[]) throws NoClassDefFoundError
{
Balance obj = new Balance(); // creating object of class A
obj.read("Sachin", 10000); // values are instr
obj.show(); //invoking show() method in the balance class
}
}
OUTPUT:
C:\vec>javac mypackage\Balance.java
C:\vec>javac AccountBalance.java
C:\vec>java AccountBalance
Sachin : $10000
RESULT:
Thus a java program to create a package was created, executed and output was verified
successfully.
SIMPLE PACKAGE CREATION
AIM:
To write a java program to find the account balance by array of objects using
package. ALGORITHM:
1. Declare class Balance and pass parameterized constructor.
2. Initialize name and balance as n and b.
3. Use member function to check balance greater than 0 and print the result.
4. Declare another class account import package.
5. Access show() function and print result.
PROGRAM:
Balance.java
package pack;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name=n;
bal=b;
}
public void show()
{
if(bal>0)
{
System.out.println(name +":$"+bal);
}
}
}
AccountBalance.java
import pack.Balance;
class AccountBalance
{
public static void main(String arg[])
{
Balance current[]=new Balance[3];
current[0]=new Balance("Steve Jobs",123.23);
current[1]=new Balance("Will Smith",157.10);
current[2]=new Balance("Tom Jackson",-12.55);
for(int i=0;i<3;i++)
{
current[i].show();
}
}
}
OUTPUT:
C:\vec>javac pac\Balance.java
C:\vec>javac AccountBalance.java
C:\vec>java AccountBalance
Steve Jobs : $123.33
Will Smith : $157.10
RESULT: Thus java program to find the balance amount using packages was created, executed and
output was verified successfully.
INTERFACES - DEVELOPING USER DEFINED INTERFACES
AIM:
To write a java program to develop user defined interfaces.
ALGORITHM:
1. Start the program
2. Declare the interface called Area and declare the function called compute in it.
3. Define the class called Rectangle and implement the interface Area.
4. Define the class called Circle and implement the interface Area.
5. Display the result.
PROGRAM:
import java.io.*;
interface Area
{
final static float pi=3.14F;
float compute(float x, float y);
}
class MainClass
{
public static void main(String args[])
{
Rectangle rect=new Rectangle(); // Object to class ‘Rectangle’
Circle cir=new Circle(); // Object to class ‘Circle’
System.out.println("Area of Rectangle ="+ rect.compute(10,20));
System.out.println("Area of Circle ="+ cir.compute(10,0));
}
}
OUTPUT:
C:\vec>javac MainClass.java
C:\vec>java MainClass
Area of Rectangle = 200.0
Area of Circle=314.0
RESULT:
Thus java program to implement user defined interface was created, executed and output was
verified successfully.
INTERFACES – USING PRE-DEFINED
INTERFACES AIM:
To write a java program using pre defined interfaces
ALGORITHM:
1. Create a class called ‘Person’ which implements predefined interface ‘Comparable’
2. Declare data members name and age in a constructor.
3. Define the member function getName() and getAge()
4. compareTo() is the method of ‘Comparable’ interface
5. Display the result.
PROGRAM:
public class Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
public int compareTo(Person per)
{
if(this.age == per.age)
return 0;
else
return this.age > per.age ? 1 : -1;
}
public static void main(String args[])
{
Person e1 = new Person("Adam", 50);
Person e2 = new Person("Steve", 60);
int val = e1.compareTo(e2);
switch(val)
{
case -1:
{
System.out.println("The " + e2.getName() + " is older!");
break;
}
case 1:
{
System.out.println("The " + e1.getName() + " is older!");
break;
}
default:
System.out.println("The two persons are of the same age!");
}
}
}
OUTPUT:
C:\vec>javac Person.java
C:\vec>java Person
The Steve is older!
RESULT:
Thus a java program for pre defined interface was created, executed and output was verified
successfully.
CREATION OF THREADING IN JAVA
AIM:
To implement threading and exception handling using java program.
ALGORITHM:
1. Declare class Th1 that extends from Thread
2. Declare try, catch with data.
3. Declare another two classes Th2 & Th3 and define method run().
4. Declare main class ThreadDemo and create object t1, t2 and t3 for each class and Access it.
5. Display the result.
PROGRAM:
import java.io.*;
class Th1 extends Thread
{
public void run()
{
try
{
Thread.sleep(1000);
System.out.println("Name: Alex");
System.out.println("Age: 20");
}
catch(InterruptedException i) {}
}
}
OUTPUT:
C:\javaprg>javac ThreadDemo.java
C:\javaprg>java ThreadDemo
Name : Alex
Age : 20
Class : computer
College : ddit
City : dire
State : dire
RESULT:
Thus a java program for threading was created, executed and output was verified successfully.
MULTITHREADING IN JAVA
AIM:
To write a java program on multithreading concept.
ALGORITHM:
1. Start the program
2. Create a main thread called ThreadDemo and starts its execution
3. Invoke the child thread class called newThread
3. newThread() invokes the superclass constructor and starts the child thread execution.
4. Main thread and child thread runs parallelly.
5. Display the result.
PROGRAM:
import java.io.*;
class Newthread extends Thread
{
Newthread()
{
super("DemoThread");
System.out.println("Child Thread:" +this);
start();
}
public void run()
{
try
{
for(int i=5;i>0;i--)
{
System.out.println("Child Thread:" +i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("Child Thread Interrupted");
}
System.out.println("Exiting Child Thread");
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
new Newthread();
try
{
for(int i=5;i>0;i--)
System.out.println("Main Thread:" +i);
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
System.out.println("Exiting Main Thread");
}
}
OUTPUT:
C:\javaprg>javac MultiThreadDemo.java
C:\javaprg>java MultiThreadDemo
Child Thread:Thread[DemoThread,5,main]
Main Thread:5
Main Thread:4
Main Thread:3
Main Thread:2
Child Thread:5
Main Thread:1
Child Thread:4
Exiting Main Thread
Child Thread:3
Child Thread:2
Child Thread:1
Exiting Child Thread
RESULT:
Thus a java program for multi threading was created, executed and output was
verified successfully.
HANDLING PREDEFINED EXCEPTION
AIM:
To implement the pre defined exception concept in java
ALGORITHM:
1. Start the program
2. Create the called error.
3. Declare and Initialize the data members.
4. Use the try and catch block to handle the exception
5. If the exception exists, corresponding catch block will be executed or else control goes out
of
the catch block.
6. Display the result.
PROGRAM:
class Exception
{
public static void main(String args[])
{
int a=10, b=5, c=5, result;
try
{
result =a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Exception occurs: Division by Zero");
}
result =a/(b+c);
System.out.println("Result =" + result);
}
}
OUTPUT:
RESULT:
Thus a java program for pre defined exception was created, executed and output was verified
successfully.
HANDLING USERDEFINED EXCEPTION
AIM:
To implement the user defined exception concept in java
ALGORITHM:
1. Create a user defined exception class called MyException
2. Throw an exception of user defined type as an argument in main()
3. Exception is handled using try, catch block
4. Display the user defined exception
PROGRAM:
import java.lang.Exception;
class JavaException
{
public static void main(String args[])
{
try
{
throw new MyException(2); // throw is used to create a new exception and throw it.
}
catch(MyException e)
{
System.out.println(e) ;
}
}
}
OUTPUT
C:\javaprg >javac JavaException.java
C:\javaprg >java JavaException
Exception Number = 2
RESULT:
Thus a java program for user defined exception was created, executed and output was verified
successfully.
ADDITIONAL EXERCISES IN JAVA
DRAW SMILEY USING JAVA APPLET
Algorithm:
Step 1: Create a java program Smiley.java
Step 2: import awt an applet package and create a class that extends Applet
Step 3: Using various methods in awt and applet class draw a face.
Step 4: Create a html file called Smiley.html and write the applet code.
Step 5: Stop
Program:
// Smiley.java
import java.awt.*;
import java.applet.*;
public class Smiley extends Applet
{
public void paint(Graphics g)
{
Font f = new Font("Helvetica", Font.BOLD, 20);
g.setFont(f);
g.drawString("Keep Smiling!!!", 50, 30);
g.drawOval(60, 60, 200, 200);
g.fillOval(90, 120, 50, 20);
g.fillOval(190, 120, 50, 20);
g.drawLine(165, 125, 165, 175);
g.drawArc(110, 130, 95, 95, 0, -180);
}
}
//Smiley.html
</html>
<body>
<applet code="Smiley.class" width=300 height=300></applet>
</body>
</html>
Output:
C:\vec>javac Smiley.java
C:\vec>appletviewer Smiley.html
RESULT:
Thus a java applet program for drawing smiley face was created, executed and output was
verified successfully.
ADDING TWO NUMBERS USING JAVA APPLET
Aim: To create a java applet program for adding two numbers by getting input from the user
Algorithm:
Step 1: Create a java program Sum.java
Step 2: import awt an applet package and create a Sum that extends Applet
Step 3: Using various methods in awt and applet class draw a face.
Step 4: Create a html file called Sum.html and write the applet code.
Step 5: Stop
Program:
// Sum.java
import java.awt.*;
import java.applet.*;
//Sum.html
<html>
<body>
<applet code="Sum.class" width=350 height=150></applet>
</body>
</html>
Output:
C:\vec>javac Sum.java
C:\vec>appletviewer Sum.html
RESULT:
Thus a java applet program for adding two numbers was created, executed and output was
verified successfully.
DRAW ARCS USING JAVA APPLET
Algorithm:
Step 1: Create a java program Arcs.java
Step 2: import awt an applet package and create a class that extends Applet
Step 3: Using various methods in awt and applet class draw a face.
Step 4: Create a html file called Arcs.html and write the applet code.
Step 5: Stop
Program:
// Arcs.java
import java.awt.*;
import java.applet.*;
public class Arcs extends Applet
{
public void init()
{
setBackground(Color.black);
setForeground(Color.green);
}
public void paint(Graphics g)
{
g.drawArc(10, 40, 70, 70, 0, 75);
g.fillArc(100, 40, 70, 70, 0, 75) ;
g.drawArc(10, 100, 70, 80, 0, 175);
g.fillArc(100, 100, 70, 90, 0, 270);
g.drawArc(200, 80, 80, 80, 0, 180);
}
}
//Arcs.html
<html>
<body>
<applet code="Arcs.class" width=300 height=250></
applet>
</body>
</html>
C:\vec>javac
Output: Arcs.java
C:\vec>appletviewer Arcs.html
RESULT:
Thus a java applet program for drawing arcs was created, executed and output was verified
successfully.
DRAW BUTTONS USING JAVA APPLET
Algorithm:
Step 1: Create a java program ButtonDemo.java
Step 2: import awt an applet package and create a class that extends Applet
Step 3: Using various methods in awt and applet class draw a face.
Step 4: Create a html file called ButtonsDemo.html and write the applet code.
Step 5: Stop
Program:
// ButtonDemo.java
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo extends Frame implements ActionListener
{
Button redBut, greenBut, blueBut, closeBut;
public ButtonDemo()
{
setLayout(new FlowLayout());
redBut = new Button("RED");
greenBut = new Button("GREEN");
blueBut = new Button("BLUE");
closeBut = new Button("CLOSE");
redBut.addActionListener(this);
greenBut.addActionListener(this);
blueBut.addActionListener(this);
closeBut.addActionListener(this);
closeBut.setForeground(Color.red);
add(redBut);
add(greenBut);
add(blueBut);
add(closeBut);
setTitle("Buttons in Action");
setSize(300, 300);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand();
if(str.equals("RED"))
setBackground(Color.red);
else if(str.equals("GREEN"))
setBackground(Color.green);
else if(str.equals("BLUE"))
setBackground(Color.blue);
else if(str.equals("CLOSE"))
System.exit(0);
}
public static void main(String args[])
{
new ButtonDemo();
}
}
// ButtonDemo.html
<html>
<body>
<applet code=" ButtonDemo.class" width=300 height=250></applet>
</body>
</html>
Output:
C:\vec>java ButtonDemo.java
C:\vec>appletviewer ButtonDemo.html
RESULT:
Thus a java applet program for creating buttons was created, executed and output was verified
successfully.
CHAT APPLICATION USING JAVA APPLET
Algorithm:
Program:
// Server.java
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String[] args) throws IOException
{
ServerSocket sersock = new ServerSocket(3000);
System.out.println("Server ready for chatting...");
Socket sock = sersock.accept( );
// reading from keyboard
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
RESULT:
Thus a java applet program for chat application was created, executed and output was verified
successfully.