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

CBCS5thSEMBCAJava Manual

The document appears to be a lab manual for a Java Programming course. It contains 10 programs to implement various Java concepts across two parts - Part A and Part B. The programs cover topics like finding factorials, checking prime numbers, sorting arrays, string operations, area calculations for shapes, classes and objects, threads, interfaces and exceptions. For each program, it lists the problem statement, sample source code and expected output. The manual provides students with examples of Java programs to complete their lab assignments.

Uploaded by

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

CBCS5thSEMBCAJava Manual

The document appears to be a lab manual for a Java Programming course. It contains 10 programs to implement various Java concepts across two parts - Part A and Part B. The programs cover topics like finding factorials, checking prime numbers, sorting arrays, string operations, area calculations for shapes, classes and objects, threads, interfaces and exceptions. For each program, it lists the problem statement, sample source code and expected output. The manual provides students with examples of Java programs to complete their lab assignments.

Uploaded by

Hari Krishna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

GOVERNMENT FIRST GRADE COLLEGE

VIJAYANAGARA
BENGALURU-560104

Department Of Computer Science & Applications

JAVA PROGRAMMING LAB

LAB MANUAL

For BCA V semester

2022-2023
INDEX
PAGE
S.NO PROGRAM NAME
NO.
PART-A
Write a program to find factorial of list of number reading input as
1 1
command line argument.
2 Write a program to display all prime numbers between two limits. 2
Write a program to sort list of elements in ascending and descending
3 3
order and show the exception handling.
4 Write a program to implement all string operations. 5

5 Write a program to find area of geometrical figures using method. 6


Write a program to implement constructor overloading by passing
6 8
different number of parameters of different types.
Write a program to create student report using applet, read the input
7 9
using text boxes and display the o/p using buttons.
Write a program to calculate bonus for different departments using
8 12
method overriding.
Write a program to implement thread, applets and graphics by
9 13
implementing animation of ball moving.
A) Write a program to implement keyboard events.
10 15
B) Write a program to implement mouse events.
PART B

1 Program to demonstrate the use of classes and objects 19

2 To sort names in alphabetical order 20

3 Program to check whether the number is palindrome or not 21


Write a program to implement Rhombus pattern reading the limit
4 22
form user.
5 Program to check number is even or odd 23
Write a program to implement the concept of threading by extending
6 24
Thread Class
7 Program to implement the concept of interfaces 25
Write a Java program to implement the concept of importing classes
8 26
from user defined package and creating packages
Write a program to implement the concept of Exception Handling
9 27
using predefined exception.
10 Program to draw Human face Using Applets 28
JAVA PROGRAMMING LAB MANUAL

PART - A

1. Write a program to find factorial of list of number reading input as command line
argument.
Source Code

public class Factorial


{
public static void main(String args[])
{
int[] arr = new int[10];
int fact;
if(args.length==0)
{
System.out.println("No Command line arguments");
return;
}
for (int i=0; i<args.length;i++)
{
arr[i]=Integer.parseInt(args[i]);
}
for(int i=0;i<args.length;i++)
{
fact=1;
while(arr[i]>0)
{
fact=fact*arr[i];
arr[i]--;
}
System.out.println("Factorial of "+ args[i]+"is : "+fact);
}
}
}

OUTPUT:

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 1


JAVA PROGRAMMING LAB MANUAL

2. Write a program to display all prime numbers between two limits.


Source Code

class Prime
{
public static void main(String args[])
{
int i,j;
if(args.length<2)
{
System.out.println("No command line Argruments ");
return;
}
int num1=Integer.parseInt(args[0]);
int num2=Integer.parseInt(args[1]);
System.out.println("Prime number between"+num1+"and" +num2+" are:");
for(i=num1;i<=num2;i++)
{
for(j=2;j<i;j++)
{
int n=i%j;
if(n==0)
{
break;
}
}
if(i==j)
{
System.out.println(" "+i);
}
}
}
}

OUTPUT:

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 2


JAVA PROGRAMMING LAB MANUAL

3. Write a program to sort list of elements in ascending and descending order and
show the exception handling.
class Sorting
{
public static void main(String args[])
{
int a[] = new int[5];
try
{
for(int i=0;i<5;i++)
a[i]=Integer.parseInt(args[i]);
System.out.println("Before Sorting\n");
for(int i=0;i<5;i++)
System.out.println(" " + a[i]);
bubbleSort(a,5);
System.out.println("\n\n After Sorting\n");
System.out.println("\n\nAscending order \n");
for(int i=0;i<5;i++)
System.out.print(" "+a[i]);
System.out.println("\n\nDescending order \n");
for(int i=4;i>=0;i--)
System.out.print(" "+a[i]);
}
catch(NumberFormatException e)
{
System.out.println("Enter only integers");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Enter only 5 integers");
}
}
private static void bubbleSort(int [] arr, int length)
{
int temp,i,j;
for(i=0;i<length-1;i++)
{
for(j=0;j<length-1-i;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
}

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 3


JAVA PROGRAMMING LAB MANUAL

OUTPUT:

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 4


JAVA PROGRAMMING LAB MANUAL

4. Write a program to implement all string operations.

Source code

class StringOperation
{
public static void main(String args[])
{
String s1="Hello";
String s2="World";
System.out.println("The strings are "+s1+"and"+s2);
int len1=s1.length();
int len2=s2.length();
System.out.println("The length of "+s1+" is :"+len1);
System.out.println("The length of "+s2+" is :"+len2);
System.out.println("The concatenation of two strings = "+s1.concat(s2));
System.out.println("First character of "+s1+"is="+s1.charAt(0));
System.out.println("The uppercase of "+s1+"is="+s1.toUpperCase());
System.out.println("The lower case of "+s2+"is="+s2.toLowerCase());
System.out.println(" the letter e occurs at position"+s1.indexOf("e")+"in"+s1);
System.out.println("Substring of "+s1+"starting from index 2 and ending at 4 is =
"+s1.substring(2,4));
System.out.println("Replacing 'e' with 'o' in "+s1+"is ="+s1.replace('e','o'));
boolean check = s1.equals(s2);
if(check==false)
System.out.println(""+s1+" and "+s2+" are not same");
else
System.out.println("" + s1+" and " + s2+"are same");
}
}

OUTPUT:

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 5


JAVA PROGRAMMING LAB MANUAL

5. Write a program to find area of geometrical figures using method.

Source code:
import java.io.*;
class Area
{
public static double circleArea(double r)
{
return Math.PI*r*r;
}
public static double squareArea(double side)
{
return side*side;
}
public static double rectArea(double width, double height)
{
return width*height;
}
public static double triArea(double base, double height1)
{
return 0.5*base*height1;
}
public static String readLine()
{
String input=" ";
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
try
{
input = in.readLine();
}
catch(Exception e)
{
System.out.println("Error" + e);
}
return input;
}
public static void main(String args[])
{
System.out.println("Enter the radius");
Double radius=Double.parseDouble(readLine());
System.out.println("Area of circle = " + circleArea(radius));
System.out.println("Enter the side");
Double side=Double.parseDouble(readLine());
System.out.println("Area of square = "+squareArea(side));
System.out.println("Enter the Width");
Double width=Double.parseDouble(readLine());
System.out.println("Enter the height");
Double height=Double.parseDouble(readLine());
System.out.println("Area of Rectangle = " + rectArea(width,height));
System.out.println("Enter the Base");

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 6


JAVA PROGRAMMING LAB MANUAL

Double base=Double.parseDouble(readLine());
System.out.println("Enter the Height");
Double height1=Double.parseDouble(readLine());
System.out.println("Area of traingle ="+triArea(base,height1));
}
}

OUTPUT:

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 7


JAVA PROGRAMMING LAB MANUAL

6. Write a program to implement constructor overloading by passing different


number of parameter of different types.
Source code
public class Box
{
int length,breadth,height;
Box()
{
length=breadth=height=2;
System.out.println("Intialized with default constructor");
}
Box(int l, int b)
{
length=l;
breadth=b;
height=2;
System.out.println("Initialized with parameterized constructor having 2 params");
}
Box(int l, int b, int h)
{
length=l;
breadth=b;
height=h;
System.out.println("Initialized with parameterized constructor having 3 params");
}
public int getVolume()
{
return length*breadth*height;
}
public static void main(String args[])
{
Box box1 = new Box();
System.out.println("The volume of Box 1 is :"+ box1.getVolume());
Box box2 = new Box(10,20);
System.out.println("Volume of Box 2 is :" + box2.getVolume());
Box box3 = new Box(10,20,30);
System.out.println("Volume of Box 3 is :" + box3.getVolume());
}
}

OUTPUT:

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 8


JAVA PROGRAMMING LAB MANUAL
7. Write a program to create student report using applet, read the input using text
boxes and display the o/p using buttons.
Source code
import java.applet.*;
import java.awt. *;
import java.awt.event.*;

/* <applet code="StudentReport.class",width=500 height=500>


</applet>*/
public class StudentReport extends Applet implements ActionListener
{
Label lblTitle, lblRegno, lblCourse, lblSemester, lblSub1, lblSub2;
TextFieldtxtRegno, txtCourse, txtSemester, txtSub1, txtSub2;
Button cmdReport;
String rno="", course="", sem="“, sub1="“, sub2="“, avg="“, heading="";
public void init()
{
GridBagLayoutgbag= new GridBagLayout();
GridBagConstraintsgbc = new GridBagConstraints();
setLayout(gbag);
lblTitle = new Label ("Enter Student Details");
lblRegno= new Label ("Register Number");
txtRegno=new TextField(25);
lblCourse=new Label ("Course Name");
txtCourse=new TextField(25);
lblSemester=new Label ("Semester ");
txtSemester=new TextField(25);
lblSub1=new Label ("Marks of Subject1");
txtSub1=new TextField(25);
lblSub2=new Label ("Marks of Subject2");
txtSub2=new TextField(25);
cmdReport = new Button ("View Report");
// Define the grid bag
gbc.weighty=2.0;
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbc.anchor=GridBagConstraints.NORTH;
gbag.setConstraints(lblTitle,gbc);
//Anchor most components to the right
gbc.anchor=GridBagConstraints.EAST;
gbc.gridwidth=GridBagConstraints.RELATIVE;
gbag.setConstraints(lblRegno,gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbag.setConstraints(txtRegno,gbc);
gbc.gridwidth=GridBagConstraints.RELATIVE;
gbag.setConstraints(lblCourse,gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbag.setConstraints(txtCourse,gbc);
gbc.gridwidth=GridBagConstraints.RELATIVE;
gbag.setConstraints(lblSemester,gbc);

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 9


JAVA PROGRAMMING LAB MANUAL
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbag.setConstraints(txtSemester,gbc);
gbc.gridwidth=GridBagConstraints.RELATIVE;
gbag.setConstraints(lblSub1,gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbag.setConstraints(txtSub1,gbc);
gbc.gridwidth=GridBagConstraints.RELATIVE;
gbag.setConstraints(lblSub2,gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbag.setConstraints(txtSub2,gbc);
gbc.anchor=GridBagConstraints.CENTER;
gbag.setConstraints(cmdReport,gbc);
add(lblTitle);
add(lblRegno);
add(txtRegno);
add(lblCourse);
add(txtCourse);
add(lblSemester);
add(txtSemester);
add(lblSub1);
add(txtSub1);
add(lblSub2);
add(txtSub2);
add(cmdReport);
cmdReport.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
try {
if(ae.getSource() == cmdReport)
{
rno=txtRegno.getText().trim();
course=txtCourse.getText().trim();
sem=txtSemester.getText().trim();
sub1=txtSub1.getText().trim();
sub2=txtSub2.getText().trim();
avg="Avg Marks:" + ((Integer.parseInt(sub1) + Integer.parseInt(sub2))/2);
rno="Register No:" + rno;
course="Course :"+ course;
sem="Semester :"+sem;
sub1="Subject1 :"+sub1;
sub2="Subject2 :"+sub2;
heading="Student Report";
removeAll();
showStatus("");
repaint();
}
}
catch(NumberFormatException e)
{

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 10


JAVA PROGRAMMING LAB MANUAL
showStatus("Invalid Data");
}

}
public void paint(Graphics g)
{
g.drawString(heading,30,30);
g.drawString(rno,30,80);
g.drawString(course,30,100);
g.drawString(sem,30,120);
g.drawString(sub1,30,140);
g.drawString(sub2,30,160);
g.drawString(avg,30,180);
}
}

Output:

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 11


JAVA PROGRAMMING LAB MANUAL

8. Write a program to calculate bonus for different departments using method


overriding.
Source code
abstract class Department
{
double salary,bonus,totalsalary;
public abstract void calBonus(double salary);
public void displayTotalSalary(String dept)
{
System.out.println(dept+"\t"+salary+"\t\t"+bonus+"\t"+totalsalary);
}
}
class Accounts extends Department
{
public void calBonus(double sal)
{
salary = sal;
bonus = sal * 0.2;
totalsalary=salary+bonus;
}
}
class Sales extends Department
{
public void calBonus(double sal)
{
salary = sal;
bonus = sal * 0.3;
totalsalary=salary+bonus;
}
}
public class BonusCalculate
{
public static void main(String args[])
{
Department acc = new Accounts();
Department sales = new Sales();
acc.calBonus(10000);
sales.calBonus(20000);
System.out.println("Department \t Basic Salary \t Bonus \t Total Salary");
System.out.println("-------------------------------------------------------------- ");
acc.displayTotalSalary("Accounts Dept");
sales.displayTotalSalary("Sales Dept");
System.out.println("--------------------------------------------------------------- ");
}
}

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 12


JAVA PROGRAMMING LAB MANUAL

OUTPUT:

9. Write a program to implement thread, applets and graphics by implementing


animation of ball moving.
Source code :
import java.awt.*;
import java.applet.*;
/* <applet code="MovingBall.class" height=300 width=300></applet> */
public class MovingBall extends Applet implements Runnable
{
int x,y,dx,dy,w,h;
Thread t;
boolean flag;
public void init()
{
w=getWidth();
h=getHeight();
setBackground(Color.yellow);
x=100;
y=10;
dx=10;
dy=10;
}
public void start()
{
flag=true;
t=new Thread(this);
t.start();
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(x,y,50,50);
}
public void run()
{
while(flag)
{
if((x+dx<=0)||(x+dx>=w))

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 13


JAVA PROGRAMMING LAB MANUAL
dx=-dx;
if((y+dy<=0)||(y+dy>=h))
dy=-dy;
x+=dx;
y+=dy;
repaint();
try
{
Thread.sleep(300);
}
catch(InterruptedException e)
{}
}
}
public void stop()
{
t=null;
flag=false;
}
}

Output:

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 14


JAVA PROGRAMMING LAB MANUAL

10.A) Write a program to implement keyboard events.

Source code
import java.awt. *;
import java.awt.event.*;
import java.applet.*;

/*<applet code="KeyBoardEvents" width=400 height=400></applet>*/

public class KeyBoardEvents extends Applet implements KeyListener


{
String str="";
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyTyped(KeyEvent e)
{
str+=e.getKeyChar();
repaint(0);
}
public void keyPressed(KeyEvent e)
{
showStatus("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
showStatus("Key Released");
}
public void paint(Graphics g)
{
g.drawString(str,15,15);
}
}

Output:

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 15


JAVA PROGRAMMING LAB MANUAL

10.B). Write a program to implement mouse events.


Source code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="Mouse" width=400 height=400></applet>*/

public class Mouse extends Applet implements MouseListener,MouseMotionListener


{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseEntered(MouseEvent m)
{
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)
{
showStatus("Mouse Pressed");

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 16


JAVA PROGRAMMING LAB MANUAL
repaint();
}
public void mouseReleased(MouseEvent m)
{
showStatus("Mouse Released");
repaint();
}
public void mouseMoved(MouseEvent m)
{
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
showStatus("Mouse Dragged");
repaint();
}
public void mouseClicked(MouseEvent m)
{
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}

Output:

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 17


JAVA PROGRAMMING LAB MANUAL

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 18


JAVA PROGRAMMING LAB MANUAL
PART-B

1.Program to demonstrate the use of classes and objects

import java.io.*;
import java.io.DataInputStream;

class Room
{
float length,breadth;
Room(int a,int b)
{
length=a; breadth =b;
}
Room(int a)
{
length =a; breadth=100;
}
float getdata()
{
return(length*breadth);
}
}

class Lab11
{
public static void main(String args[])
{
float area;
int l=0,b=0;
DataInputStream in=new DataInputStream(System.in);
try
{
System.out.println("\n enter the value for Room length:");
l=Integer.parseInt(in.readLine());
System.out.println("\n enter the value for Room breadth:");
b=Integer.parseInt(in.readLine());
}
catch(Exception e)
{
}
Room room1=new Room(l,b);
area=room1.getdata();
System.out.println("\n length="+room1.length);
System.out.println("\n breadth="+room1.breadth);
System.out.println("\n Area="+area);
System.out.println("\n passing only length of the room with breadth=100");
Room room2=new Room(l);
area =room2.getdata();
System.out.println("\n length="+room2.length);
System.out.println("\n breadth="+room2.breadth);

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 19


JAVA PROGRAMMING LAB MANUAL

System.out.println("\n Area="+area);
}
}

OUTPUT

2: To sort names in alphabetical order


import java.io.*;
import java.lang.*;
class Names
{
public static void main(String args[])throws IOException
{
String t;
int n=args.length;
int i,j;
System.out.println("\n you have entered"+n+"names to sort it in ascendingorder");
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(args[i].compareTo(args[j])>0)
{
t=args[i];
args[i]=args[j];
args[j]=t;

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 20


JAVA PROGRAMMING LAB MANUAL
}
System.out.println("\n sorted name list is…\n");
for (i=0;i<n;i++)
{
System.out.println(args[i]);
}
}
}

OUTPUT:

3. Program to check whether the number is palindrome or not*/

import java.io.*;
class palind
{
public static void main(String[] args) throws IOException
{
int n,m,r,s=0;
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
System.out.println("Enter the number");
n=Integer.parseInt(in.readLine());
m=n;
while(n!=0)
{
r=n%10;
s=s*10+r;
n=n/10;
}
if(s==m)
{
System.out.println("The given number is palindrome"+s);
}
else
System.out.println("the given number is not palindrome"+s);

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 21


JAVA PROGRAMMING LAB MANUAL
}
}

Output:
Enter the number
343
The given number is palindrome

4. Write a program to implement Rhombus pattern reading the limit form user.

Source code
import java.io.*;
public class RhombusPattern
{
public static void main(String args[]) throws IOException
{
int i,j,limit;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the limit");
limit=Integer.parseInt(br.readLine());

for(i=1;i<=limit;i++)
{
for(j=limit-i;j>0;j--)
System.out.print(" ");

for(j=1;j<=2*i-1;j++)
System.out.print("*");
System.out.println();
}

for(i=limit-1;i>=1;i--)
{
for(j=1;j<=limit-i;j++)
System.out.print(" ");
for(j=1;j<=2*i-1;j++)
System.out.print("*");
System.out.println();
}
}
}

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 22


JAVA PROGRAMMING LAB MANUAL

OUTPUT:

5. /* Program to check number is even or odd*/

import java.io.*;
class odd
{
public static void main(String[] args)throws IOException
{
int n;
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
System.out.println("Enter a number");
n=Integer.parseInt(in.readLine());
if(n%2==1)
System.out.println("Number is odd="+n);
else
System.out.println("Number is even="+n);
}}

Output:
Enter a number
7
Number is odd=7

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 23


JAVA PROGRAMMING LAB MANUAL
6. /*Write a program to implement the concept of threading 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();
}
}

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 24


JAVA PROGRAMMING LAB MANUAL

Output:
Thread A is started:
From thread A: i=1
From thread A: i=2
From thread A: i=3
From thread A: i=4
From thread A: i=5
Exit from thread A:

7. Program to implement the concept of interfaces

import java.io.*;
class Income
{
float iamount;

void get()throws IOException


{
DataInputStream d=new DataInputStream(System.in);
System.out.println("\n enter the income :");
iamount=Float.parseFloat(d.readLine());
}
}
interface Expenditure
{
public void get1();
}
class Netincome extends Income implements Expenditure
{
float eamount,namount;
public void get1()
{
try
{
DataInputStream d=new DataInputStream(System.in);
System.out.println("\n enter expenditure:");
eamount=Float.parseFloat(d.readLine());
}
catch(IOException e)
{}
}
void print()
{
System.out.println("\n income :" +iamount);
System.out.println("\n expenditure :" +eamount);
System.out.println("\n net income :" +(iamount-eamount));
}

class Intsample

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 25


JAVA PROGRAMMING LAB MANUAL
{
public static void main(String args[])throws IOException
{
Netincome n=new Netincome();
n.get();
n.get1();
n.print();
}
}

OUTPUT:

8. /*Write a Java program to implement the concept of importing classes from user
defined package and creating packages.*/

/*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
{

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 26


JAVA PROGRAMMING LAB MANUAL
public static void main(String arg[])
{
student s=new student();
s.getdata(123,"xyz");
s.putdata();
}
}

Output:
regno = 123
name = xyz

9. /*Write a program to implement the concept of Exception Handling using


predefined exception. */

import java.lang.*;
class Exception_handle
{
public static void main(String argv[])
{
int a=10,b=5,c=5,x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("DIVISION BY ZERO");
}
y=a/(b+c);
System.out.println("y="+y);
}
}

Output:

DIVISION BY ZERO
y=1

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 27


JAVA PROGRAMMING LAB MANUAL

10. Program to draw Human face Using Applets


/*<applet code="Shapes.java" width=300 height=300>
</applet>*/
import java.awt.*;
import java.applet.*;
public class Shapes extends Applet
{
public void paint(Graphics g)
{
g.drawOval(40,40,120,150);
g.drawOval(57,75,30,20);
g.drawOval(110,75,30,20);
g.fillOval(68,81,10,10);
g.fillOval(121,81,10,10);
g.fillArc(60,125,80,40,180,180);
g.drawOval(25,95,15,30);
g.drawOval(160,92,15,30);
}
}

OUTPUT:

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 28


JAVA PROGRAMMING LAB MANUAL

1. What do you mean by Object?


Object is a runtime entity and its state is stored in fields and behavior is shown via methods. Methods operate
on an object's internal state and serve as the primary mechanism for object-to object communication.
2. Define class?
A class is a blue print from which individual objects are created. A class can contain fields and methods to
describe the behavior of an object.
3. What kind of variables a class can consist of?
A class consist of Local variable, instance variables and class variables.
4. What is a Local Variable?
Variables defined inside methods, constructors or blocks are called local variables. The variable will be
declared and initialized within the method and it will be destroyed when the method has completed.
5. What is a Instance Variable?
Instance variables are variables within a class but outside any method. These variables are instantiated when
the class is loaded.
6. What is a Class Variable?
These are variables declared with in a class, outside any method, with the static keyword.
7. What is Singleton class?
Singleton class control object creation, limiting the number to one but allowing the flexibility to create more
objects if the situation changes.
8. What do you mean by Constructor?
Constructor gets invoked when a new object is created. Every class has a constructor. If we do not
explicitly write a constructor for a class the java compiler builds a default constructor for that class.
9. List the three steps for creating an Object for a class?
An Object is first declared, then instantiated and then it is initialized.
10. What is the default value of byte datatype in Java?
Default value of byte datatype is 0.
11. What is the default value of float and double datatype in Java?
Default value of float and double datatype in different as compared to C/C++. For float its 0.0f and for double
it’s 0.0d
12. When a byte datatype is used?
This data type is used to save space in large arrays, mainly in place of integers, since a byte is four times
smaller than an int.
13. What is a static variable?
Class variables also known as static variables are declared with the static keyword in a class, but outside a
method, constructor or a block.
14. What do you mean by Access Modifier?
Java provides access modifiers to set access levels for classes, variables, methods and constructors. A
member has package or default accessibility when no accessibility modifier is specified.
15. What is protected access modifier?
Variables, methods and constructors which are declared protected in a superclass can be accessed only by
the subclasses in other package or any class within the package of the protected members' class.
16. What do you mean by synchronized Non-Access Modifier?
Java provides these modifiers for providing functionalities other than Access Modifiers, synchronized used
to indicate that a method can be accessed by only one thread at a time.
17. According to Java Operator precedence, which operator is considered to be with highest
precedence?
Postfix operators i.e () [] . is at the highest precedence.
18. Variables used in a switch statement can be used with which datatypes?
Variables used in a switch statement can only be a string, enum, byte, short, int, or char.

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 29


JAVA PROGRAMMING LAB MANUAL

19. When parseInt() method can be used?


This method is used to get the primitive data type of a certain String.
20. Why is String class considered immutable?
The String class is immutable, so that once it is created a String object cannot be changed. Since String is
immutable it can safely be shared between many threads ,which is considered very important for
multithreaded programming.
21. Why is String Buffer called mutable?
The String class is considered as immutable, so that once it is created a String object cannot be changed. If
there is a necessity to make a lot of modifications to Strings of characters then String Buffer should be used.
22. What is the difference between StringBuffer and StringBuilder class?
Use StringBuilder whenever possible because it is faster than StringBuffer. But, if thread safety is necessary
then use StringBuffer objects.
23. Which package is used for pattern matching with regular expressions?
java.util.regex package is used for this purpose.
24. What is finalize() method?
It is possible to define a method that will be called just before an object's final destruction by the garbage
collector. This method is called finalize (), and it can be used to ensure that an object terminates cleanly.
25. What is an Exception?
An exception is a problem that arises during the execution of a program. Exceptions are caught by handlers
positioned along the thread's method invocation stack.
26. What do you mean by Checked Exceptions?
It is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For
example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot
simply be ignored at the time of compilation.
27. Explain Runtime Exceptions?
It is an exception that occurs that probably could have been avoided by the programmer. As opposed to
checked exceptions, runtime exceptions are ignored at the time of compilation.
28. Which are the two subclasses under Exception class?
The Exception class has two main subclasses : IOException class and RuntimeException Class.
29. When throws keyword is used?
If a method does not handle a checked exception, the method must declare it using the throws keyword. The
throws keyword appears at the end of a method's signature.
30. When throw keyword is used?
An exception can be thrown, either a newly instantiated one or an exception that you just caught, by using
throw keyword.
31. How finally used under Exception Handling?
The finally keyword is used to create a block of code that follows a try block.A finally block of code always
executes, whether or not an exception has occurred.
32. Define Inheritance?
It is the process where one object acquires the properties of another. With the use of inheritance, the
information is made manageable in a hierarchical order.
33. When super keyword is used?
If the method overrides one of its superclass's methods, overridden method can be invoked through the use
of the keyword super. It can be also used to refer to a hidden field.
34. What is Polymorphism?
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in
OOP occurs when a parent class reference is used to refer to a child class object.

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 30


JAVA PROGRAMMING LAB MANUAL

35. What is Abstraction?


It refers to the ability to make a class abstract in OOP. It helps to reduce the complexity and also improves
the maintainability of the system.
36. What is Abstract class?
These classes cannot be instantiated and are either partially implemented or not at all implemented. This
class contains one or more abstract methods which are simply method declarations without a body.
37. When Abstract methods are used?
If you want a class to contain a particular method but you want the actual implementation of that method to
be determined by child classes, you can declare the method in the parent class as abstract.
38. What is Encapsulation?
It is the technique of making the fields in a class private and providing access to the fields via public methods.
If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields
within the class. Therefore, encapsulation is also referred to as data hiding.
39. What is the primary benefit of Encapsulation?
The main benefit of encapsulation is the ability to modify our implemented code without breaking the code
of others who use our code. With this Encapsulation gives maintainability, flexibility and extensibility to our
code.
40. What is an Interface?
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the
abstract methods of the interface.
41. Give some features of Interface?
1.Interface cannot be instantiated 2. An interface does not contain any constructors.
3.All of the methods in an interface are abstract.
42. Define Packages in Java?
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations)
providing access protection and name space management.
43. Why Packages are used?
Packages are used in Java in-order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations, etc., easier.
44. What do you mean by Multithreaded program?
A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution.
45. What are the two ways in which Thread can be created?
Thread can be created by: implementing Runnable interface, extending the Thread class.
46. What is an applet?
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
47. An applet extend which class?
An applet extends java.applet.Applet class.
48. Explain garbage collection in Java?
It uses garbage collection to free the memory. By cleaning those objects that is no longer reference by any
of the program.
49. Explain the usage of this() with constructors?
It is used with variables or methods and used to call constructer of same class.
50. Difference between throw and throws?
It includes:
Throw is used to trigger an exception where as throws is used in declaration of exception.
Without throws, Checked exception cannot be handled where as checked exception can be
propagated with throws.

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 31


JAVA PROGRAMMING LAB MANUAL

51. Explain the following line used under Java Program −


public static void main (String args[ ])
The following shows the explanation individually −
public − it is the access specifier.
static − it allows main() to be called without instantiating a particular instance of a class.
void − it affirns the compiler that no value is returned by main().
main() − this method is called at the beginning of a Java program.
String args[ ] − args parameter is an instance array of class String
52.Define JRE i.e. Java Runtime Environment?
Java Runtime Environment is an implementation of the Java Virtual Machine which executes Java
programs. It provides the minimum requirements for executing a Java application;
53. What is JAR file?
JAR files is Java Archive fles and it aggregates many files into one. It holds Java classes in a library. JAR
files are built on ZIP file format and have .jar file extension.
54. Define JIT compiler?
It improves the runtime performance of computer programs based on bytecode.
55. What is the difference between object oriented programming language and object based
programming language?
Object based programming languages follow all the features of OOPs except Inheritance. JavaScript is an
example of object based programming languages.
56. What is the purpose of default constructor?
The java compiler creates a default constructor only if there is no constructor in the class.
57. What is function overloading?
If a class has multiple functions by same name but different parameters, it is known as Method
Overloading.
58. What is function overriding?
If a subclass provides a specific implementation of a method that is already provided by its parent class, it
is known as Method Overriding.
59. Difference between Overloading and Overriding?
Method overloading increases the readability of the program. Method overriding provides the specific
implementation of the method that is already provided by its super class parameter must be different in case
of overloading, parameter must be same in case of overriding.
60. What is final class?
Final classes are created so the methods implemented by that class cannot be overridden. It can’t be
inherited.
61. What is NullPointerException?
A NullPointerException is thrown when calling the instance method of a null object, accessing or
modifying the field of a null object etc.
62. What are Wrapper classes?
These are classes that allow primitive types to be accessed as objects. Example: Integer, Character, Double,
Boolean etc.
63. What is the difference between a Window and a Frame?
The Frame class extends Window to define a main application window that can have a menu bar.
64. Which package has light weight components?
javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are
lightweight components.
65. What is the difference between the paint() and repaint() methods?
The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to
be invoked by the AWT painting thread.

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 32


JAVA PROGRAMMING LAB MANUAL

66. Which class should you use to obtain design information about an object?
The Class class is used to obtain information about an object's design and java.lang.Class class instance
represent classes, interfaces in a running Java application.
67. What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-
static variables take on unique values with each object instance.
68. What is Serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream. Deserialization is the
process of restoring these objects.
69. What's the difference between constructors and other methods?
Constructors must have the same name as the class and can not return a value. They are only called once
while regular methods could be called many times.
70. What's the difference between the methods sleep() and wait()?
The code sleep(2000); puts thread aside for exactly two seconds. The code wait(2000), causes a wait of up
to two second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method
wait() is defined in the class Object and the method sleep() is defined in the class
Thread.
71. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of
objects.
72. Which class is the immediate superclass of the Container class?
Component class is the immediate super class.
73. What is the difference between an Interface and an Abstract class?
An abstract class can have instance methods that implement a default behavior. An Interface can
only declare constants and instance methods, but cannot implement default behavior and all
methods are implicitly abstract. An interface has all public members and no implementation.
What will happen if static modifier is removed from the signature of the main method?
Program throws "NoSuchMethodError" error at runtime.
74. What is the difference between error and an exception?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. Exceptions are
conditions that occur because of bad input etc. e.g., FileNotFoundException will be thrown if the specified
file does not exist.
75. What is Dynamic Binding (late binding)?
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding means that the code associated with a given procedure call is not known until the time of
the call at run-time.
76. What is type casting?
Type casting means treating a variable of one type as though it is another type.
77. Where import statement is used in a Java program?
Import statement is allowed at the beginning of the program file after package statement.
78. Life cycle of an applet includes which steps?
Life cycle involves the following steps −
Initialization
Starting
Stopping
Destroying
Painting
79. Why is the role of init() method under applets?
It initializes the applet and is the first method to be called.

GOVT. FIRST GRADE COLLEGE, VIJAYANAGARA Page | 33

You might also like