JAVA Lab Manual
JAVA Lab Manual
Lab Manual
Skill Outcomes
SEO 1 √ √ √
SEO 2 √ √ √ √ √ √
SEO 3 √ √ √
SEO 4 √ √
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
SO1 3 1 1 1 1 1 - - - - 3 1 3 - 2
SO2 3 - 2 1 2 1 - - - - 3 1 3 - -
SO3 3 - 2 1 2 1 - - - - 3 1 3 - -
SO4 3 - 2 1 2 1 - - - - 3 1 3 - -
SO5 3 - 2 1 2 1 - - - - 3 1 3 - -
SO6 3 3 3 3 3 3 2 2 2 2 3 1 3 - 2
List of Experiments:
Experiment No:1
Aim: Write a programs on Basic programming constructs like branching and looping.
A: Write a program implement different arithmetic operations using switch case statement
B. Write a program to display Fibonacci Series by using loop. Also write a program
to implement for each loop to display array elements.
Theory:
Control statements in java is one of the fundamentals required for java programming. It allows
the smooth flow of a program.
Simple if statement
The if statement determines whether a code should be executed based on the specified condition.
Syntax:
If (condition) {
If..else statement
In this statement, if the condition specified is true, the if block is executed. Otherwise, the else
block is executed.
Nested if statement
An if present inside an if block is known as a nested if block. It is similar to an if..else statement,
except they are defined inside another if..else statement.
if (condition1) {
if (condition2) {
else {
Switch statement
A switch statement in java is used to execute a single statement from multiple conditions. The
switch statement can be used with short, byte, int, long, enum types, etc.
Certain points must be noted while using the switch statement:
α one or n number of case values can be specified for a switch expression.
Α case values that are duplicate are not permissible. A compile-time error is generated by the
compiler if unique values are not used.
Α the case value must be literal or constant. Variables are not permissible.
Α usage of break statement is made to terminate the statement sequence. It is optional to use this
statement. If this statement is not specified, the next case is executed.
2. Looping statements
Statements that execute a block of code repeatedly until a specified condition is met are known
as looping statements. Java provides the user with three types of loops:
While loop :
Known as the most common loop, the while loop evaluates a certain condition. If the condition is
true, the code is executed. This process is continued until the specified condition turns out to be
false.The condition to be specified in the while loop must be a boolean expression. An error will
be generated if the type used is int or a string.
while (condition)
Statement one;
Do….while loop :
The do-while loop is similar to the while loop, the only difference being that the condition in the
do-while loop is evaluated after the execution of the loop body. This guarantees that the loop is
executed at least once
do{
//code to be executed
}while(condition);
For
The for loop in java is used to iterate and evaluate a code multiple times. When the number of
iterations is known by the user, it is recommended to use the for loop.
Syntax:
{Statement;}
for-each
The traversal of elements in an array can be done by the for-each loop. The elements present in
the array are returned one by one. It must be noted that the user does not have to increment the
value in the for-each loop.
Branching statements :
Branching statements in java are used to jump from a statement to another statement, thereby the
transferring the flow of execution.
Break :
The break statement in java is used to terminate a loop and break the current flow of the
program.
Continue :
To jump to the next iteration of the loop, we make use of the continue statement. This statement
continues the current flow of the program and skips a part of the code at the specified condition.
Conclusion: Control statements in java are studied. switch case control statement is used to
perform different arithmetic operations and looping statements used to display Fibonacci series
number and print array elements.
Questions:
2. What is the difference between while and dowhile,for and foreach ,break and continue.
Experiment No:2
Aim: Write a program to demonstrate different ways of accepting user input in java
C. Write a program to display addition of two numbers by using Command Line argument.
(Commend Line argument)
Theory:
2.Scanner class
3.BufferedReader class
There may be occasions when we may like our program to act in a particular way depending on
the input provided at the time of execution. This is achieved by java programs by using what is
known as Command Line arguments. They are parameters that are supplied to the application
program at the time of invoking at for execution.
2. The Java Scanner class is used to collect user input. Scanner is part of the java.util package, so
it can be imported without downloading any external libraries.
In order to work with the Scanner class, you must first import it into your code. There are two
ways you can do this:
If you only need to work with the java.util.Scanner class, you can import the Scanner
class directly.
If you are working with other modules in the java.util library, you may want to import
the full library.
import java.util.*; // This will import the full java.util library—every class within
java.util.
nextBoolean() Boolean
nextByte() Byte
nextDouble() Double
nextFloat() Float
nextInt() Int
nextLine() String
nextLong() Long
nextShort() Short
Java BufferedReader class is used to read the text from a character-based input stream. It can be
used to read data line by line by readLine() method. It makes the performance fast. It
inherits Reader class.
Conclusion: Java provides different ways of accepting user input. Scanner class, Buffered Reader
class and Command Line argument approach is used here to demonstrate the same.
Viva Questions:
Experiment No:3
Aim: Write a program to implement the concept of method overloading and Constructor
overloading
Theory:
Method Overloading is a feature that allows a class to have more than one method having the
same name, if their argument lists are different. Method overloading is an example of Static
Polymorphism. Static Polymorphism is also known as compile time binding or early binding.
Static binding happens at compile time. Method overloading is an example of static binding
where binding of method call to its definition happens at Compile time.
add(int, int)
add(int, int)
add(int, float)
add(int, float)
add(float, int)
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter list. The compiler differentiates these constructors by taking
into account the number of parameters in the list and their type.
Account(int a);
Account (int a,int b);
Account (String a,int b);
Conclusion: The concept of method overloading is studied and implemented to calculate are of
different shapes like rectangle, square and circle.
Viva Questions:
3. what do you mean by compile time polymorphism and how to achieve this.
Experiment No:4
Theory:
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
arrayRefVar=new datatype[size];
String Class
In Java, a string is a sequence of characters. For example, "hello" is a string containing a
sequence of characters 'h', 'e', 'l', 'l', and 'o'.
Viva Questions:
Experiment No:5
Theory:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
is-a relationship
• A car is a vehicle.
• Orange is a fruit.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
Types of Inheritance:
Conclusion: The concept of inheritance and its types is studied and implemented to see the real
life usage.
Viva Questions:
1. What is inheritance?
Experiment No:6
Theory:
Declaring a method in sub class which is already present in parent class is known as method
overriding. Overriding is done so that a child class can give its own implementation to a method
which is already provided by the parent class. In this case the method in parent class is called
overridden method and the method in child class is called overriding method.
The main advantage of method overriding is that the class can give its own specific
implementation to a inherited method without even modifying the parent class code.
This is helpful when a class has several child classes, so if a child class needs to use the parent
class method, it can use it and the other classes that want to have different implementation can
use overriding feature to make changes without touching the parent class code.
1. Argument list: The argument list of overriding method (method of child class) must
match the Overridden method(the method of parent class). The data types of the
arguments and their sequence should exactly match.
1. private, static and final methods cannot be overridden as they are local to the class.
However static methods can be re-declared in the sub class, in this case the sub-class
method would act differently and will have nothing to do with the same static method of
parent class.
2. Overriding method (method of child class) can throw unchecked exceptions, regardless of
whether the overridden method(method of parent class) throws any exception or not.
However the overriding method should not throw checked exceptions that are new or
broader than the ones declared by the overridden method.
3. Binding of overridden methods happen at runtime which is known as dynamic binding.
4. If a class is extending an abstract class or implementing an interface then it has to
override all the abstract methods unless the class itself is a abstract class.
Viva Questions:
Experiment No:7
Aim: A. Write a program to implement the concept of abstract class and abstract method.
Theory:
Abstraction is a process of hiding the implementation details and showing only functionality to
the user. It shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal
processing about the message delivery.
2. Interface (100%)
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
o It cannot be instantiated.
o It can have final methods which will force the subclass not to change the body of the
method.
A method which is declared as abstract and does not have implementation is known as an
abstract method.
Conclusion: Concept of abstract class and abstract method is studied and implemented.
Viva Questions:
1. What is abstraction?
Experiment No:8
A: Develop a program which consists of the package named let_me_calculate with a class
named calculator and a method name add to add two integer numbers, import
let_me_calculate package in another program to add two numbers.
B: Develop a program which consists of the package named myinstitute include class name
as Department with one method to display the staff of that department. Develop a program
to import this package in java application and call the method define in the package.
Theory:
A package is nothing but a physical folder structure (directories) that contains a group of related
classes, interfaces, and sub-packages according to their functionality. It provides a convenient
way to organize your work. The Java language has various in-built packages.For example,
java.lang, java.util, java.io, and java.net. All these packages are defined as a very clear and
systematic packaging mechanism for categorizing and managing.
2. Reusability: We can place the common code in a common folder so that everybody can check
that folder and use it whenever needed.
3. Name conflict: Packages help to resolve the naming conflict between the two classes with the
same name. Assume that there are two classes with the same name Student.java. Each class will
be stored in its own packages such as stdPack1 and stdPack2 without having any conflict of
names.
5. Access Protection: A package provides access protection. It can be used to provide visibility
control. The members of the class can be defined in such a manner that they will be visible only
to elements of that package.
package myPackage;
public class A {
// class body
}
2. Predefined Packages in Java (Built-in Packages)
Predefined packages in java are those which are developed by Sun Microsystem. They are also
called built-in packages in java. These packages consist of a large number of predefined classes,
interfaces, and methods that are used by the programmer to perform any task in his programs.
1. Java.lang: lang stands for language. The Java language package consists of java classes and
interfaces that form the core of the Java language and the JVM. It is a fundamental package
which is useful for writing and executing all Java programs.
Examples are classes, objects, String, Thread, predefined data types, etc. It is imported
automatically into the Java programs.
2. Java.io: io stands for input and output. It provides a set of I/O streams that are used to read and
write data to files. A stream represents a flow of data from one place to another place.
3. Java util: util stands for utility. It contains a collection of useful utility classes and related
interfaces that implement data structures like LinkedList, Dictionary, HashTable, stack, vector,
Calender, data utility, etc.
4. Java.net: net stands for network. It contains networking classes and interfaces for networking
operations. The programming related to client-server can be done by using this package.
1. Java.awt: awt stands for abstract window toolkit. The Abstract window toolkit packages
contain the GUI(Graphical User Interface) elements such as buttons, lists, menus and text areas.
Programmers can develop programs with colorful screens, paintings, and images, etc using this
package.
2. Java.awt.image: It contains classes and interfaces for creating images and colors.
3. Java.applet: It is used for creating applets. Applets are programs which are executed from the
server into the client machine on a network.
4. Java.text: This package contains two important classes such as DateFormat and
NumberFormat. The class DateFormat is used to format dates and times. The NumberFormat is
used to format numeric values.
5. Java.sql: SQL stands for structured query language. This package is used in a Java program to
connect databases like Oracle or Sybase and retrieve the data from them.
Viva Questions:
1. What is package?
3. What is the difference between inbuilt package and user defined package?
Experiment No:9
A : Write any java program which illustrates the try, catch and finally blocks.
B : Write a program that handles an exception "Entry of negative age of person" using throw and
thows.
Theory:
Exception handling
Exception handling is one of the most important feature of java programming that allows us to
handle the runtime errors caused by exceptions.
What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. In such cases we get a system generated
error message. The good thing about exceptions is that they can be handled in Java. By handling
the exceptions we can provide a meaningful message to the user about the issue rather than a
system generated message, which may not be understandable to a user.
There can be several reasons that can cause a program to throw exception. For example: Opening
a non-existing file in your program, Network connection problem, bad input data provided by
user etc.
Types of exceptions
1) Checked exceptions
2) Unchecked exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not. If these
exceptions are not handled/declared in the program, you will get compilation error. For example,
SQLException, IOException, ClassNotFoundException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked
at compile-time so compiler does not check whether the programmer has handled them or not but
it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
1. try
2. catch
3. finally
4. throw
5. throws
• try-catch is a block of statements to try some commands and trap the runtime errors.
• finally is again a block to always execute some code irrespective of an exception. A try
can have only one finally block at the bottom.
• throw keyword is used to throw an object of some kind of class exception and
Viva Questions:
1. What is Exception?
Experiment No:10
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.Java is a multi-threaded programming
language which means we can develop multi-threaded program using Java. A multi-threaded
program contains two or more parts that can run concurrently and each part can handle a
different task at the same time making optimal use of the available resources specially when your
computer has multiple CPUs.Multi-threading enables you to write in a way where multiple
activities can proceed concurrently in the same program.
Thread Methods
Following is the list of important methods available in the Thread class.
1
public void start()
Starts the thread in a separate path of execution, then invokes the run() method on
this Thread object.
2
public void run()
If this Thread object was instantiated using a separate Runnable target, the run()
method is invoked on that Runnable object.
3
public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for
retrieving the name.
4
public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5
public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6
public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current
thread to block until the second thread terminates or the specified number of
milliseconds passes.
7
public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any
reason.
8
public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started
but before it runs to completion.
Viva Questions:
1. What is Multithreading?
Experiment No:11
Aim: Design form for Admission process management application system using AWT or Java
Swing
Software Required: Jdk1.8.0
Theory:
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
o Secured
Important points :
2. Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer. JDK provides a standard applet viewer tool called applet viewer.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
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
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.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
Conclusion: The concept of applet and Graphics is used to display smiley face
Questions:
1. What is applet?
Experiment No:12
Aim: Study and Implement the concept of JDBC and Perform CRUD Operation using Java
Database Connectivity (Select/Update/Delete operation) using Virtual Lab
Link: http://vlabs.iitb.ac.in/vlabs-dev/vlab_bootcamp/bootcamp/bots_with_dots/labs/index.html
http://vlabs.iitb.ac.in/vlabs-dev/vlab_bootcamp/bootcamp/bots_with_dots/labs/exp1/
Theory:
What is JDBC ?
JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC ( Open
Database Connectivity ). JDBC is an standard API specification developed in order to move data
from frontend to backend. This API consists of classes and interfaces written in Java
To begin with, you first need load the driver or register it before using it in the program .
Registration is to be done once in your program. You can register a driver in one of two ways
mentioned below :
Class.forName() : Here we load the driver’s class file into memory at the runtime. No need of
using new or creation of object .The following example uses Class.forName() to load the Oracle
driver –
Class.forName(“oracle.jdbc.driver.OracleDriver”);
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
user – username from which your sql command prompt can be accessed.
password – password from which your sql command prompt can be accessed.
Where oracle is the database used, thin is the driver used , @localhost is the IP Address where
database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above
are of String type and are to be declared by programmer before calling the function. Use of this
can be referred from final code.
3. Create a statement
Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you to send
SQL commands and receive data from your database.
Statement st = con.createStatement();
Now comes the most important part i.e executing the query. Query here is an SQL Query . Now
we know we can have multiple types of queries. Some of them are as follows:
The executeQuery() method of Statement interface is used to execute queries of retrieving values
from the database. This method returns the object of ResultSet that can be used to get all the
records of a table.
So finally we have sent the data to the specified location and now we are at the verge of
completion of our task .
By closing connection, objects of Statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
Sourse Code: Source code of program
Questions:
1. What is JDBC?