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

JAVA Lab Manual

Uploaded by

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

JAVA Lab Manual

Uploaded by

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

K J Somaiya Institute of Engineering and Information Technology

K. J. Somaiya Institute of Engineering


And
Information Technology
Sion, Mumbai - 400022

DEPARTMENT OF COMPUTER ENGINEERING

Academic Year: 2022-23(Odd Sem)

Lab Manual

Class –SY Sem - III

Subject: Skill Based Learning: Object Oriented


Programming with Java (SAT-III)
(1UCEXS33)

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

K.J.SOMAIYA INSTITUTE OF ENGINEERING AND INFORMATION


TECHNOLOGY

DEPARTMENT OF COMPUTER ENGINEERING


Subject: Skill Based Learning: Object Oriented Semester: III
Programming with Java (SAT-III)

Course code: 1UCEXS33 Practical/week: 2 hrs/batch


Session: 2021-22

Skill based learning Educational Objectives (SEOs):


Sr. No Objectives
SEO1 To learn the basic concepts of object-oriented programming
SEO2 To study JAVA programming language
SEO3 To study various concepts of JAVA programming like multithreading, exception
Handling, packages, etc.
SEO4 To explain components of GUI based programming

Skill Outcomes (LOs): Learner will be able to…


Index Outcomes
SO1 Apply fundamental programming constructs.
SO2 Implement the concept of classes and objects, inheritance and interfaces.
SO3 Implement the concept of strings, arrays and packages
SO4 Implement the concept of exception handling and multithreading.
SO5 Develop GUI based application.
SO6 Apply ethical principles like timeliness and adhere to the rules of the laboratory

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Mapping of Skill Objectives with Skill Outcomes:

Skill Outcomes

Skill Objectives SO1 SO2 SO3 SO4 SO5 SO6

SEO 1 √ √ √

SEO 2 √ √ √ √ √ √

SEO 3 √ √ √

SEO 4 √ √

Mapping of SOs with POs and PSOs:

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

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

List of Experiments:

Expt Name of Experiments SEOs SOs


No.
0 Prerequisite lab
1 Write a program to implement basic SEO1,SEO2 SO1, SO6
programming constructs like branching and
looping
2 Write a program to demonstrate different SEO1,SEO2 SO1, SO6
ways of accepting user input in Java
3 Write a program to implement the concept SEO1,SEO2 SO2, SO6
of :
1. Method overloading
2. Constructor overloading
4 Write a program implement the concept of SEO2 SO3, SO6
2D array and String Manipulation functions
in Java
5 Write a program to implement the concept SEO1,SEO2 SO2, SO6
of Inheritance
6 Write a program to implement the concept SEO1,SEO2 SO2, SO6
of Method Overriding
7 Write a program to implement the concept SEO1,SEO2 SO2, SO6
of abstract class and abstract method
8 Write a program to implement the concept SEO2, SEO3 SO3, SO6
of package
9 Write a program to implement the concept SEO2, SEO3 SO4, SO6
of Exception handling
10 Write a program to implement the concept SEO2, SEO3 SO4, SO6
of Multithreading Algorithm
11 Design form for Admission process SEO2, SEO4 SO5, SO6
management application system using AWT
or Java Swing
12 Study and Implement the concept of JDBC SEO2, SEO4 SO5, SO6
and Perform CRUD Operation on the form
created in 11 using Java Database
Connectivity

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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.

Software Required: Jdk1.8.0

Theory:

Control statements in java is one of the fundamentals required for java programming. It allows
the smooth flow of a program.

Java control statements:

Control statements can be divided into three categories, namely

• Selection statements/decision making statements


• Iteration statements
• Jump statements

1. lection statements/decision making statements

Simple if statement
The if statement determines whether a code should be executed based on the specified condition.

Syntax:

