You are on page 1of 20

Edited with the trial version of

Foxit Advanced PDF Editor


To remove this notice, visit:
www.foxitsoftware.com/shopping
SIMPLE JAVA PROGRAM

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

C:\vec> set PATH=“C:\Program Files\Java\jdk1.7.0_75\bin”;


C:\vec> javac example.java
C:\vec> java example
Enter height of the
Rectangle: 10
Enter width of the
Rectangle: 5
The Area of Rectangle is: 50

RESULT:
Thus the java program to find the area of rectangle was created, executed and output
was verified successfully.

Page: 1
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);
}
}

Page: 2
OUTPUT:

C:\> cd vec

C:\vec> javac stringUse.java

C:\vec> java stringUse

Enter the First Name: sam


Enter the Last Name: daniel
First Name: sam
Last Name: daniel
Length of Name: 9
Copied Name: samdaniel
Name in Lowercase: samdaniel
Name in Uppercase: SAMDANIEL
Character at position 0: s
Checks First name starts with character v: false
Same memory location = true
Substring: sam
Name equality with case checking: true
Name equality without case checking: true

RESULT:

Thus a java program for handling strings was created, executed and output was verified
successfully.

Page: 3
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.

Page: 4
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.

Page: 5
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 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);
}
}

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.

Page: 6
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!");
}
}
}

Page: 7
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.

Page: 8
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) {}
}
}

class Th2 extends Thread


{
public void run()
{
try
{
Thread.sleep(2000);
System.out.println("Class: computer");
System.out.println("College: ddit");
}
catch(InterruptedException i) {}
}
}

class Th3 extends Thread


{
public void run()
{
try
{
Thread.sleep(3000);
System.out.println("City: dire");
System.out.println("State: dire");
}
catch(InterruptedException i) {}
}
}

Page: 9
class
ThreadDemo {
public static void main(String args[ ])
{
Th1 t1=new Th1();
t1.start( );
Th2 t2=new Th2();
t2.start( );
Th3 t3=new Th3( );
t3.start( );
}
}

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.

Page: 10
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");
}
}

Page: 11
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.

Page: 12
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:

C:\javaprg> javac Exception.java


C:\javaprg> java Exception

Exception occurs: Division by Zero


Result = 1

RESULT:
Thus a java program for pre defined exception was created, executed and output was verified
successfully.

Page: 13
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 MyException extends Exception


{
int a;
MyException(int b)
{
a=b;
}
public String toString()
{
return ("Exception Number = " +a) ;
}
}

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.

Page: 14
Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

//EXAMPLE PROGRAM FOR CONSTRUCTOR AND DESTRUCTOR IN JAVA

In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the object is created, and memory is allocated for the object.
It is a special type of method which is used to initialize the object.
When is a constructor called
Every time an object is created using new () keyword, at least one constructor is called. It
calls a default constructor.
Note: It is called constructor because it constructs the values at the time of object creation.
It is not necessary to write a constructor for a class. It is because java compiler creates a
default constructor if your class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:
1. Default constructor (no-arg constructor): No parameters are their.
2. Parameterized constructor
//Default constructor program
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
//Java Program to demonstrate the use of parameterized constructor
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;

15
Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
//EXAMPLE PROGRAM FOR CONSTRUCTOR OVERLOADING
In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the list
and their types.

//Java program to overload constructors in java


class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();

16
Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

}
}

Java Copy Constructor


There is no copy constructor in java. However, we can copy the values from one object to
another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using java
constructor.

class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}

//Example program for single inheritance

class Animal
{

17
Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}

18
Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

//EXAMPLE PROGRAM FOR MULTILEVEL INHERITANCE

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}

19
Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

//EXAMPLE PROGRAM FOR HIERARCHIAL INHERITANCE

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{
System.out.println("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}

20

You might also like