0% found this document useful (0 votes)
35 views39 pages

Java Programming Lab Manual

This lab manual outlines the Java programming curriculum for Dhruv Rai, a BSC.IT student at Amity Institute of Information Technology. It includes modules covering various topics such as data types, classes, inheritance, exceptions, and GUI building, along with code examples and outputs for practical understanding. The manual serves as a comprehensive guide for students to learn and apply Java programming concepts.

Uploaded by

ashurai24033
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views39 pages

Java Programming Lab Manual

This lab manual outlines the Java programming curriculum for Dhruv Rai, a BSC.IT student at Amity Institute of Information Technology. It includes modules covering various topics such as data types, classes, inheritance, exceptions, and GUI building, along with code examples and outputs for practical understanding. The manual serves as a comprehensive guide for students to learn and apply Java programming concepts.

Uploaded by

ashurai24033
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

LAB MANUAL

NAME- DHRUV RAI


ENROLL NO- A71004924018
COURSE/BATCH- [Link](SEM-3)/2024-2027
DEPARTMENT- AMITY INSTITUTE OF
INFORMATION TECHNOLOGY
SUBJECT- JAVA PROGRAMMING

INDEX
MODULE -01

1. Datatypes in Java
2. If Else Demo
3. For Loop Demo
4. Math Class in Java
5. Switch Case
6. If Else Ladder Demo

MODULE-02

1. Class & Object


2. Constructor
3. Method Overloading
4. Static Keyword
5. Final Keyword
6. Transient Keyword

MODULE-03

1. Applet
2. Abstract Class
3. File Handling
4. Inheritance
5. Interfaces

MODULE-04

1. Exceptions- Checked, Unchecked, Generics and Enums


2. Building GUI using AWT, Swing & Event Handling
3. Threads and Multithreading

MODULE-05

1. Creating web applications using Servlets

MODULE-01

1. Datatypes in Java
CODE-

public class P1

public static void main(String[] args)

int a, b, c;

double x,y,z;

char A='A';

String s="Good Afternoon!";

a=25;

b=30;

c=a+b;

x=25; y=38;

z=x+y;

[Link]("Integer Datatype of Addition of "+a+ " & " +b+" is " + c);

[Link]("Double Datatype Addition of "+x+ " & " +y+" is " + z);

[Link]("Character Datatype" + A);

[Link]("String Datatype Demo " + s);

OUTPUT-

Integer Datatype of Addition of 25 & 30 is 55

Double Datatype Addition of 25.0 & 38.0 is 63.0

Character Datatype A

String Datatype Demo Good Afternoon!

2. If Else Demo

CODE-
public class P2

public static void main(String[] args)

int x,y,z;

x=50;

y=40;

if(x<y)

z=x+y;

[Link]("Addition of "+x+" and "+y+" is "+z);

else

z=x-y;

[Link]("Subtraction of "+x+" and "+y+" is "+z);

OUTPUT-

Subtraction of 50 and 40 is 10

3. For Loop Demo

CODE-
public class P3

public static void main(String[] args)

int i,j=0,k;

for(i=0;i<=5;i++)

j=j+i;

[Link]("Value of J:"+j);

OUTPUT-

Value of J:0

Value of J:1

Value of J:3

Value of J:6

Value of J:10

Value of J:15

4. Math Class in Java

CODE-
public class MathDemo

public static void main(String[] args)

int a,b;

double x,y;

a=20;

b=-134;

x=22.450;

y=0.456;

[Link]("3 x 3 x 3 x 3 = " + [Link](3, 4));

[Link]("Pi is " + [Link]);

[Link]("e is " + Math.E);

[Link]("min(" + x + "," + y + ") is " + [Link](y, y));

[Link]("pow(2.0, 2.0) is " + [Link](2.0, 2.0));

[Link]("Here's one random number: " + [Link]());

OUTPUT-

3 x 3 x 3 x 3 = 81.0

Pi is 3.141592653589793

e is 2.718281828459045

min(22.45,0.456) is 0.456

pow(2.0, 2.0) is 4.0

Here's one random number: 0.47880985371906903

5. Switch Case

CODE-
public class switchdemo

public static void main(String[] args)

int day = 5;