If (condition) {

Statement 1; //executed if condition is true

Statement 2; //executed irrespective of the condition

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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) {

Statement 1; //executed if first condition is true

if (condition2) {

Statement 2; //executed if second condition is true

else {

Statement 3; //executed if second condition is false

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.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Syntax:

for (initialization; condition; increment/decrement)

{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.

Source Code: Source code of program

Output: Screenshots of output.

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:

1. What are different control statements in Java?

2. What is the difference between while and dowhile,for and foreach ,break and continue.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Experiment No:2

Aim: Write a program to demonstrate different ways of accepting user input in java

A: Write a program to calculate area of circle. (Scanner class)

B. Write a program to find the number is prime number or not. (BufferedReaderClass)

C. Write a program to display addition of two numbers by using Command Line argument.
(Commend Line argument)

Software Required: Jdk1.8.0

Theory:

There are different ways of accepting user input in java.

1.Command Line Argument

2.Scanner class

3.BufferedReader class

1.Command Line Argument

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.

Command line arguments are passed in an array of Strings,which is passed as parameter to


main() method in any application program. The first array component starts with zero.

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.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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.

The following is the code for each of the above methods:

import java.util.Scanner; // This will import the Scanner class.

import java.util.*; // This will import the full java.util library—every class within
java.util.

Methods of Scanner Class:

Method Type of Value the Method Collects

nextBoolean() Boolean

nextByte() Byte

nextDouble() Double

nextFloat() Float

nextInt() Int

nextLine() String

nextLong() Long

nextShort() Short

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Java BufferedReader Class :

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.

Sourse Code: Source code of program

Output: Screenshots of output.

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:

1.What is Command Line argument

2.How to use BufferedReader Class

3.What is the difference between Scanner class and BufferedReader Class

4.What are the different methods of Scanner Class to accept input

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Experiment No:3

Aim: Write a program to implement the concept of method overloading and Constructor
overloading

Software Required: Jdk1.8.0

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.

Three ways to overload a method


In order to overload a method, the argument lists of the methods must differ in either of these:
1.Number of parameters.
For example: This is a valid case of overloading

add(int, int)

add(int, int, int)

2. Data type of parameters.


For example:

add(int, int)

add(int, float)

3. Sequence of Data type of parameters.


For example:

add(int, float)

add(float, int)

Invalid case of method overloading:


It is not possible

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

int add(int, int)


float add(int, 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.

Examples of valid constructors for class Account are

Account(int a);
Account (int a,int b);
Account (String a,int b);

Sourse Code: Source code of program

Conclusion: The concept of method overloading is studied and implemented to calculate are of
different shapes like rectangle, square and circle.

Viva Questions:

1. What do you mean by method overloading?

2. What do you mean by constructor overloading?

3. what do you mean by compile time polymorphism and how to achieve this.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Experiment No:4

Aim: A. Write a program to perform addition of two matrices using 2D array.


B. Write a program to implement different String Manipulation functions.

Software Required: Jdk1.8.0

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.

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

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'.

String Manipulation Function:


Methods Description

concat() joins the two strings together

equals() compares the value of two strings

charAt() returns the character present in the specified location

getBytes() converts the string to an array of bytes

returns the position of the specified character in the


indexOf()
string

length() returns the size of the specified string

replaces the specified old character with the specified


replace()
new character

substring() returns the substring of the string

split() breaks the string into an array of strings

toLowerCase() converts the string to lowercase

toUpperCase() converts the string to uppercase

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

valueOf() returns the string representation of the specified data

Sourse Code: Source code of program

Output: Screenshots of output.

Conclusion: The concept of array and String is studied and implemented.

Viva Questions:

1. What is array? What are different methods of Array?

2. What are different string manipulation functions?

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Experiment No:5

Aim: Write a program to implement the concept of Inheritance

A. Write a program to implement multilevel inheritance.

Software Required: Jdk1.8.0

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

Inheritance is an is-a relationship. We use inheritance only if an is-a relationship is present


between the two classes.

Here are some examples:

• A car is a vehicle.

• Orange is a fruit.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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.

o Reusability: As the name specifies, reusability is a mechanism which facilitates you to


reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.

Types of Inheritance:

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Sourse Code: Source code of program

Output: Screenshots of output.

Conclusion: The concept of inheritance and its types is studied and implemented to see the real
life usage.

Viva Questions:

1. What is inheritance?

2. Different types of inheritance in Java?

3. Which Keyword is used to achieve inheritance?

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Experiment No:6

Aim: Write a program to implement the concept of Method Overriding.

Software Required: Jdk1.8.0

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.

Advantage of method overriding

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.

Rules of method overriding in Java

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.

2. Access Modifier of the overriding method (method of subclass) cannot be more


restrictive than the overridden method of parent class. For e.g. if the Access Modifier of
parent class method is public then the overriding method (child class method ) cannot
have private, protected and default Access modifier, because all of these three access
modifiers are more restrictive than public.

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.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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.

Sourse Code: Source code of program

Output: Screenshots of output.

Conclusion: The concept of Method Overriding is studied and implemented.

Viva Questions:

1. What is method overriding?

2. What is use of super keyword?

3. What is the use of final keyword?

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Experiment No:7

Aim: A. Write a program to implement the concept of abstract class and abstract method.

B. Write a program to demonstrate multiple inheritance using interface.

Software Required: Jdk1.8.0

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.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)

2. Interface (100%)

Abstract class in Java

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 An abstract class must be declared with an abstract keyword.

o It can have abstract and non-abstract methods.

o It cannot be instantiated.

o It can have constructors and static methods also.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

o It can have final methods which will force the subclass not to change the body of the
method.

Example of abstract class

1. abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Sourse Code: Source code of program

Output: Screenshots of output.

Conclusion: Concept of abstract class and abstract method is studied and implemented.

Viva Questions:

1. What is abstraction?

2. How to achieve abstraction?

3. What is the difference between abstraction and interface?

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Experiment No:8

Aim: Write a program to implement the concept of package

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.

Software Required: Jdk1.8.0

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.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Advantage of using packages in Java


1. Maintenance: Java packages are used for proper maintenance. If any developer newly joined a
company, he can easily reach to files needed.

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.

4. Organized: It also helps in organizing the files within our project.

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.

Types of Packages in Java


There are two different types of packages in Java. They are:
1. User-defined Package
The package which is defined by the user is called a User-defined package. It contains user-
defined classes and interfaces.
Creating package: package packageName;

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.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology
Core packages:

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.

Window Toolkit and Applet:

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.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Source Code: Source code of program

Output: Screenshots of output.

Conclusion: The concept of package is studied and implemented.

Viva Questions:

1. What is package?

2. What is the advantage of using package?

3. What is the difference between inbuilt package and user defined package?

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Experiment No:9

Aim: Write a program to implement the concept of Exception Handling.

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.

Software Required: Jdk1.8.0

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.

Why an exception occurs?

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.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Types of exceptions

There are two types of exceptions in Java:

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.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Java provides five keyword for Exception Handling :

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.

• A try can have many catch statements.

• 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

• throws keyword is used to carry forward that exception object.

Sourse Code: Source code of program

Output: Screenshots of output.

Conclusion: The concept of exception handling and usage of keywords like


try,catch,throw,throws and finally is studied and implemented.

Viva Questions:

1. What is Exception?

2. Why exception handling is important?

3. What is the usage of keywords like try,catch,throw,throws and finally?

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Experiment No:10

Aim: Write a program to implement the concept of Multithreading.


Software Required: Jdk1.8.0
1. Create a Thread by Extending a Thread Class
Theory:

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.

Ways to Create Thread:

2. Create a Thread by Implementing a Runnable Interface

Thread Methods
Following is the list of important methods available in the Thread class.

Sr.No. Method & Description

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)

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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.

Sourse Code: Source code of program

Output: Screenshots of output.

Conclusion: The concept of multithreading is studied and implemented.

Viva Questions:

1. What is Multithreading?

2. Explain Thread Life cycle?

3. What are the different ways to create Thread?

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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

There are many advantages of applet. They are as follows:

o It works at client side so less response time.

o Secured

o It can be executed by browsers running under many plateforms, including Linux,


Windows, Mac Os etc.

Important points :

1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.

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.

3. In general, execution of an applet does not begin at main() method.

4. Output of an applet window is not performed by System.out.println(). Rather it is handled


with various AWT methods, such as drawString().

Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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.

Sourse Code: Source code of program

Output: Screenshots of output.

Conclusion: The concept of applet and Graphics is used to display smiley face

Questions:

1. What is applet?

2. what is the difference between applet and application?

3. Explain applet life cycle?

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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/

Software Required: Jdk1.8.0

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

Steps for connectivity between Java program and database:

1. Loading the Driver

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(): DriverManager is a Java inbuilt class with a static member


register. Here we call the constructor of the driver class at compile time . The following example
uses DriverManager.registerDriver()to register the Oracle driver –

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

2. Create the connections


After loading the driver, establish connections using :

Connection con = DriverManager.getConnection(url,user,password)

user – username from which your sql command prompt can be accessed.

password – password from which your sql command prompt can be accessed.

con: is a reference to Connection interface.

url : Uniform Resource Locator. It can be created as follows:

String url = “ jdbc:oracle:thin:@localhost:1521:xe”

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.

Use of JDBC Statement is as follows:

Statement st = con.createStatement();

Here, con is a reference to Connection interface used in previous step .

4. Execute the query

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:

Query for updating / inserting table in a database.

Query for retrieving data .

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

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.

The executeUpdate(sql query) method ofStatement interface is used to execute queries of


updating/inserting .

5.Close the connections

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

Output: Screenshots of output.

Conclusion: Different database operations are performed using JDBC .

Questions:

1. What is JDBC?

2. what is How to perform select operation?

3. What is PreparedStatement in Java?

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA


K J Somaiya Institute of Engineering and Information Technology

Department of Computer Engineering/SY/Sem-III/SBL- OOPM JAVA

You might also like