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

Final Java File

The document discusses a Java lab file submitted by a student for an Advanced Java Programming course. It includes 10 experiments covering topics like inheritance, polymorphism, exceptions, method overriding, and user defined exceptions.

Uploaded by

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

Final Java File

The document discusses a Java lab file submitted by a student for an Advanced Java Programming course. It includes 10 experiments covering topics like inheritance, polymorphism, exceptions, method overriding, and user defined exceptions.

Uploaded by

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

HMR INSTITUTE OF TECHNOLOGY AND MANAGEMENT

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

SUBMITTED TO: SUBMITTED BY:


MR. FAISAL Name – NEELIMA GUPTA
Assistant Professor Enroll No. - 05313302721
CSE Department CSE 6-B
INDEX

S.NO NAME OF EXPERIMENT EXPERIMENT SUBMISSION REMARKS/SIGN


DATE DATE
Write a Java program to

1. implement Multilevel
inheritance.
Write a Java program to

2. iimplement Polymorphism.

Write a Java program to

3. Handle the Exception Using


Try and Multiple Catch
Block.
Write a Java program to
Display Method Overriding
4.
in a Class using
Inheritance Class.
Write a Java program to

5. Handle the User Defined


Exception using Throw
Keyword.
Write a Java program to
demonstrate the concept of
6.
socket programming.
Write a Java program to
demonstrate the concept of
7.
applet programming.
Write a Java program to
demonstrate the concept of
8.
multi‐threading.
Write a Java program to

9. demonstrate the concept of


applet.
Write a Java program to

10. demonstrate the use of


Java Beans.
EXPERIMENT – 1

AIM: Write a Java program to implement Multilevel inheritance.

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

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

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 void vehicleType() {


System.out.println("Vehicle Type: Car");
}
}

class Maruti extends Car {

public Maruti() {
System.out.println("Class Maruti");
}

public void brand() {


System.out.println("Brand: Maruti");
}

public void speed() {


System.out.println("Max: 90Kmph");
}
}

public class Maruti800 extends Maruti {

public Maruti800() {
System.out.println("Maruti Model: 800");
}
public void speed() {
System.out.println("Max: 80Kmph");
}

public static void main(String args[]) {


Maruti800 obj = new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}

Output:
EXPERIMENT - 2

AIM: Write a Java program to implement Polymorphism.

THEORY:

POLYMORPHISM:- Polymorphism is considered one of the important features of Object-


Oriented Programming. Polymorphism allows us to perform a single action in different ways. In
other words, polymorphism allows you to define one interface and have multiple
implementations. The word “poly” means many and “morphs” means forms, So it means many
forms.

Types of Java Polymorphism


In Java Polymorphism is mainly divided into two types:
• Compile-time Polymorphism
• Runtime Polymorphism

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 {

// method to render a shape


public void render() {
System.out.println("Rendering Polygon...");
}
}

class Square extends Polygon {


// renders Square
public void render() {
System.out.println("Rendering Square...");
}
}

class Circle extends 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();

// create an object of Circle


Circle c1 = new Circle();
c1.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.

Exception Handling:- Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

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.

throw The "throw" keyword is used to throw an exception.

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.

Rules for Java 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:

class InvalidAgeException extends Exception


{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}

// class that uses custom exception InvalidAgeException


public class TestCustomException1
{

// method to check the age


static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}

Output:
EXPERIMENT – 6

AIM: Write a Java program to demonstrate the concept of socket programming .

THEORY:-
Java Socket Programming

Java Socket programming is used for communication between the applications running on
different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.

The client in socket programming must know two information:

1. IP Address of Server, and


2. Port number.

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 :

SERVER SIDE PROGRAMMING -

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);
}
}
}

CLIENT SIDE PROGRAMMING -


import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}
catch(Exception e){
System.out.println(e);
}
}
}

OUTPUT :
EXPERIMENT – 7

AIM: Write a Java program to demonstrate the concept of applet programming.

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.

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

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

Simple example of Applet by html file:

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

int height, width;

public void init()

height = getSize().height;

width = getSize().width;

setName("MyApplet");

public void paint(Graphics g)

g.drawRoundRect(10, 30, 120, 120, 2, 3);

In HTML:-

< applet code = "MyApplet" width=400 height=400 >

< /applet >


OUTPUT :
EXPERIMENT - 8

AIM : Write a Java program to demonstrate the concept of multi‐threading.

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

THREAD CREATION BY IMPLEMENTING THE RUNNABLE INTERFACE :


We create a new class which implements java.lang.Runnable interface and
override run() method. Then we instantiate a Thread object and call start()
method on this object.

THREAD CREATION BY 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.

THREAD CLASS VS RUNNABLE INTERFACE :


1. If we extend the Thread class, our class cannot extend any other class
because Java doesn’t support multiple inheritance. But, if we implement the
Runnable interface, our class can still extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class
because it provides some inbuilt methods like yield(), interrupt() etc. that are
not available in Runnable interface.

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

AIM : Write a Java program to demonstrate the concept of applet.

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

Applet Life Cycle in Java


The life cycle of a Java applet refers to the various stages an applet goes through from its
initialization to its termination. Understanding the applet life cycle is essential for developing
applets correctly. Here are the stages involved in the life cycle of a Java applet:

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 :

Creating a Simple Banner using Applet in Java

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

AIM : Write a Java program to demonstrate the use of Java Beans.

THEORY :
A JavaBean is a Java class that should follow the following conventions:

o It should have a no-arg constructor.


o It should be Serializable.
o It should provide methods to set and get the values of the properties, known as
getter and setter methods.

Eg:-

public class TestBean {


private String name;

public void setName(String name) {


this.name = name;
}

public String getName() {


return name;
}
}

Setter and Getter Methods in Java

Properties for setter methods:


• It should be public in nature.
• The return type a should be void.
• The setter method should be prefixed with the set.
• It should take some argument i.e. it should not be a no-arg method.

Properties for getter methods:


• It should be public in nature.
• The return type should not be void i.e. according to our requirement, return type we
have to give the return type.
• The getter method should be prefixed with get.
• It should not take any argument.

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 class StudentsBean implements java.io.Serializable {


private String firstName = null;
private String lastName = null;
private int age = 0;

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 First Name: Zara

Student Last Name: Ali

Student Age: 10

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy