Java Lab Programs
Java Lab Programs
}
Output
Light on?true
Light off? false
int n = 4;
String temp;
if (names[i].compareTo(names[j]) > 0) {
// swapping
temp = names[i];
names[i] = names[j];
names[j] = temp;
System.out.println(names[i]);
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
System.out.println(add(4, 6));
System.out.println("add() with 3 parameters");
System.out.println(add(4, 6, 7));
}
}
Output:
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;
}
}
{
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%
Output
Output
8.WAP to handle the Exception using try and multiple catch block.
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));
}
}
int factorial(int n) {
if(n==0)
return 1;
else
return n*factorial(n-1);
}
}
Output
10. Create a Layout using applets to arrange Buttons for digits and for the
+ - * % operations. Add a text field to display the result.
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='+';
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");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear")) {
T1.setText("");
}
}
}
Output
Output
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;
Id = Integer.parseInt(sc.nextLine());
Name = sc.nextLine();
Age = Integer.parseInt(sc.nextLine());
Salary = Integer.parseInt(sc.nextLine());
int i;
for(i=0;i<3;i++)
for(i=0;i<3;i++)
Emp[i].GetData();
System.out.print("\nDetails of Employees\n");
for(i=0;i<3;i++)
Emp[i].PutData();
Output
3. Object – Oriented
5.Distributed
8.High Performance
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 multiple inheritance of classes. This is accomplished using a
new feature called “interface”.
Inheritance
Polymorephism
Dynamic Binding
Message Communication.
A variable is an identifier that denotes a storage location used to store a data value.
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.
Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean,
char.
Function with same name but different argument perform different task known as method
overloading.
Constructor is a special member function of class call automatically when object is created.
The constructors that can take argument are called parameterized constructors.
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.
Encapsulation is the mechanism that binds together code and data it manipulates and keeps
both safe from outside interference and misuse.
Polymorphism is the feature that allows one interface to be used for general class actions.
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.
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.
Constructor will be automatically invoked when an object is created whereas method has to
be called sexplicitly.
Methods are functions that operate on instances of classes in which they are defined.
Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API
and all packages.
Q19-What is casting?
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.
While defining method, variables passed in the method are called parameters. While using
those methods, values passed to those variables are called arguments.
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.
A5- Unicode is used for internal representation of characters and strings and it uses 16 bits to
represent each other.
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.
Wrapper classes are classes that allow primitive types to be accessed as objects.
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.
A2- Package is the collection of class stored in a folder. These class can be used in any java
program.
An abstract class is a class designed with implementation gaps for subclasses to fill in and is
deliberately incomplete.
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.
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.
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.
you have only been catching exceptions that are thrown by the Java run-time system.
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.
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.
While defining method, variables passed in the method are called parameters. While using
those methods, values passed to those variables are called arguments.
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.
this() can be used to invoke a constructor of the same class whereas super() can be used to
invoke a super class constructor.
A super class is a class that is inherited whereas sub class is a class that does the inheriting.
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.
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.