Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
52 views

Java Lab Programs

Best Java language programs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Java Lab Programs

Best Java language programs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Java Lab Manual Nandini S R

1. Create a class called lamp it contains a variable is on and two methods


turn on() and turn off () with an associated object.
public class Lamp
{
booleanisOn;
void turnOn()
{
isOn=true;
System.out.println("Light on?" +isOn);
}
void turnOff()
{
isOn=false;
System.out.println("Light off? " +isOn);
}

public static void main(String[] args) {


// TODO Auto-generated method stub
Lamp led=new Lamp();
led.turnOn();
led.turnOff();
}

}
Output
Light on?true
Light off? false

Dept. of CSE, BGSIT, BG Nagar 1


Java Lab Manual Nandini S R

2. Write a java program for sorting a given list of names in ascending


order.
class Alphabetical_order

public static void main(String[] args)

// storing input in variable

int n = 4;

// create string array called names

String names[] = { "Rahul", "Ajay", "Gourav", "Riya" };

String temp;

for (int i = 0; i< n; i++) {

for (int j = i + 1; j < n; j++) {

// to compare one string with other strings

if (names[i].compareTo(names[j]) > 0) {

// swapping

temp = names[i];

names[i] = names[j];

names[j] = temp;

// print output array

System.out.println("The names in alphabetical order are: ");

for (int i = 0; i< n; i++) {

System.out.println(names[i]);

Dept. of CSE, BGSIT, BG Nagar 2


Java Lab Manual Nandini S R

OR
import java.io.*;
import java.util.*;
class Alphabetical_order {
public static void main(String[] args)
{
// storing input in variable
int n = 4;
// create string array called names
String names[] = { "Rahul", "Ajay", "Gourav", "Riya" };
// inbuilt sort function
Arrays.sort(names);
// print output array
System.out.println( "The names in alphabetical order are: ");
for (int i = 0; i< n; i++) {
System.out.println(names[i]);
}
}
}
Output
The names in alphabetical order are:
Ajay
Gourav
Rahul
Riya

Dept. of CSE, BGSIT, BG Nagar 3


Java Lab Manual Nandini S R

3. Write a java program for Method overloading and Constructor


overloading.
import java.io.*;
class MethodOverloadingEx
{

static int add(int a, int b)


{
return a + b;
}

static int add(int a, int b, int c)


{
return a + b + c;
}

public static void main(String args[])


{
System.out.println("add() with 2 parameters");

System.out.println(add(4, 6));
System.out.println("add() with 3 parameters");
System.out.println(add(4, 6, 7));
}
}

Output:

Dept. of CSE, BGSIT, BG Nagar 4


Java Lab Manual Nandini S R

4.Create a class called Bank and calculate the rate of interest for different
banks using method overriding and inheritance.
class Bank
{
int getRateOfInterest()
{
return 0;
}
}

class SBI extends Bank


{
int getRateOfInterest()
{
return 5;
}
}

class ICICI extends Bank


{
int getRateOfInterest()
{
return 6;
}
}

class AXIS extends Bank


{
int getRateOfInterest()

Dept. of CSE, BGSIT, BG Nagar 5


Java Lab Manual Nandini S R

{
return 7;
}
}
class DisplayResult
{
public static void main(String args[])
{
SBI s = new SBI();
ICICI i = new ICICI();
AXIS a = new AXIS();
System.out.println("Rate of Interest in SBI is "+s.getRateOfInterest()+"%");
System.out.println("Rate of Interest in ICICI is "+i.getRateOfInterest()+"%");
System.out.println("Rate of Interest in AXIS is "+a.getRateOfInterest()+"%");
}
}
Output
Rate of Interest in SBI is 5%
Rate of Interest in ICICI is 6%
Rate of Interest in AXIS is 7%

Dept. of CSE, BGSIT, BG Nagar 6


Java Lab Manual Nandini S R

5.Write a java program to create an abstract class named Shape that


contains two integers and an empty method named print Area (). Provide
three classes named Rectangle, Triangle and Circle such that each one of
the classes extends the class Shape. Each one of the classes contain only the
method print Area() that prints the area of the given shape.
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of triangle is :"+(0.5*x*y));
}
}
public class AbstactDDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.area(2,5);
Circle c=new Circle();
c.area(5,5);
Triangle t=new Triangle();
t.area(2,5);
}
}

Dept. of CSE, BGSIT, BG Nagar 7


Java Lab Manual Nandini S R

Output

Area of rectangle is :10.0


Area of circle is :78.5
Area of triangle is :5.0

Dept. of CSE, BGSIT, BG Nagar 8


Java Lab Manual Nandini S R

6. Write a java program to create user defined packages.


A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
B.java
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

Output

Dept. of CSE, BGSIT, BG Nagar 9


Java Lab Manual Nandini S R

7. Write a java program to calculate the salary of employee using interface.


interface SalaryCalculator
{
double calculateSalary();
}

// Implementation class for SalaryCalculator


class Employee implements SalaryCalculator
{
private double basicSalary;
private double allowances;
// Constructor
public Employee(double basicSalary, double allowances)
{
this.basicSalary = basicSalary;
this.allowances = allowances;
}
// Method to calculate salary @Override
public double calculateSalary() {
return basicSalary + allowances;
}
}
// Main class to test the program
public class Main {
public static void main(String[] args) {
double basicSalary = 50000; // Example basic salary
double allowances = 10000; // Example allowances

// Creating an Employee object

Dept. of CSE, BGSIT, BG Nagar 10


Java Lab Manual Nandini S R

Employee emp = new Employee(basicSalary, allowances);

// Calculating and printing the salary


System.out.println("Employee Salary: $" + emp.calculateSalary());
}
}
Output

Dept. of CSE, BGSIT, BG Nagar 11


Java Lab Manual Nandini S R

8.WAP to handle the Exception using try and multiple catch block.

public class MultipleCatchBlocks


{
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 Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Dept. of CSE, BGSIT, BG Nagar 12


Java Lab Manual Nandini S R

9.Develop an Applet that receives an integer in one text field & compute its
factorial value & returns it in another text field when button “compute” is
clicked.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="FactorialApplet" width=500 height=250>
</applet>*/
public class FactorialApplet extends Applet implements ActionListener {
Label L1,L2;
TextField T1,T2;
Button B1;
public void init() {
L1=new Label("Enter any Number : ");
add(L1);
T1=new TextField(10);
add(T1);
L2=new Label("Factorial of Num : ");
add(L2);
T2=new TextField(10);
add(T2);
B1=new Button("Compute");
add(B1);
B1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==B1)
{
int value=Integer.parseInt(T1.getText());
int fact=factorial(value);
T2.setText(String.valueOf(fact));
}
}

Dept. of CSE, BGSIT, BG Nagar 13


Java Lab Manual Nandini S R

int factorial(int n) {
if(n==0)
return 1;
else
return n*factorial(n-1);
}
}

Output

Dept. of CSE, BGSIT, BG Nagar 14


Java Lab Manual Nandini S R

10. Create a Layout using applets to arrange Buttons for digits and for the
+ - * % operations. Add a text field to display the result.

/* Program to create a Simple Calculator */


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="MyCalculator" width=300 height=300>
</applet>
*/
public class MyCalculator extends Applet implements ActionListener {
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init() {
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++) {
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");

Dept. of CSE, BGSIT, BG Nagar 15


Java Lab Manual Nandini S R

clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
for(int i=0;i<10;i++) {
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++) {
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+")){
num1=Integer.parseInt (T1.getText());
Operation='+';

Dept. of CSE, BGSIT, BG Nagar 16


Java Lab Manual Nandini S R

T1.setText ("");
}
if(str.equals("-")){
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*")){
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/")){
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
}
if(str.equals("%")){
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("=")) {
num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e) {
result=num2;
JOptionPane.showMessageDialog(this,"Divided by zero");

Dept. of CSE, BGSIT, BG Nagar 17


Java Lab Manual Nandini S R

}
break;
}
T1.setText(""+result);
}
if(str.equals("clear")) {
T1.setText("");
}
}
}
Output

Dept. of CSE, BGSIT, BG Nagar 18


Java Lab Manual Nandini S R

Content Beyond Syllabus Programs

1. The Fibonacci sequence is defined by the following rule. The first 2


values in the sequence are 1, 1. Every subsequent value is the sum of the 2
values preceding it. Write a Java program that uses non-recursive
functions to print the nth value of the Fibonacci sequence.

/*Non Recursive Solution*/


import java.util.Scanner;
class Fib {
public static void main(String args[ ]) {
Scanner input=new Scanner(System.in);
int i,a=1,b=1,c=0,t;
System.out.println("Enter value of t:");
t=input.nextInt();
System.out.print(a);
System.out.print(" "+b);
for(i=0;i<t-2;i++) {
c=a+b;
a=b;
b=c;
System.out.print(" "+c);
}
System.out.println();
System.out.print(t+"th value of the series is: "+c);
}
}

Output

Dept. of CSE, BGSIT, BG Nagar 19


Java Lab Manual Nandini S R

2. Write a java program to display the employee details using Scanner class.

import java.util.Scanner;

class Employee

int Id;

String Name;

int Age;

long Salary;

void GetData() // Defining GetData()

Scanner sc = new Scanner(System.in);

System.out.print("\n\tEnter Employee Id : ");

Id = Integer.parseInt(sc.nextLine());

System.out.print("\n\tEnter Employee Name : ");

Name = sc.nextLine();

System.out.print("\n\tEnter Employee Age : ");

Age = Integer.parseInt(sc.nextLine());

System.out.print("\n\tEnter Employee Salary : ");

Salary = Integer.parseInt(sc.nextLine());

Dept. of CSE, BGSIT, BG Nagar 20


Java Lab Manual Nandini S R

void PutData() // Defining PutData()

System.out.print("\n\t" + Id + "\t" +Name + "\t" +Age + "\t" +Salary);

public static void main(String args[])

Employee[] Emp = new Employee[3];

int i;

for(i=0;i<3;i++)

Emp[i] = new Employee(); // Allocating memory to each object

for(i=0;i<3;i++)

System.out.print("\nEnter details of "+ (i+1) +" Employee\n");

Emp[i].GetData();

System.out.print("\nDetails of Employees\n");

for(i=0;i<3;i++)

Emp[i].PutData();

Dept. of CSE, BGSIT, BG Nagar 21


Java Lab Manual Nandini S R

Output

Dept. of CSE, BGSIT, BG Nagar 22


Java Lab Manual Nandini S R

Viva Questions for “OOPS with Java programming lab ”


Q1- List the Java Features ?

1.Compiled and Interpreted

2.Platform-Independent and Portable

3. Object – Oriented

4.Robust and Secure

5.Distributed

6.Simple, Small and Familiar

7.Multithreaded and interactive

8.High Performance

9.Dynamic and Extensible

Q2 -How Java Differs From C ?

 Java does not include the C unique statement keywords goto, size of, and type def.

 Java does not contain the data type struct,union and enum.

 Java does not define the type modifiers keywords auto,extern ,register,signed,and
unsigned.

 Java does not support an explicit pointer type.

Q3- How Java Differs From C ++ ?

 Java does not support operator overloading.

 Java does not have template classes as in C++.

 Java does not support multiple inheritance of classes. This is accomplished using a
new feature called “interface”.

Dept. of CSE, BGSIT, BG Nagar 23


Java Lab Manual Nandini S R

Q4- Name the Java Components?

 Object and Classes

 Data Abstraction and Encapsulation

 Inheritance

 Polymorephism

 Dynamic Binding

 Message Communication.

Q5- What is the Variables ?

A variable is an identifier that denotes a storage location used to store a data value.

Q6- What are Class?

Class is a template for multiple objects with similar features and it is a blue print for
objects. It defines a type of object according to the data the object can hold and the
operations the object can perform.

Q7- What are Primitive data types?

Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean,
char.

Q8- Define method overloading.?

Function with same name but different argument perform different task known as method
overloading.

Q9- What is Constructor ?

Constructor is a special member function of class call automatically when object is created.

Q10- What is the Parameterized constructors ?

The constructors that can take argument are called parameterized constructors.

Q11- What is OOPs?

Object oriented programming organizes a program around its data, i. e. , objects and a set of
well defined interfaces to that data. An object-oriented program can be characterized as data
controlling access to code.

Dept. of CSE, BGSIT, BG Nagar 24


Java Lab Manual Nandini S R

Q12- What are Encapsulation?

Encapsulation is the mechanism that binds together code and data it manipulates and keeps
both safe from outside interference and misuse.

Q13- What are Polymorphism?

Polymorphism is the feature that allows one interface to be used for general class actions.

Q14- What is the difference between procedural and object-oriented programs?

a) In procedural program, programming logic follows certain procedures and the instructions
are executed one after another. In OOP program, unit of program is object, which is nothing
but combination of data and code.

b) In procedural program, data is exposed to the whole program whereas in OOPs program, it
is accessible with in the object and which in turn assures the security of the code.

Q15- What is an Object and how do you allocate memory to it?

Object is an instance of a class and it is a software unit that combines a structured set of data
with a set of operations for inspecting and manipulating that data. When an object is created
using new operator, memory is allocated to it.

Q16- What is the difference between constructor and method?

Constructor will be automatically invoked when an object is created whereas method has to
be called sexplicitly.

Q17- What are methods and how are they defined?

Methods are functions that operate on instances of classes in which they are defined.

Q18- What is the use of bin and lib in JDK?

Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API
and all packages.

Q19-What is casting?

Casting is used to convert the value of one type to another.

Dept. of CSE, BGSIT, BG Nagar 25


Java Lab Manual Nandini S R

Q20- How many ways can an argument be passed to a subroutine and explain them?

An argument can be passed in two ways. They are passing by value and passing by
reference. Passing by value: This method copies the value of an argument into the formal
parameter of the subroutine.

Passing by reference: In this method, a reference to an argument (not the value of the
argument) is passed to the parameter.

Q21- What is the difference between an argument and a parameter?

While defining method, variables passed in the method are called parameters. While using
those methods, values passed to those variables are called arguments.

Q22- What are different types of access modifiers?

public: Any thing declared as public can be accessed from anywhere.

private: Any thing declared as private can’t be seen outside of its class.

protected: Any thing declared as protected can be accessed by classes in the same package
and subclasses in the other packages.

default modifier : Can be accessed only to classes in the same package.

Q23- What is UNICODE?

A5- Unicode is used for internal representation of characters and strings and it uses 16 bits to
represent each other.

Q24- What is the difference between String and String Buffer?

a) String objects are constants and immutable whereas StringBuffer objects are not.

b) String class supports constant strings whereas StringBuffer class supports growable and
modifiable strings.

Q25- What are wrapper classes?

Wrapper classes are classes that allow primitive types to be accessed as objects.

Q26.What is the Inheritance and what are its advantages?

Dept. of CSE, BGSIT, BG Nagar 26


Java Lab Manual Nandini S R

A10- Inheritance is the process by which object of one class acquire the properties of object
of another class. The advantages of inheritance are reusability of code and accessibility of
variables and methods of the super class by subclasses.

Q27- What is the Package?

A2- Package is the collection of class stored in a folder. These class can be used in any java
program.

Q28- What is an abstract class?

An abstract class is a class designed with implementation gaps for subclasses to fill in and is
deliberately incomplete.

Q29- What is the difference between abstract class and interface?

a) All the methods declared inside an interface are abstract whereas abstract class must have
at least one abstract method and others may be concrete or abstract.

b) In abstract class, key word abstract must be used for the methods whereas interface we
need not use that keyword for the methods.

c) Abstract class must have subclasses whereas interface can’t have subclasses.

Q30- What is the class and interface in java to create thread and which is the most
advantageous method?

Thread class and Runnable interface can be used to create threads and using Runnable
interface is the most advantageous method to create threads because we need not extend
thread class here.

Q31- What are the states associated in the thread?

Thread contains ready, running, waiting and dead states.

Q32-What is The Try-Catch-Finally ?

1.Java uses a keyword Try to handle a run-time error, simply enclose the code that you want
to monitor inside a try block. Immediately following the try block.

2.include a catch clause that specifies the exception type that you wish to catch.

Dept. of CSE, BGSIT, BG Nagar 27


Java Lab Manual Nandini S R

3.finally block can be used to handle any exception generated within a try block.

4.When a finally block is defined , this is guaranteed to execute ,regardless of whether or not
an exception is thrown.

Q33-What are the Throw statements ?

you have only been catching exceptions that are thrown by the Java run-time system.

Q34-What are the Throws ?

A4- If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception.

Q35- What is Java?

Java is an object-oriented programming language developed initially by James Gosling and


colleagues at Sun Microsystems.

Q36- Can you have virtual functions in Java?

Yes, all functions in Java are virtual by default.

Q37- Name the containers which uses Border Layout as their default layout?

Containers which uses Border Layout as their default are: window, Frame and Dialog
classes.

Q38-What is the exception ?

An exception is a condition that is caused by a run-time error in the program.

Q39-What is the difference between an argument and a parameter?

While defining method, variables passed in the method are called parameters. While using
those methods, values passed to those variables are called arguments.

Q40-What is Garbage Collection and how to call it explicitly?

Dept. of CSE, BGSIT, BG Nagar 28


Java Lab Manual Nandini S R

When an object is no longer referred to by any variable, java automatically reclaims memory
used by that object. This is known as garbage collection. System. gc() method may be used to
call it explicitly.

Q41-What is the difference between this() and super()?

this() can be used to invoke a constructor of the same class whereas super() can be used to
invoke a super class constructor.

Q42- What is the difference between superclass and subclass?

A super class is a class that is inherited whereas sub class is a class that does the inheriting.

Q43-What is the difference between exception and error?

The exception class defines mild error conditions that your program encounters. Exceptions
can occur when trying to open the file, which does not exist, the network connection is
disrupted, operands being manipulated are out of prescribed ranges, the class file you are
interested in loading is missing.

The error class defines serious error conditions that you should not attempt to recover from.
In most cases it is advisable to let the program terminate when such an error is encountered.

Q44- What is the multithreaded?

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 define a separate path of execution.

Q45-What is the difference between process and thread?

Process is a program in execution whereas thread is a separate path of execution in a


program.

Dept. of CSE, BGSIT, BG Nagar 29

You might also like