0% found this document useful (0 votes)
266 views

Java Lab List

The document contains a list of 9 Java programming lab exercises covering topics such as: 1. Creating classes, objects and methods 2. Sorting elements in an array using bubble sort 3. Demonstrating constructor and method overloading 4. Implementing string handling methods 5. Demonstrating inheritance between classes 6. Implementing multiple inheritance using interfaces 7. Creating shape classes in a package 8. Implementing custom exception handling for bank withdrawals 9. Demonstrating multithreading implementation

Uploaded by

Prajwal Kumbar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
266 views

Java Lab List

The document contains a list of 9 Java programming lab exercises covering topics such as: 1. Creating classes, objects and methods 2. Sorting elements in an array using bubble sort 3. Demonstrating constructor and method overloading 4. Implementing string handling methods 5. Demonstrating inheritance between classes 6. Implementing multiple inheritance using interfaces 7. Creating shape classes in a package 8. Implementing custom exception handling for bank withdrawals 9. Demonstrating multithreading implementation

Uploaded by

Prajwal Kumbar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

LIST OF LAB PROGRAMS

1. Write a JAVA Program to implement class, object and method.


Eg: Write a program to print the area of a rectangle by creating a class named 'Area'
having two methods. First method named as 'setDim' takes length and breadth of
rectangle as parameters and the second method named as 'getArea' returns the area of
the rectangle.
Solution
public class Area{
int length,breadth;
public void setDim(int l, int b){
length = l;
breadth = b;
}
public int getArea(){
int results = length * breadth;
return results;
}
public static void main(String []args){
Area x =new Area();
x.setDim(6,4);
int a=getArea();
System.out.println("Area ="+a);
}
}

2. Write a Java program to sort for an element in a given list of elements using bubble
sort.
Solution
Public class bubble
{
public static void main(String args[])
{
int[] data = { -2, 45, 0, 11, -9 };
Int size=data.length;
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; j < size - i - 1; j++)
{
if (data[j] > data[j + 1])
{
int temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
System.out.println("Sorted Array in Ascending Order:");
for(int i=0;i<size;i++)
System.out.println(data[i]+” ”);
}
}
}
3. Write a JAVA Program to demonstrate Constructor Overloading and Method
Overloading

4. Write a program in Java for String handling, the program must implement any 5
methods of String and String Buffer classes.

import java.lang.String;
public class StringMethods{
Void stringclassmethods(){
String targetString = "Java is fun to learn";
String s1= "JAVA";
String s2= "Java";
String s3 = " Hello Java ";
System.out.println("Char at index 2(third position): " + targetString.charAt(2));
System.out.println("After Concat: "+ targetString.concat("-Enjoy-"));
System.out.println("Checking equals ignoring case: " +s2.equalsIgnoreCase(s1));
System.out.println("Checking equals with case: " +s2.equals(s1));
System.out.println("Checking Length: "+ targetString.length());
System.out.println("Replace function: "+ targetString.replace("fun", "easy"));
System.out.println("SubString of targetString: "+ targetString.substring(8));
System.out.println("SubString of targetString: "+ targetString.substring(8, 12));
System.out.println("Converting to lower case: "+ targetString.toLowerCase());
System.out.println("Converting to upper case: "+ targetString.toUpperCase());
System.out.println("Triming string: " + s3.trim());
System.out.println("searching s1 in targetString: " + targetString.contains(s1));
System.out.println("searching s2 in targetString: " + targetString.contains(s2));
char [] charArray = s2.toCharArray();
System.out.println("Size of char array: " + charArray.length);
System.out.println("Printing last element of array: " + charArray[3]);
}
Void stringbuffer(){

StringBuffer s = new StringBuffer("Coding Atharva");

System.out.println("\n String = "+s); // Will Print the string

System.out.println("\n Length = "+s.length() ); // total numbers of characters

System.out.println("\n Length = "+s.capacity() ); // total allocated capacity

s.setLength(6); // Sets the length and destroy the remaining characters

System.out.println("\n After setting length String = "+s );

s.setCharAt(0,'K'); // It will change character at specified position

System.out.println("\n SetCharAt String = "+s );

s.setCharAt(0,'C');

int a = 007;

s.append(a); // It concatenates the other data type value

System.out.println("\n Appended String = "+s );

s.insert(6," Atharva"); // used to insert one string or char or object

System.out.println("\n Inserted String = "+s );

s.reverse();

System.out.println("\n Reverse String = "+s );

s.reverse();

s.delete(6,14); // used to delete sequence of character

System.out.println("\n\n After deleting string="+s);

}
}
Class Demo{
public static void main(String[] args) {
StringMethods s= new StringMethods();
s.stringclassmethods();
s.stringbuffer();
}
}