switch(day) {

case 0:

[Link]("Today is Sunday."); break;

case 1:

[Link]("Today is Monday."); break;

case 2:

[Link]("Today is Tuesday."); break;

case 3:

[Link]("Today is Wednesday."); break;

case 4:

[Link]("Today is Thursday."); break;

case 5:

[Link]("Today is Friday."); break;

default:

[Link]("Today is Saturday.");

OUTPUT-

Today is Friday.

6. If Else Ladder Demo

CODE-
public class ifLadder

public static void main(String[] args)

String month = "March";

if(month == "January")

[Link]("It\'s January");

else if (month == "February")

[Link]("It\'s February");

else if (month == "March")

[Link]("It\'s March");

else if (month == "April")

[Link]("It\'s April");

else if (month == "May")

[Link]("It\'s May");

OUTPUT-

It's March

MODULE-02

1. Classes and Object


CODE-

class Box {

double w;

double h;

double d;

class MathOp {

void display() {

[Link]("I am in the MathOp Class");

public class BoxDemo {

public static void main(String[] args) {

Box mybox = new Box();

MathOp M = new MathOp();

double vol;

mybox.w = 10;

mybox.h = 20;

mybox.d = 30;

vol = mybox.w * mybox.h * mybox.d;

[Link]("Volume is : " + vol);

[Link]();

}
OUTPUT-

Volume is : 6000.0

I am in the MathOp Class

2. Constructors

CODE-

class Book

int pages;

double price;

String author;

Book()

[Link]("Constructing Book Construction!!");

pages= 146;

price = 250;

author = "Yeshwant Kanetkar";

[Link]("Author of the Book is :"+author);

[Link]("Price of the Book is :"+price);

[Link]("Pages of the are :"+pages);

Book(int pgs, double p, String a) {

pages=pgs ;

price= p;

author=a;

[Link]("Author of the Book is :"+author);


[Link]("Price of the Book is :"+price);

[Link]("Pages of the are :"+pages);

class ConstructorDemo

public static void main(String args[])

// declare, allocate, and initialize Box objects

Book b1 = new Book();

Book b2 = new Book(210,400.00,"Cal Newport");

OUTPUT-

Constructing Book Construction!!

Author of the Book is :Yeshwant Kanetkar

Price of the Book is :250.0

Pages of the Book are :146

Author of the Book is :Cal Newport

Price of the Book is :400.0

Pages of the Book are :210

3. Method Overloading

CODE-
class OverloadDemo

void test()

[Link]("No parameters");

// Overload test for one integer parameter.

void test(int a) {

[Link]("a: " + a);

// Overload test for two integer parameters.

void test(int a, int b) {

[Link]("a and b: " + a + " " + b);

// overload test for a double parameter

double test(double a) {

[Link]("double a: " + a);

return a*a;

class Overload {

public static void main(String args[]) {

OverloadDemo ob = new OverloadDemo();

double result;

// call all versions of test()

[Link]();

[Link](10);

[Link](10, 20);

result = [Link](123.25);
[Link]("Result of [Link](123.25): " + result);

OUTPUT-

No parameters

a: 10

a and b: 10 20

double a: 123.25

Result of [Link](123.25): 15188.5625

4. Static keyword

CODE-

class staticDemo

static int a=30;

static int b;

int d;

static

[Link]("Static Block initialized!!");

b=a*5;

//d=a+b;

public static void main(String[] args)

[Link]("From Main!!");

[Link]("Value of a :"+a);
[Link]("Value of b :"+b);

}}

OUTPUT-

Static Block initialized!!

From Main!!

Value of a :30

Value of b :150

5. Final Keyword

CODE-

class Animal {

void breathe()

//final void breathe()

[Link]("Breathing in Animal Class"); }

class Fish extends Animal

public void breathe()

int a=5;

[Link]("Bubbling in Fish Class");

a=a*5;

[Link]("Value of Variable A"+a);

class Test

int x;
public void demo(int i)

this.x=i;

[Link](x);

public class finalDemo

public static void main(String[] args)

[Link]("Creating an animal...");

Animal a = new Animal();

[Link]();

[Link]("Creating a lungfish...");

Fish f = new Fish();

[Link]();

Test t=new Test();

[Link](5);

OUTPUT-

Creating an animal...

Breathing in Animal Class

Creating a lungfish...

Bubbling in Fish Class

Value of Variable A: 25

6. Transient Keyword

CODE-
// Java program to demonstrate transient keyword

// Filename [Link]

import [Link].*;

class transientDemo implements Serializable

// Normal variables

int i = 10, j = 20;

// Transient variables

transient int k = 30;

// Use of transient has no impact here

transient static int l = 40;

transient final int m = 50;

public static void main(String[] args) throws Exception

transientDemo input = new transientDemo();

// serialization

FileOutputStream fos = new FileOutputStream("[Link]");

ObjectOutputStream oos = new ObjectOutputStream(fos);

[Link](input);

// de-serialization

FileInputStream fis = new FileInputStream("[Link]");

ObjectInputStream ois = new ObjectInputStream(fis);

transientDemo output = (transientDemo)[Link]();

[Link]("i = " + output.i);


[Link]("j = " + output.j);

[Link]("k = " + output.k);

[Link]("l = " + output.l);

[Link]("m = " + output.m);

OUTPUT-

i = 10

j = 20

k=0 ← transient → not serialized

l = 40 ← static → not serialized, value remains

m = 50 ← final → compiler inlines the value

MODULE-03

1. Applet

CODE-

interface Callback

void callback(int param);

class Client implements Callback {

// Implement Callback's interface

public void callback(int p) {

[Link]("callback called with " + p);

}
class TestIface {

public static void main(String args[]) {

Callback c = new Client();

[Link](42);

OUTPUT-

callback called with 42

2. Abstract Class

Code-

// A Simple demonstration of abstract.

abstract class A {

abstract void callme();

// concrete methods are still allowed in abstract classes

void callmetoo() {

[Link]("This is a concrete method.");

class B extends A {

void callme() {

[Link]("B's implementation of callme.");

class AbstractDemo {

public static void main(String args[]) {

B b = new B();

[Link]();
[Link]();

Output-

B's implementation of callme.

This is a concrete method.

3. File Handling
(1)Creating new file in java
(2) import [Link];
(3) import [Link];
(4)
(5) public class CreateFile
(6) {
(7) public static void main(String[] args)
(8) {
(9)
(10) try {
(11) File Obj = new File("[Link]");
(12)
(13) // Creating File
(14) if ([Link]()) {
(15) [Link]("File created: " + [Link]());
(16) }
(17) else {
(18) [Link]("File already exists.");
(19) }
(20) }
(21)
(22) // Exception Thrown
(23) catch (IOException e) {
(24) [Link]("An error has occurred.");
(25) [Link]();
(26) }
(27) }
(28) }
(2) Editing file in java

import [Link];

import [Link];

public class WriteFile

public static void main(String[] args)

{
// Writing Text File

try {

FileWriter Writer = new FileWriter("[Link]");

// Writing File

[Link]("Do not use Cellphones in the Class!!");

[Link]();

[Link]("Successfully written.");

// Exception Thrown

catch (IOException e) {

[Link]("An error has occurred.");

[Link]();

4. Inheritance

// Create a superclass.

class A {

int i, j;

void showij() {

[Link]("i and j: " + i + " " + j);

}
// Create a subclass by extending class A.

class B extends A {

int k;

void showk() {

[Link]("k: " + k);

void sum() {

[Link]("i + j + k: " + (i + j + k));

public class SimpleInheritance {

public static void main(String args[]) {

A superOb = new A();

B subOb = new B();

// The superclass may be used by itself.

superOb.i = 10;

superOb.j = 20;

[Link]("Contents of superOb:");

[Link]();

[Link]();

/* The subclass has access to all public members

of its superclass. */

subOb.i = 7;
subOb.j = 8;

subOb.k = 9;

[Link]("Contents of subOb:");

[Link]();

[Link]();

[Link]();

[Link]("Sum of i, j and k in subOb:");

[Link]();

OUTPUT-

Contents of superOb:

i and j: 10 20

Contents of subOb:

i and j: 7 8

k: 9

Sum of i, j and k in subOb:

i + j + k: 24

5. Interfaces

CODE-

interface Callback {

void callback(int param);

void draw();

double getArea();
}

class Client implements Callback {

private double radius;

// optional: constructor to set radius

Client(double radius) {

[Link] = radius;

public void callback(int p) {

[Link]("callback called with " + p);

public void draw() {

[Link]("Drawing a Circle!!");

public double getArea() {

return [Link] * radius * radius;

public class TestIface {

public static void main(String args[]) {

Client c = new Client(5.0); // radius = 5

[Link](42);

[Link]();
[Link]("Area: " + [Link]());

OUTPUT-

callback called with 42

Drawing a Circle!!

Area: 78.53981633974483

MODULE-04

1. Exceptions- Checked, Unchecked, Generics and Enums

CODE-

class ExceptionHandlingDemo

public static void main(String args[]) {

int d, a;

try {

// monitor a block of code.

d = 0;

a = 42 / d;

[Link]("This will not be printed.");

catch (ArithmeticException e) {

// catch divide-by-zero error

[Link]("Division by zero.");

[Link]("After catch statement.");

OUTPUT-
Division by zero.

After catch statement.

1. Building GUI using AWT, Swing & Event Handling

J BUTTON

// Demonstrate an icon-based JButton.

import [Link].*;

import [Link].*;

import [Link].*;

/*

<applet code="JButtonDemo" width=250 height=450>

</applet>

*/

public class JButtonDemo extends JApplet

implements ActionListener {

JLabel jlab;

public void init() {

try {

[Link](

new Runnable() {

public void run() {

makeGUI();

);

} catch (Exception exc) {

[Link]("Can't create because of " + exc);

}
private void makeGUI() {

// Change to flow layout.

setLayout(new FlowLayout());

// Add buttons to content pane.

ImageIcon france = new ImageIcon("[Link]");

JButton jb = new JButton(france);

[Link]("India");

[Link](this);

add(jb);

ImageIcon germany = new ImageIcon("[Link]");

jb = new JButton(germany);

[Link]("USA");

[Link](this);

add(jb);

ImageIcon italy = new ImageIcon("[Link]");

jb = new JButton(italy);

[Link]("China");

[Link](this);

add(jb);

ImageIcon japan = new ImageIcon("[Link]");

jb = new JButton(japan);

[Link]("Europe");

[Link](this);

add(jb);

// Create and add the label to content pane.

jlab = new JLabel("Choose a Flag");

add(jlab);
}

// Handle button events.

public void actionPerformed(ActionEvent ae) {

[Link]("You selected " + [Link]());

CHECKBOX

// Demonstrate JCheckbox.

import [Link].*;

import [Link].*;

import [Link].*;

/*

<applet code="JCheckBoxDemo" width=270 height=50>

</applet>

*/

public class JCheckBoxDemo extends JApplet

implements ItemListener {

JLabel jlab;

public void init() {

try {

[Link](

new Runnable() {

public void run() {

makeGUI();

);

} catch (Exception exc) {

[Link]("Can't create because of " + exc);


}

private void makeGUI() {

// Change to flow layout.

setLayout(new FlowLayout());

// Add check boxes to the content pane.

JCheckBox cb = new JCheckBox("C");

[Link](this);

add(cb);

cb = new JCheckBox("C++");

[Link](this);

add(cb);

cb = new JCheckBox("Java");

[Link](this);

add(cb);

cb = new JCheckBox("Perl");

[Link](this);

add(cb);

// Create the label and add it to the content pane.

jlab = new JLabel("Select languages");

add(jlab);

// Handle item events for the check boxes.

public void itemStateChanged(ItemEvent ie) {

JCheckBox cb = (JCheckBox)[Link]();

if([Link]())

[Link]([Link]() + " is selected");

else

[Link]([Link]() + " is cleared");


}

TEXTFIELD

// Demonstrate JTextField.

import [Link].*;

import [Link].*;

import [Link].*;

public class JTextFieldDemo extends JApplet {

JTextField jtf;

public void init() {

try {

[Link](

new Runnable() {

public void run() {

makeGUI();

);

} catch (Exception exc) {

[Link]("Can't create because of " + exc);

private void makeGUI() {

// Change to flow layout.

setLayout(new FlowLayout());

// Add text field to content pane.

jtf = new JTextField(15);


add(jtf);

[Link](new ActionListener() {

public void actionPerformed(ActionEvent ae) {

// Show text when user presses ENTER.

showStatus([Link]());

});

/*

<applet code="JTextFieldDemo" width=300 height=50>

</applet>

*/

2. THREAD & MULTITHREADING

THREAD

// Create a second thread.

class NewThread implements Runnable {

Thread t;

NewThread() {

// Create a new, second thread

t = new Thread(this, "Demo Thread");

[Link]("Child thread: " + t);

[Link](); // Start the thread

// This is the entry point for the second thread.

public void run() {

try {
for(int i = 5; i > 0; i--) {

[Link]("Child Thread: " + i);

[Link](1500);

} catch (InterruptedException e) {

[Link]("Child interrupted.");

[Link]("Exiting child thread.");

class ThreadDemo {

public static void main(String args[]) {

new NewThread(); // create a new thread

try {

for(int i = 5; i > 0; i--) {

[Link]("Main Thread: " + i);

[Link](1500);

} catch (InterruptedException e) {

[Link]("Main thread interrupted.");

[Link]("Main thread exiting.");

MULTITHREADING

// Create multiple threads.

class NewThread implements Runnable {

String name; // name of thread

Thread t;
NewThread(String threadname) {

name = threadname;

t = new Thread(this, name);

[Link]("New thread: " + t);

[Link](); // Start the thread

// This is the entry point for thread.

public void run() {

try {

for(int i = 5; i > 0; i--) {

[Link](name + ": " + i);

[Link](1000);

} catch (InterruptedException e) {

[Link](name + "Interrupted");

[Link](name + " exiting.");

class MultiThreadDemo {

public static void main(String args[]) {

new NewThread("One"); // start threads

new NewThread("Two");

new NewThread("Three");

try {

// wait for other threads to end

[Link](10000);

} catch (InterruptedException e) {

[Link]("Main thread Interrupted");


}

[Link]("Main thread exiting.");

MODULE-05

Creating web application using Servlets

Aim: Demonstrating Servlet and doGet() and doPost() method.

1. Start Eclipse IDE.


2. To develop a dynamic web project, we need to set the Java Environment
to Java EE.
3. To achieve that, Go to Windoe-> Perscpective->Open Perspective-
>Other in the Eclipse IDE.

4. Select Java EE Perspective from other and open it.


5. Once the Java EE perspective is selected the Dynamic Web Project
option is available in File->New->Dynamic Web Project.
6. Create a new Dynamic Web Project with the name TestProject in the
window and click on Finish. A new Dynamic web project is created with
the name as TestProject.

7. To create a JSP page ([Link]), Right click on the WEB_INF folder


and select New->JSP file to create a User Interface.
8. A new jsp file [Link] is created in the webapp folder. Write
the following code in the [Link] file.
[Link]

<%@ page language="java" contentType="text/html; charset=ISO-8859- 1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">

<title>Insert title here</title>


</head>
<body>
<form method="get" action="TestServlet">

<pre>
Enter Your Name: <input type="text" name=tname><br>
Enter Your Address: <input type="text" name=tadd><br>

<input type=submit> <input type=reset>

</pre>
</form>
</body>
</html>

The above jsp page will take the input from the user in the textboxes and on the
click of a submit button will call the TestServlet using the get method. The
doGet() method in the servlet will process the input coming from the textboxes.

9. Next, create a servlet “TestServlet” by right clicking on src/main/java


folder and write the following code.
[Link]
import [Link]; import
[Link]; import
[Link];
import [Link]; import
[Link]; import
[Link];
import [Link];

/**

* Servlet implementation class TestServlet


*/
public class TestServlet extends HttpServlet { private
static final long serialVersionUID = 1L;

/**

* @see HttpServlet#HttpServlet()
*/
public TestServlet() { super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
[Link]().append("Served at:
").append([Link]());
String sname=[Link]("tname"); String
sadd=[Link]("tadd"); PrintWriter
pw=[Link]();
[Link]("<h1>Hello, Mr/MS :"+sname+"</h1><br>");
[Link]("<h1>Hello, Mr/MS :"+sadd+"</h1>");
}

/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub doGet(request,
response);
}

The doGet() method in the servlet will process the input from the textboxes and
display the output.

10. Run the file [Link] by right clicking and selecting the Run as
option and selecting Tomcat as the Server.
11. The [Link] file will run on selected web browser.

***

You might also like