0% found this document useful (0 votes)
11 views36 pages

Java Lab Cbcs

Uploaded by

gayathrinaik12
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)
11 views36 pages

Java Lab Cbcs

Uploaded by

gayathrinaik12
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
You are on page 1/ 36

1.

Write a Java program that creates an object and initializes its data
members using constructor. Use constructor overloading concept.

import java.lang.*;
class student
{
String name;
int regno;
int marks1,marks2,marks3;

student()
{
name="raju";
regno=12345;
marks1=56;
marks2=47;
marks3=78;
}

student(String n,int r,int m1,int m2,int m3)


{
name=n;
regno=r;
marks1=m1;
marks2=m2;
marks3=m3;
}

student(student s)
{
name=s.name;
regno=s.regno;
marks1=s.marks1;
marks2=s.marks2;
marks3=s.marks3;
}
void display()
{
System.out.println(name + "\t" +regno+ "\t"
+marks1+ "\t" +marks2+ "\t" + marks3);
}
}
class studentdemo
{
public static void main(String arg[])
{
student s1=new student();
student s2=new student("john",34266,58,96,84);
student s3=new student(s1);
s1.display();
s2.display();
s3.display();
}
}

************************OUTPUT****************************
2. Write your own simple Account class. You should be able to make
deposits and withdrawals and read out the balance — a private
double variable. Member functions should be: void
Account::withdraw (const double &amount); //Take from account
void Account::deposit(const double &amount); // Put into account
double account::balance(void); //Return the balance Make sure that
the Account constructor function initializes the balance to zero. If you
like, add an overloaded constructor function to set an initial balance.
class BankAccount
{
private String accountNum;
private double balance;

public BankAccount(String acctNum, double initialBalance)


{
accountNum = acctNum;
balance = initialBalance;
}

public void deposit(double amount)


{
double newBalance = balance + amount;
balance = newBalance;
}

public void withdraw(double amount)


{
double newBalance = balance - amount;
balance = newBalance;
}

public String getAccount()


{
return accountNum;
}

public double getBalance()


{
return balance;
}

public void transferFundsA(BankAccount destination,


double amount)
{
destination.balance = destination.balance + amount;
this.balance = this.balance - amount;
}

public void transferFundsB(BankAccount destination,


double amount)
{
destination.deposit(amount);
this.withdraw(amount);
}
}

public class BankAccountTest2


{
public static void main(String[] args)
{
BankAccount first = new BankAccount("1111111", 20000);
BankAccount second = new BankAccount("2222222",
30000);
System.out.printf("Account #%s has initial balance of
$%.2f%n",
first.getAccount(), first.getBalance());
System.out.printf("Account #%s has initial balance of
$%.2f%n",
second.getAccount(), second.getBalance());

first.transferFundsA(second, 5000);

System.out.println("\nAfter \"first.transferFunds(second,
5000)\" ...");
System.out.printf("Account #%s has new balance of
$%.2f%n",
first.getAccount(), first.getBalance());
System.out.printf("Account #%s has new balance of
$%.2f%n",
second.getAccount(), second.getBalance());
second.transferFundsB(first, 10000);
System.out.println("\nAfter \"second.transferFunds(first,
10000)\" ...");
System.out.printf("Account #%s has new balance of
$%.2f%n",
first.getAccount(), first.getBalance());
System.out.printf("Account #%s has new balance of
$%.2f%n",
second.getAccount(), second.getBalance());
}
}

