Java Lab Manual - Final
Java Lab Manual - Final
Ghangapatna, Bhubaneswar-752054
Odisha
Approved by AICTE, New Delhi|Affiliated to BPUT, Odisha
LAB MANUAL
G
Course: B.Tech
I Branch: Computer Science and Engineering
Name: ………………………………………
Registration No: .………………………….
Roll No: …………………………………….
Branch: …………………………………….
Java is a programming language developed by James Gosling with other team members 1995 for Sun
Microsystems. Java is a high level, robust, object-oriented and secure programming language
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist.
It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run
those programs which are written in other languages and compiled to Java bytecode.
The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is
a set of software tools which are used for developing Java applications. It is used to provide the runtime
environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM
uses at runtime.
This Java Development Kit(JDK) allows to code and run Java programs. It's possible that we can install multiple
JDK versions on the same PC.
1. Download latest Java JDK for your version(32 or 64 bit) of java for Windows
2. Once the download is complete, run the exe for install JDK
Once installation is complete set Environment Variables in Java, Path and Classpath
Environment Variable:
Environment variables basically are strings that contain information such as drive, path, or file name. It points
to the directory where the Java Development Kit (JDK) is installed on your computer.
PATH Setting:
1. Open Notepad from Start menu by selecting Programs > Accessories > Notepad.
2. Create a Source Code for Program
Declare a class with name A.
Declare the main method public static void main(String args[]){
Now Type the System.out.println("Hello World"); which displays the text Hello World.
class A{
public static void main(String args[]){
System.out.println("Hello World");
}
}
3. Save the file by using classname.java make sure to select file type as all files while saving the file in our
working folder
4. To Compile the java program open command prompt & write javac A.java
5. To execute the java program write java A
Source Code( .java) (compiler) Byte Code( . class) Load into JVM ( class Loader) JVM Machine code
Conclusion:
From the above experiment we can know the creation compilation and execution of java program.
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
Conclusion:
From the above experiment we can know about the Data types, variables, decision control structures: if, nested
if.
Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
While Loop:
The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed,
it is recommended to use while loop.
Syntax: while(condition){
//code to be executed
}
Do-while Loop:
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
Syntax: do{
//code to be executed
Conclusion:
From the above experiment we can know about the Loop control structures: do, while, for.
class Student{
int id;
String name;
}
class Student2{
public static void main(String args[]){
Student s1=new Student();
s1.id=331;
s1.name="Tarini";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Output: 331 Tarini
class Student{
int rollno;
String name;
void insertData(int r, String n){
rollno=r;
name=n;
}
void displayInfo(){
System.out.println(rollno+" "+name);
}
}
class Student3{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){
System.out.println(id+" "+name+" "+salary);
}
}
public class Emp {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(331,"Kalia",45000);
e2.insert(332,"Tapu",25000);
e3.insert(333,"Tapan",55000);
e1.display();
e2.display();
e3.display();
}
}
Output: 331 Kalia 45000.0
332 Tapu 25000.0
Conclusion:
From the above experiment we can know about the class and object creation and initialisation.
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With
the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose
properties are inherited is known as superclass (base class, parent class).
extends Keyword - extends is the keyword used to inherit the properties of a class.
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.
In Java polymorphism is mainly divided into two types:
1. Compile time Polymorphism
2. Runtime Polymorphism
1. Compile time polymorphism: It is also known as static polymorphism. This type of polymorphism is
achieved by function overloading or operator overloading.
Method Overloading: When there are multiple functions with same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by change
in number of arguments or/and change in type of arguments.
Operator Overloading: Java also provide option to overload operators. For example, we can
make the operator („+‟) for string class to concatenate two strings. We know that this is the
addition operator whose task is to add two operands. So a single operator „+‟ when placed between
integer operands, adds them and when placed between string operands, concatenates them.
Parent a;
a = new subclass1();
a.Print();
a = new subclass2();
a.Print();
}
}
Compile the above class : javac TestPolymorphism.java
java TestPolymorphism
Output: subclass1
subclass2
Conclusion:
From the above experiment we can know about the Encapsulation, Inheritance & Polymorphism.
Thread:
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a
shared memory area.
Multithreading in java is a process of executing multiple threads simultaneously.We use multithreading than
multiprocessing because threads use a shared memory area. They don't allocate separate memory area so
saves memory, and context-switching between the threads takes less time than process.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple operations
at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
a. New:
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method
b. Runnable:
The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
c. Running:
The thread is in running state if the thread scheduler has selected it.
d. Non-Runnable (Blocked):
This is the state when the thread is still alive, but is currently not eligible to run.
e. Terminated:
A thread is in terminated or dead state when its run() method exits.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class
extends Object class and implements Runnable interface.
APPLET:
Applet is a Java program that can be embedded into a web page. It runs inside the web browser and works at
client side. Applet is embedded in a HTML page using the APPLET or OBJECT tag and hosted on a web
server.
Applets are used to make the web site more dynamic and entertaining.
Life cycle of an applet :
When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can
be used for drawing oval, rectangle, arc etc.
In this case we have to define an html page with <applet code > ……… </applet>. This tag will link
the applet program and the size of its window. When this html file is opened using browser then the applet is
executed.
2. By appletViewer tool ( for Testing purpose)
Conclusion:
From the above experiment we can know about the Threads, exception handlings and applet programs.
So the question arises why use interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in interface are final,
public and static.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
Inner Class:
Inner class or nested class is a class which is declared inside the class or interface. We use inner
classes to logically group classes and interfaces in one place so that it can be more readable and
maintainable.
Additionally, it can access all the members of outer class including private data members and methods.
Wrapper Class:
The wrapper class in Java provides the mechanism to convert primitive into object and object into
primitive.Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into
primitives automatically. The automatic conversion of primitive into an object is known as autoboxing and
vice-versa unboxing.
1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments
passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
4. An object is needed to support synchronization in multithreading.
Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is
known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.
Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class
to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to
long, Double to double etc.
Generics in Java:
Generics in Java is similar to templates in C++. The Java Generics programming is introduced in
J2SE 5 to deal with type-safe objects. It makes the code stable by detecting the bugs at compile time.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store
other objects.
2) Type casting is not required: There is no need to typecast the object.
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.
Program to demonstrate the Generic
File Name: GenericMethodTest.java
public class GenericMethodTest {
// generic method printArray
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
Conclusion:
From the above experiment we can know about the Interfaces and inner classes, wrapper classes, generics.