Final Java File
Final Java File
Hamidpur, Delhi-110036
(Affiliated to Guru Gobind Singh Indraprastha University, New Delhi)
Bachelor of Technology
In
Computer Science and Engineering
2021-2025
ADVANCED JAVA PROGRAMMING
Lab File
Code: CIE - 306P
1. implement Multilevel
inheritance.
Write a Java program to
2. iimplement Polymorphism.
THEORY:
INHERITANCE- 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).
Multi-level Inheritance
The multi-level inheritance includes the involvement of at least two or more than two
classes. One class inherits the features from a parent class and the newly created sub -class
becomes the base class for another new class. A flow diagram of multi-level inheritance.
Code:
class Car {
public Car() {
System.out.println("Class Car");
}
public Maruti() {
System.out.println("Class Maruti");
}
public Maruti800() {
System.out.println("Maruti Model: 800");
}
public void speed() {
System.out.println("Max: 80Kmph");
}
Output:
EXPERIMENT - 2
THEORY:
Compile-time polymorphism
Compile-time polymorphism is obtained through method overloading. The term method
overloading allows us to have more than one method with the same name. Since this process is
executed during compile time, that’s why it is known as Compile-Time Polymorphism.
Runtime polymorphism.
When a polymorphism receives the information to call a method and that to be in runtime,
then it is called runtime polymorphism.
Code:
class Polygon {
// renders circle
public void render() {
System.out.println("Rendering Circle...");
}
}
class Main {
public static void main(String[] args) {
// create an object of Square
Square s1 = new Square();
s1.render();
Output:
EXPERIMENT – 3
AIM: Write a Java program to Handle the Exception Using Try and Multiple Catch Block.
THEORY:-
Exception:- In Java, an exception is an event that disrupts the normal flow of the program. It is
an object which is thrown at runtime.
Keyword Description
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.
Code:
class MultipleTryCatch
{
public static void main(String arg[])
{
int arr[]=new int[5];
try
{
try
{
System.out.println("Divide 1");
int b=23/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
arr[7]=10;
int c=22/0;
System.out.println("Divide 2 : "+c);
}
catch(ArithmeticException e)
{
System.out.println("Err:Divide by 0");
}
catch(ArrayIndexOutOfBoundsException e)
//ignored
{
System.out.println("Err:Array out of bound");
}
}
catch(Exception e)
{
System.out.println("Handled");
}
}
}
Output:
EXPERIMENT – 4
AIM: Write a Java program to Display Method Overriding in a Class using Inheritance Class.
THEORY:-
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Code:
class Parent {
void show(){
System.out.println("Parent's show()");
}
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override
void show()
{
System.out.println("Child's show()");
}
}
// Driver class
class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.show();
Parent obj2 = new Child();
obj2.show();
}
}
Output:
EXPERIMENT - 5
AIM: Write a Java program to Handle the User Defined Exception using Throw Keyword.
THEORY:-
Exception Handling in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to
handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.
Built-in Exceptions:-
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
• Checked Exceptions: Checked exceptions are called compile-time exceptions because
these exceptions are checked at compile-time by the compiler.
• Unchecked Exceptions: The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions at compile time. In simple
words, if a program throws an unchecked exception, and even if we didn’t handle or
declare it, the program would not give a compilation error.
User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
Code:
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
Output:
EXPERIMENT – 6
THEORY:-
Java Socket Programming
Java Socket programming is used for communication between the applications running on
different JRE.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Client sends a message to the server, server reads the message and prints it. Here, two classes
are being used: Socket and ServerSocket. The Socket class is used to communicate client and
server. Through this class, we can read and write message. The ServerSocket class is used at
server-side. The accept() method of ServerSocket class blocks the console until the client is
connected. After the successful connection of client, it returns the instance of Socket at server-
side.
CODE :
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept(); //establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
OUTPUT :
EXPERIMENT – 7
THEORY :
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.
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.
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
In HTML:-
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
CODE :
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
height = getSize().height;
width = getSize().width;
setName("MyApplet");
In HTML:-
THEORY :
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.
Threads can be created by using two mechanisms :
1. Implementing the Runnable Interface
2. Extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides
the run() method available in the Thread class. A thread begins its life inside
run() method. We create an object of our new class and call start() method to
start the execution of a thread. Start() invokes the run() method on the Thread
object.
3. Using runnable will give you an object that can be shared amongst multiple
threads.
CODE :-
a) RUNNABLE INTERFACE
public class Multi1 implements Runnable
{
public void run()
{
System.out.println("thread is running...through Runnable interface");
}
public static void main(String[] args)
{ Multi1 m1=new Multi1();
Thread t1 =new Thread(m1);
t1.start();
}}
b) THREAD CLASS
public class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...through Thread class");
}
public static void main(String[] args)
{
Multi t1=new Multi();
t1.start();
}}
OUTPUT :-
a) RUNNABLE INTERFACE
b) THREAD CLASS
EXPERIMENT - 9
THEORY :
An applet in Java is a specialized program designed to run within a web browser, embedded
within a webpage. Applets are Java programs specifically created to be integrated into web
pages, allowing for dynamic content generation within the browser
1) Initialization:
Class Loading: The applet’s class is loaded by the Java Virtual Machine (JVM).
Initialization: The init() method is invoked to initialize the applet. This method is called once in
the lifecycle of an applet.
Parameters: The getParameter() method retrieves any parameters specified in the HTML tag
that embeds the applet.
2) Starting:
Start Method: The start() method is called after the init() method to indicate that the applet is
starting execution.
Resuming: If an applet is stopped (using the stop() method), it can be restarted using the start()
method.
3) Running:
Running State: The applet remains in this state as long as it is visible on the web page.
User Interaction: During this phase, users can interact with the applet, and the applet can
process events and update its display as required.
4) Stopping:
Stop Method: The stop() method is called when the applet is no longer visible on the screen or
when the web page containing the applet is closed.
Cleanup: In this method, you can release resources, stop threads, or perform any cleanup
activities necessary when the applet stops.
5) Destroying:
Destroy Method: The destroy() method is invoked when the applet is about to be unloaded
from memory.
Final Cleanup: You can perform any final cleanup activities, such as releasing resources, closing
files, etc., in this method.
Methods Involved:
init(): Initializes the applet and is called when the applet is loaded.
start(): Starts the execution of the applet after it has been initialized.
stop(): Stops the applet’s execution. It is called when the applet is no longer visible or active.
destroy(): Performs any cleanup operations and is called before the applet is unloaded.
CODE :
import java.awt.*;
import java.applet.*;
/*
<applet code ="RepaintApplet" width=300 height=50>
</applet>
*/
public class RepaintApplet extends Applet implements Runnable
{
String msg = "A simple Moving Banner.";
Thread t = null;
int state;
boolean stopFlag;
public void init ()
{
setBackground (Color.cyan); // To set Background color of an Applet
setForeground (Color.red); // To set Foreground color of an Applet
}
public void start ()
{
t = new Thread (this);
stopFlag = false;
t.start ();
}
public void run ()
{
char ch;
for (;;)
{
try
{
repaint();
Thread.sleep(250);
ch = msg.charAt (0);
msg = msg.substring(1, msg.length ());
msg += ch;
if (stopFlag)
break;
}
catch (InterruptedException ie)
{
}
}
}
public void stop ()
{
stopFlag = true;
t = null;
}
public void paint (Graphics g)
{
g.drawString (msg, 50, 30);
}
}
OUTPUT :
EXPERIMENT – 10
THEORY :
A JavaBean is a Java class that should follow the following conventions:
Eg:-
JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object.
The feature can be of any Java data type, containing the classes that you define.
A JavaBean property may be read, write, read-only, or write-only. JavaBean features are
accessed through two methods in the JavaBean's implementation class:
1. getPropertyName ()
For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.
CODE :
public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}
OUTPUT :
Student Age: 10