***************************OUTPUT*****************************
3. Write a java program to calculate gross salary & net salary taking the
following data. Input: empno, empname, basic Process: DA=50%of
basic HRA=12%of basic CCA=Rs240/- PF=10%of basic PT=Rs100/-
import java.util.*;
class Employee
{
public static void main(String []args)
{
float DA, HRA, PF, grass_sal, net_sal;
float CCA=240f, PT=100f;
Scanner sc= new Scanner(System.in);

System.out.print("Enter Employee Name : ");


String name=sc.nextLine();
System.out.print("Enter Employee Number: ");
int number=sc.nextInt();
System.out.print("Enter Employee Basic Salary : ");
float basic_sal=sc.nextFloat();

DA = (0.5f)* basic_sal;
HRA = (0.12f)*basic_sal;
PF = (0.1f)*basic_sal;
grass_sal=(basic_sal + DA + HRA);
net_sal=(grass_sal - CCA - PT - PF);
System.out.println("Employee Gross Salary : " +grass_sal);
System.out.println("Employee Net Salary : " +net_sal);
}
}

****************************OUTPUT****************************
4. Write a Java program to sort the elements using bubble sort.

import java.util.Scanner;
class BubbleSort
{
public static void main(String args[])
{
int n, i, j, temp;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);

System.out.print("Enter Total Number of Elements : ");


n = scan.nextInt();

System.out.print("Enter " +n+ " Numbers : ");


for(i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}
System.out.print("Sorting Array using Bubble Sort
Technique...\n\n");
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.print("Array Sorted Successfully..!!\n\n");
System.out.print("Sorted List in Ascending Order : \n");
for(i=0; i<n; i++)
{
System.out.print(arr[i]+ " ");
}
}
}

****************************OUTPUT****************************
5. Write a Java program to search an element using binary search.
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int n, i, search, first, last, middle;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);

System.out.print("Enter Total Number of Elements : ");


n = scan.nextInt();

System.out.print("Enter " +n+ " Elements : ");


for(i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}

System.out.print("Enter a Number to Search..");


search = scan.nextInt();

first = 0;
last = n-1;
middle = (first+last)/2;

while(first <= last)


{
if(arr[middle] < search)
{
first = middle+1;
}
else if(arr[middle] == search)
{
System.out.print(search+ " Found at Location "
+middle);
break;
}
else
{
last = middle - 1;
}
middle = (first+last)/2;
}
if(first > last)
{
System.out.print("Not Found..!! " +search+ " is not
Present in the List.");
}
}
}

****************************OUTPUT****************************
6. Write a Java program that counts the number of objects created by
using static variable.
class CountObject
{
private static int count;
public CountObject()
{
count++;
}
public static void main(String args[])
{
CountObject ob1 = new CountObject();
CountObject ob2 = new CountObject();
CountObject ob3 = new CountObject();
CountObject ob4 = new CountObject();
CountObject ob5 = new CountObject();
System.out.print("Total Number of Objects: " +
CountObject.count);
}
}

****************************OUTPUT****************************
7. Write a Java program to count the frequency of words, characters in
the given line of text.
import java.util.Scanner;
class Frequency_of_Characters_in_String
{
public static void main(String args[])
{
String str;
Scanner scan = new Scanner(System.in);

System.out.print("Enter a String : ");


str=scan.nextLine();

System.out.print("Total Number of Words in Entered Sentence is


" + countWords(str)+"\n\n");

System.out.print("Total Number of Characters in Entered


Sentence is " + countCharacter(str));
}

public static int countCharacter(String str)


{
int i, j, k, count=0;
char c, ch;
i=str.length();
for(c='A'; c<='z'; c++)
{
k=0;
for(j=0; j<i; j++)
{
ch = str.charAt(j);
if(ch == c)
{
k++;
count++;
}
}
if(k>0)
{
System.out.println("The character " + c + " has occurred for
" + k + " times");
}
}
return count;
}

public static int countWords(String str)


{
int count = 1;
for(int i=0; i<=str.length()-1; i++)
{
if(str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
{
count++;
}
}
return count;
}
}

****************************OUTPUT****************************
8. Write a java program to identify the significance of finally block in
handling exceptions.
class TestFinallyBlock1
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

****************************OUTPUT****************************
9. Write a java program to access member variables of classes defined in
user created package.

/*Source code of package p1 under the directory C:\jdk1.6.0_26\bin>p1\edit


Student.java */
package p1;
public class Student
{
int regno;
String name;
public void getdata(int r,String s)
{
regno=r;
name=s;
}
public void putdata()
{
System.out.println("regno = " +regno);
System.out.println("name = " + name);
}
}

/* Source code of the main function under C:\jdk1.6.0_26\bin>edit StudentTest.java */


import p1.*;
class StudentTest
{
public static void main(String arg[])
{
student s=new student();
s.getdata(123,"xyz");
s.putdata();
}
}

*******************************OUTPUT**************************
C:\jdk1.6.0_26\bin>javac p1\Student.java
C:\jdk1.6.0_26\bin>javac StudentTest.java
C:\jdk1.6.0_26\bin>java StudentTest
regno = 123
name = xyz
10. Write a Java Program to implement multilevel inheritance by
applying various access controls to its data members and methods.

import java.io.DataInputStream;
class Student
{
private int rollno;
private String name;
DataInputStream dis=new DataInputStream(System.in);
public void getrollno()
{
try
{
System.out.println("Enter rollno ");
rollno=Integer.parseInt(dis.readLine());
System.out.println("Enter name ");
name=dis.readLine();
}
catch(Exception e){ }
}

void putrollno()
{
System.out.println("Roll No ="+rollno);
System.out.println("Name ="+name);
}
}

class Marks extends Student


{
protected int m1,m2,m3;
void getmarks()
{
try
{
System.out.println("Enter marks :");
m1=Integer.parseInt(dis.readLine());
m2=Integer.parseInt(dis.readLine());
m3=Integer.parseInt(dis.readLine());
}
catch(Exception e) { }
}

void putmarks()
{
System.out.println("m1="+m1);
System.out.println("m2="+m2);
System.out.println("m3="+m3);
}
}

class Result extends Marks


{
private float total;
void compute_display()
{
total=m1+m2+m3;
System.out.println("Total marks :" +total);
}
}

class MultilevelDemo
{
public static void main(String arg[])
{
Result r=new Result();
r.getrollno();
r.getmarks();
r.putrollno();
r.putmarks();
r.compute_display();
}
}
**************************OUTPUT*******************************
11. Write a Java Program to implement Vector class and its methods.
import java.lang.*;
import java.util.Vector;
import java.util.Enumeration;
class vectordemo
{
public static void main(String arg[])
{
Vector v=new Vector();
v.addElement("one");
v.addElement("two");
v.addElement("three");
v.insertElementAt("zero",0);
v.insertElementAt("oops",3);
v.insertElementAt("four",5);
System.out.println("Vector Size :"+v.size());
System.out.println("Vector apacity :"+v.capacity());
System.out.println(" The elements of a vector are :");
Enumeration e=v.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement() +" ");
System.out.println();
System.out.println("The first element is : " +v.firstElement());
System.out.println("The last element is : " +v.lastElement());
System.out.println("The object oops is found at position :
"+v.indexOf("oops"));
v.removeElement("oops");
v.removeElementAt(1);
System.out.println("After removing 2 elements ");
System.out.println("Vector Size :"+v.size());
System.out.println("The elements of vector are :");
for(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i)+" ");
}
}
**************************OUTPUT******************************
12. Write a program to demonstrate use of user defined packages.

Package is a keyword of Java followed by the package name. Just


writing the package statement followed by the name creates a new
package; see how simple Java is to practice. For this reason, Java is
known as a production language.

While create User Defined Packages Java, the order of statements is


very important. The order must be like this, else, compilation error.
1. Package statement
2. Import statement
3. Class declaration
package forest;
import java.util.*;
public class Tiger
{
public void getDetails(String nickName, int weight)
{
System.out.println("Tiger nick name is " + nickName);
System.out.println("Tiger weight is " + weight);
}
}

When the code is ready, the next job is compilation. We must compile
with package notation. Package notation uses –d compiler option as
follows.
C:\snr > javac -d . Tiger.java

The –d compiler option creates a new folder called forest and places
the Tiger.class in it. The dot (.) is an operating system's environment
variable that indicates the current directory. It is an instruction to the
OS to create a directory called forest and place the Tiger.class in it.

Using User Defined Packages Java


After creating the package let us use it.

2nd step: Set the classpath from the target directory.


Let us assume D:\sumathi is the target directory. Let us access
Tiger.class in forest package from here.
From the target directory set the classpath following way.
D:\vinay> set classpath=C:\snr;%classpath%;

classpath is another environment variable which gives the address of


the forest directory to the OS. %classpath% informs the OS to append
the already existing classpath to the current classpath that is right
now set.

3rd Step: Now finally, write a program from the target directory
D:\vinay and access the package.
D:\vinay> notepad Animal.java
import forest.Tiger;
public class Animal
{
public static void main(String args[])
{
Tiger t1 = new Tiger ();
t1.getDetails("Everest", 50);
}
}

The compilation and execution is as usual as follows.


D:\vinay>javac Animal.java
D:\vinay> java Animal
13. Write a java program to implement exception handling using multiple
catch statements.
class MultipleCatchBlock1
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception
occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exc
eption occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

****************************OUTPUT****************************
14. Design stack and queue classes with necessary exception handling.
import java.util.*;

/* Class arrayStack */

class arrayStack
{
protected int arr[];
protected int top, size, len;

/* Constructor for arrayStack */


public arrayStack(int n)
{
size = n;
len = 0;
arr = new int[size];
top = -1;
}

/* Function to check if stack is empty */


public boolean isEmpty()
{
return top == -1;
}

/* Function to check if stack is full */


public boolean isFull()
{
return top == size -1 ;
}

/* Function to get the size of the stack */


public int getSize()
{
return len ;
}

/* Function to check the top element of the stack */


public int peek()
{
if( isEmpty() )
throw new NoSuchElementException("Underflow
Exception");
return arr[top];
}

/* Function to add an element to the stack */


public void push(int i)
{
if(top + 1 >= size)
throw new IndexOutOfBoundsException("Overflow
Exception");
if(top + 1 < size )
arr[++top] = i;
len++ ;
}

/* Function to delete an element from the stack */


public int pop()
{
if( isEmpty() )
throw new NoSuchElementException("Underflow
Exception");
len-- ;
return arr[top--];
}

/* Function to display the status of the stack */


public void display()
{
System.out.print("\nStack = ");
if (len == 0)
{
System.out.print("Empty\n");
return ;
}
for (int i = top; i >= 0; i--)
System.out.print(arr[i]+" ");
System.out.println();
}
}

/* Class StackImplement */
public class StackImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Stack Test\n");
System.out.println("Enter Size of Integer Stack ");
int n = scan.nextInt();

/* Creating object of class arrayStack */


arrayStack stk = new arrayStack(n);

/* Perform Stack Operations */


char ch;
do
{
System.out.println("\nStack Operations");
System.out.println("1. push");
System.out.println("2. pop");
System.out.println("3. peek");
System.out.println("4. check empty");
System.out.println("5. check full");
System.out.println("6. size");
int choice = scan.nextInt();
switch (choice)
{
case 1 : System.out.println("Enter integer
element to push");
try
{
stk.push( scan.nextInt() );
}
catch (Exception e)
{
System.out.println("Error : " +
e.getMessage());
}
break;

case 2 :
try
{
System.out.println("Popped Element = " +
stk.pop());
}
catch (Exception e)
{
System.out.println("Error : " +
e.getMessage());
}
break;

case 3 :
try
{
System.out.println("Peek Element = " +
stk.peek());
}
catch (Exception e)
{
System.out.println("Error : " +
e.getMessage());
}
break;

case 4 :
System.out.println("Empty status = " +
stk.isEmpty());
break;

case 5 :
System.out.println("Full status = " +
stk.isFull());
break;

case 6 :
System.out.println("Size = " +
stk.getSize());
break;

default :
System.out.println("Wrong Entry \n ");
break;
}

/* display stack */
stk.display();
System.out.println("\nDo you want to continue (Type y
or n) \n");
ch = scan.next().charAt(0);
}
while (ch == 'Y'|| ch == 'y');
}
}

****************************OUTPUT****************************

Stack Test

Enter Size of Integer Stack


5

Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size

4
Empty status = true
Stack = Empty

Do you want to continue (Type y or n)


y

Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size

1
Enter integer element to push
24

Stack = 24

Do you want to continue (Type y or n)


y

Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size

1
Enter integer element to push
6

Stack = 6 24

Do you want to continue (Type y or n)


y
15. Write a Java program to illustrate AWT controls frame, panel, layout
manager, command button and text boxes.
import java.awt.*;
class AWTExample extends Frame
{
AWTExample()
{
Button b = new Button("Click Me!!");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setTitle("This is our basic AWT example");
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
AWTExample f = new AWTExample();
}
}

****************************OUTPUT****************************
16. Write a Java program to illustrate basic calculator using grid layout
manager.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="Calculator1" width=300 height=300></applet>*/

public class Calculator1 extends Applet implements ActionListener


{
TextField t;
Button b[]=new Button[15];
Button b1[]=new Button[6];
String op2[]={"+","-","*","%","=","C"};
String str1="";
int p=0,q=0;
String oper;
public void init()
{
setLayout(new GridLayout(5,4));
t=new TextField(20);
setBackground(Color.pink);
setFont(new Font("Arial",Font.BOLD,20));
int k=0;
t.setEditable(false);
t.setBackground(Color.white);
t.setText("0");
for(int i=0;i<10;i++)
{
b[i]=new Button(""+k);
add(b[i]);
k++;
b[i].setBackground(Color.pink);
b[i].addActionListener(this);
}

for(int i=0;i<6;i++)
{
b1[i]=new Button(""+op2[i]);
add(b1[i]);
b1[i].setBackground(Color.pink);
b1[i].addActionListener(this);
}
add(t);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("+"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("-"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("*"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("%"))
{
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("="))
{
str1="";
if(oper.equals("+"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p+q)));
}
else if(oper.equals("-"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p-q)));
}
else if(oper.equals("*"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p*q)));
}
else if(oper.equals("%"))
{
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p%q)));
}
}
else if(str.equals("C"))
{
p=0;q=0;
t.setText("");
str1="";
t.setText("0");
}
else
{
t.setText(str1.concat(str));
str1=t.getText();
}
}
}
****************************OUTPUT****************************
17. Illustrate creation of thread by extending Thread class.
import java.lang.Thread;
class A extends Thread
{
public void run()
{
System.out.println("thread A is started:");
for(int i=1;i<=5;i++)
{
System.out.println("\t from thread A:i="+i);
}
System.out.println("exit from thread A:");
}
}

class B extends Thread


{
public void run()
{
System.out.println("thread B is started:");
for(int j=1;j<=5;j++)
{
System.out.println("\t from thread B:j="+j);
}
System.out.println("exit from thread B:");
}
}

class C extends Thread


{
public void run()
{
System.out.println("thread C is started:");
for(int k=1;k<=5;k++)
{
System.out.println("\t from thread C:k="+k);
}
System.out.println("exit from thread C:");
}
}

class Threadtest
{
public static void main(String arg[])
{
new A().start();
new B().start();
new C().start();
}
}

****************************OUTPUT****************************
18. Illustrate thread creation by implementing runnable interface.

import java.lang.Runnable;
class X implements Runnable
{
public void run()
{
for(int i=1;i<10;i++)
{
System.out.println("\t Thread X:"+i);
}
System.out.println("End of Thread X");
}
}

class Runnabletest
{
public static void main(String arg[])
{
X R=new X();
Thread T=new Thread(R);
T.start();
}
}
****************************OUTPUT****************************

You might also like