5. Write a JAVA Program to demonstrate Inheritance.


class Person {
String p;
Person(String p)
{
this.p=p;
}
void display()
{
System.out.println("Name: "+p+"\n");
}
}
class Employee extends Person{
double salary;
int year;
int insurance_number;
Employee(double salary,int year,int insurance_number,String p)
{
super(p);
this.salary=salary;
this.year=year;
this.insurance_number=insurance_number;
}
void display1()
{
System.out.println("Salary: "+salary+"\n");
System.out.println("Year:"+year+"\n");
System.out.println("Insurance Number:"+insurance_number+"\n");
}
}
public class InheritanceTest {

public static void main(String[] args) {


// TODO Auto-generated method stub
Employee emp = new Employee(250000,2013,20292,"Imran Gummanahalli");
emp.display();
emp.display1();
}
}

6. Simple Program on Java for the implementation of Multiple inheritance using


interfaces to calculate the area of a rectangle and triangle.
// InterfaceMain.java
interface rectangle
{
public void rectarea(float x, float y);
}
interface triangle
{
public void trianglearea(float x, float y);
}
class result implements rectangle,triangle
{
public void rectarea(float x, float y)
{
System.out.println (“Area of rectangle=” + x*y);
}
public void trianglearea(float x, float y)
{
System.out.println (“Area of rectangle=” + (x*y/2));
}
}
class InterfaceMain
{
public static void main(String args[])
{
result a= new result();
a.rectarea(10,20);
a.trianglearea(10,2);
}
}

7. Complete the following: a. Create a package named shape. b. Create some classes
in the package representing some common shapes like Square, Triangle, and Circle. c.
Import and compile these classes in other program.

/*Mainclass.java*/
import shape.Square;
import shape.Triangle;
import shape.Circle;
public class MainClass
{
public static void main(String args[])
{
Square square=new Square();
Triangle triangle=new Triangle();
Circle circle=new Circle();
square.getData((float)5.5);
System.out.println("The area of square is:"+square.area());
triangle.getData((double)20.56,(double)23.90);
System.out.println("The area of triangle is:"+triangle.area());
circle.getData((double)5.5);
System.out.println("The area of circle is:"+circle.area());
}
}

/*Square.java*/
package shape;
public class Square
{
float side;
public void getData(float temp)
{
side=temp;
}
public double area()
{
return (side*side);
}
}

/*Triangle.java*/
package shape;
public class Triangle
{
double base;
double height;
public void getData(double temp1,double temp2)
{
base=temp1;
height=temp2;
}
public double area()
{
return ((1.0/2.0)*(base*height));
}
}

/*Circle.java*/
package shape;
public class Circle
{
double radius;
double height;
public void getData(double temp)
{
radius=temp;
}
public double area()
{
return ((3.1427*(2.0*radius)*(2.0*radius))/4.00);
}
}

8. Write a JAVA program to implement user defined Exception Handling for withdrawal
process in a bank (also make use of throw, throws).
InSufficientFundException.java
This is Custom Exception class.In this class we have created two constructors for
displaying error message.

public class InSufficientFundException extends RuntimeException {

private String message;

public InSufficientFundException(String message) {

this.message = message;

public InSufficientFundException(Throwable cause, String message) {

super(cause);

this.message = message;

public String getMessage() {

return message;

}
}
Account.java
In this class we have created two methods withdraw and deposit.Initial Balance
of Account is 3000 dollars.Withdraw method parameter is amount and that
amount we are subtracting from initial balance. If amount passes is greater
than initial balance, it will throw Custom Exception
InSufficientFundException,else it will calculate new balance by subtracting
amount from initial balance.

public class Account {

private int balance = 3000;

public int balance() {

return balance;

public void withdraw(int amount) throws InSufficientFundException {

if (amount > balance) {

throw new InSufficientFundException(String.format(


"Current balance %d is less than requested
amount %d",balance, amount));

balance = balance - amount;

public void deposit(int amount) {

if (amount <= 0) {

throw new IllegalArgumentException(String.format(

"Invalid deposit amount %s", amount));

}
Test.java
Now create a test class to test our implemented Custom Exception Class.

public class Test {

public static void main(String args[]) {

Account acct = new Account();

System.out.println("Current balance : " +


acct.balance());

System.out.println("Withdrawing $200");

acct.withdraw(200);

System.out.println("Current balance : " +


acct.balance());

acct.withdraw(3500);

9. Write a Java program to demonstrate the implementation of multithreading.

class MyThread implements Runnable {


String name;
Thread t;
MyThread (String thread){
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}

class MultiThread {
public static void main(String args[]) {
new MyThread("One");
new MyThread("Two");
new NewThread("Three");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

10. Write a JAVA applet program which read 2 numbers and displaying their sum

11. Write a JAVA Program to create a simple calculator which performs a basic
mathematical operations using java swing.
import javax.swing.*;
import java.awt.event.*;

class Calc implements ActionListener


{
JFrame f;
JTextField t;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bdiv,bmul,bsub,badd,bdec,beq,bclr;

static double a=0,b=0,result=0;


static int operator=0;

Calc()
{
f=new JFrame("Calculator");
t=new JTextField();
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
b0=new JButton("0");
bdiv=new JButton("/");
bmul=new JButton("*");
bsub=new JButton("-");
badd=new JButton("+");
bdec=new JButton(".");
beq=new JButton("=");
bclr=new JButton("Clear");
t.setBounds(30,40,280,30);
b7.setBounds(40,100,50,40);
b8.setBounds(110,100,50,40);
b9.setBounds(180,100,50,40);
bdiv.setBounds(250,100,50,40);
b4.setBounds(40,170,50,40);
b5.setBounds(110,170,50,40);
b6.setBounds(180,170,50,40);
bmul.setBounds(250,170,50,40);
b1.setBounds(40,240,50,40);
b2.setBounds(110,240,50,40);
b3.setBounds(180,240,50,40);
bsub.setBounds(250,240,50,40);
bdec.setBounds(40,310,50,40);
b0.setBounds(110,310,50,40);
beq.setBounds(180,310,50,40);
badd.setBounds(250,310,50,40);
bclr.setBounds(180,380,100,40);
f.add(t);
f.add(b7);
f.add(b8);
f.add(b9);
f.add(bdiv);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(bmul);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(bsub);
f.add(bdec);
f.add(b0);
f.add(beq);
f.add(badd);
f.add(bclr);
f.setLayout(null);
f.setVisible(true);
f.setSize(350,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
badd.addActionListener(this);
bdiv.addActionListener(this);
bmul.addActionListener(this);
bsub.addActionListener(this);
bdec.addActionListener(this);
beq.addActionListener(this);
bclr.addActionListener(this);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==b1)
t.setText(t.getText().concat("1"));
if(e.getSource()==b2)
t.setText(t.getText().concat("2"));
if(e.getSource()==b3)
t.setText(t.getText().concat("3"));
if(e.getSource()==b4)
t.setText(t.getText().concat("4"));
if(e.getSource()==b5)
t.setText(t.getText().concat("5"));
if(e.getSource()==b6)
t.setText(t.getText().concat("6"));
if(e.getSource()==b7)
t.setText(t.getText().concat("7"));
if(e.getSource()==b8)
t.setText(t.getText().concat("8"));
if(e.getSource()==b9)
t.setText(t.getText().concat("9"));
if(e.getSource()==b0)
t.setText(t.getText().concat("0"));
if(e.getSource()==bdec)
t.setText(t.getText().concat("."));
if(e.getSource()==badd)
{
a=Double.parseDouble(t.getText());
operator=1;
t.setText("");
}
if(e.getSource()==bsub)
{
a=Double.parseDouble(t.getText());
operator=2;
t.setText("");
}
if(e.getSource()==bmul)
{
a=Double.parseDouble(t.getText());
operator=3;
t.setText("");
}
if(e.getSource()==bdiv)
{
a=Double.parseDouble(t.getText());
operator=4;
t.setText("");
}
if(e.getSource()==beq)
{
b=Double.parseDouble(t.getText());
switch(operator)
{
case 1: result=a+b;
break;
case 2: result=a-b;
break;
case 3: result=a*b;
break;
case 4: result=a/b;
break;
default: result=0;
}
t.setText(""+result);
}
if(e.getSource()==bclr)
t.setText("");
}

public static void main(String...s)


{
new Calc();
}
}

You might also like