0% found this document useful (0 votes)
5 views48 pages

Java Programming Concepts and Examples

Uploaded by

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

Java Programming Concepts and Examples

Uploaded by

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

Contents

1. Programming in Java ............................................................................................................................ 2


1.1. Class and object ............................................................................................................................ 2
1.2. Inheritance and interface ............................................................................................................. 6
1.3. Exception Handling ..................................................................................................................... 11
1.4. Multithreading ........................................................................................................................... 12
1.5. File IO .......................................................................................................................................... 16
1.5.1. Read Into & Write From File .............................................................................................. 16
1.5.2. Zip and UnZip File ............................................................................................................... 18
2. User Interface Components with swings ........................................................................................... 20
2.1. GUI tools (Buttons, Labels, Text fields, Dialog box, Tooltips, Menus, etc.) ............................. 20
2.2. Layout Managements ................................................................................................................. 25
2.2.1. Border Layout ..................................................................................................................... 25
2.2.2. Grid Layout ......................................................................................................................... 27
2.2.3. Flow Layout ........................................................................................................................ 29
3. Events Handling .................................................................................................................................. 32
4. Database Connectivity ....................................................................................................................... 34
5. Network Programming ....................................................................................................................... 34
5.1. Working with URLs ..................................................................................................................... 34
5.2. TCP sockets ................................................................................................................................. 35
6. Servlets ............................................................................................................................................... 37
6.1. HTTP Request and Response ...................................................................................................... 37
7. Java Server Pages ............................................................................................................................... 38
7.1. JSP Basic ...................................................................................................................................... 38
7.2. Creating and Processing Forms .................................................................................................. 39
7.3. Session Management ................................................................................................................. 42
8. RMI ...................................................................................................................................................... 47
8.1. Creating and Executing RMI Application ................................................................................... 47
1. Programming in Java
1.1. Class and object

Exercise 1
Implement the following classes and test its functions.

Solution:
public class Line {
private Point BEGIN=new Point();
private Point END=new Point();

public Line(int x1,int y1,int x2,int y2){


[Link](x1);
[Link](y1);
[Link](x2);
[Link](y2);
}
public Line(Point begin, Point end) {
[Link] = begin;
[Link] = end;
}
public Point getBEGIN() {
return BEGIN;
}
public void setBEGIN(Point begin) {
[Link] = begin;
}
public Point getEND() {
return END;
}
public void setEND(Point end) {
[Link] = end;
}
public int getBEGINX() {
return [Link]();
}
public int getBEGINY() {
return [Link]();
}
public void setBEGINX(int beginx) {
[Link](beginx);
}
public void setBEGINY(int beginy) {
[Link](beginy);
}
public void setBEGINXY(int beginx,int beginy) {
[Link](beginx);
[Link](beginy);
}
public int getENDX() {
return [Link]();
}

public int getENDY() {


return [Link]();
}

public void setENDX(int endx) {


[Link](endx);
}

public void setENDY(int endy) {


[Link](endy);
}

public void setENDXY(int endx,int endy) {


[Link](endx);
[Link](endy);
}

@Override
public String toString(){
return(" Begin @("+[Link]()+","+[Link]()+") &
END @("+[Link]()+","+[Link]()+")");
}
public double getLength(){
double xDiff = [Link]()-[Link]();
double yDiff = [Link]()-[Link]();
double result = [Link]((xDiff*xDiff)+(yDiff*yDiff));
return(result);
}
}

public class Point {


private int X;
private int Y;

public Point(){

}
public Point(int x, int y) {
this.X = x;
this.Y = y;
}
public int getX() {
return X;
}

public void setX(int X) {


this.X = X;
}

public int getY() {


return Y;
}

public void setY(int Y) {


this.Y = Y;
}

@Override
public String toString(){
return("Point @ ("+[Link]()+","+[Link]()+")");
}

public class test {


public static void main(String[] args) {
Point P1 =new Point();
Point P2 =new Point(5,6);
Point P3 =new Point(7,8);
[Link]("X:"+[Link]()+",Y:"+[Link]());
[Link]("X:"+[Link]()+",Y:"+[Link]());
[Link]([Link]());
[Link]([Link]());

Line L1=new Line(1,2,3,4);


[Link]("Begin (X:"+[Link]()+",Y:"+[Link]()+")");
[Link]("END (X:"+[Link]()+",Y:"+[Link]()+")");
Line L2=new Line(P2,P3);
[Link]("Begin (X:"+[Link]()+",Y:"+[Link]()+")");
[Link]("END (X:"+[Link]()+",Y:"+[Link]()+")");
[Link](9, 8);
[Link]("Begin (X:"+[Link]()+",Y:"+[Link]()+")");
[Link]("END (X:"+[Link]()+",Y:"+[Link]()+")");
[Link]([Link]());
[Link]([Link]());
[Link]("Line 1 "+[Link]());
[Link]("Line 2 "+[Link]());
[Link]("Distance1: "+[Link]());
[Link]("Distance2: "+[Link]());
}

}
Outputs

1.2. Inheritance and interface

Exercise 2: (Inheritance & Interface)


Write a program to represent geometric shapes and some operations that can be performed on
them. The idea here is that shapes in higher dimensions inherit data from lower dimensional
shapes. For example a cube is a three dimensional square. A sphere is a three dimensional circle
and a glom is a four dimensional circle. A cylinder is another kind of three dimensional circle.
The circle, sphere, cylinder, and glom all share the attribute radius. The square and cube share
the attribute side length. There are various ways to use inheritance to relate these shapes but
please follow the inheritance described in the table below.
All shapes inherit getName() from the superclass Shape.
Specification:
Your program will consist of the following classes: Shape, Circle, Square, Cube, Sphere,

Cylinder, and Glome and two interfaces Area and Volume ([Link] and [Link] are
given below).
Your classes may only have the class variable specified in the table below and the methods
defined in the two interfaces Area and Volume. You will implement the methods specified in
the Area and Volume interfaces and have them return the appropriate value for each shape.
Class Shape will have a single public method called getName that returns a string.

Class Class Variable Constructor Extends Implements


Shape String name Shape()
Circle double radius Circle( double r, String n ) Shape Area
Square double side Square( double s, String n ) Shape Area
Cylinder double height Cylinder(double h, double r, String n ) Circle Volume
Sphere None Sphere( double r, String n ) Circle Volume
Cube None Cube( double s, String n ) Square Volume
Glome None Glome( double r, String n ) Sphere Volume

Note: the volume of a glome is 0.5(π2)r4 where r is the radius


Solution:
[Link]
public interface Area {

public double getArea();


}
[Link]
public interface Volume {

public double getVolume();

}
[Link]
public class Circle extends Shape implements Area{
private double RADIUS;

public Circle(double r,String n){


super(n);
[Link]=r;
}

public double getRADIUS() {


return RADIUS;
}

@Override
public double getArea() {
return([Link]*[Link]*[Link]);
}
}
[Link]
public class Cube extends Square implements Volume {

public Cube(double s, String n) {


super(s, n);
}

@Override
public double getVolume() {
return([Link]()*[Link]()*[Link]());
}

}
[Link]
public class Cylinder extends Circle implements Volume {
private double HEIGHT;

public Cylinder(double height, double r, String n) {


super(r, n);
[Link] = height;
}

public double getHEIGHT() {


return HEIGHT;
}

public double getVolume() {


return([Link]()*[Link]);
}
}
[Link]
public class Glome extends Sphere implements Volume{

public Glome(double r, String n) {


super(r, n);
}

@Override
public double getVolume(){
return(0.5*[Link]()*[Link]());
}
}
[Link]
public class Shape {
private String NAME;

public Shape(String s){


[Link]=s;
}

public String getNAME() {


return NAME;
}
}
[Link]
public class Sphere extends Circle implements Volume {

public Sphere(double r, String n) {


super(r, n);
}

@Override
public double getVolume() {
return(4/3*[Link]()*[Link]());
}
}
[Link]
public class Square extends Shape implements Area {
private double SIDE;

public Square(double side,String n) {


super(n);
[Link] = side;
}

public double getSIDE() {


return SIDE;
}

@Override
public double getArea() {
return([Link]()*[Link]());
}

}
[Link]
public class test {
public static void main(String[] args) {
Circle C=new Circle(5,"Circle1");
Cube Cu=new Cube(3,"Cube1");
Cylinder Cy=new Cylinder(7,6,"Cylinder1");
Sphere S=new Sphere(8,"Sphere1");
Square Sq=new Square(6,"Square1");
Glome G=new Glome(9,"Glome1");

[Link]([Link]()+" has Radius:"+[Link]()+", Area:"+[Link]());


[Link]([Link]()+" has Radius:"+[Link]()+", Volume:"+[Link]());
[Link]([Link]()+" has Height:"+[Link]()+",
Radius:"+[Link]()+", Volume:"+[Link]());
[Link]([Link]()+" has Radius:"+[Link]()+", Volume:"+[Link]());
[Link]([Link]()+" has Side:"+[Link]()+", Area:"+[Link]());
[Link]([Link]()+" has Radius:"+[Link]()+", Volume:"+[Link]());
}
}
Outputs

1.3. Exception Handling


[Link]

import [Link];

class ExceptionExample {

public static void main(String args[]) {

int a = 0, b = 0, c = 0;

Random r = new Random();

for (int i = 0; i < 10; i++) {

try {

b = [Link]();

c = [Link]();

a = 12345 / (b / c);
} catch (ArithmeticException e) {

[Link]("Division by zero");
a = 0;

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

Output

1.4. Multithreading
[Link]

public class ExtendThread extends Thread {

private int sleepTime;

public ExtendThread(String name) {

super(name);

sleepTime = (int) ([Link]() * 5000);


[Link]("Thread Name: " + getName() + " "

+ ";Sleep Time :" + sleepTime);

}
public void run() {

try {

[Link](getName() + " is going to sleep");

[Link](sleepTime);

[Link]();

} catch (Exception e)
{ [Link]([Link]());

[Link](getName()+" is done sleeping");

[Link]

public class ImplementThread implements Runnable {

private int sleepTime;

private String name;

public ImplementThread(String name) {

[Link] = name;

sleepTime = (int) ([Link]() * 5000);


[Link]("Thread Name: " + getName() + " "

+ ";Sleep Time :" + sleepTime);

@Override

public void run() {

Thread th = new Thread();

try {
[Link](getName() + " is going to sleep");

[Link](sleepTime);

} catch (Exception e)
{ [Link]([Link]());

[Link](getName() + " is done sleeping");

private String getName() {

return [Link];

[Link]

public class MultiThreadingDemo {

public static void main(String[] args) {

ExtendThread Thread1, Thread2, Thread3, Thread4;

Thread1 = new ExtendThread("Thread1");

Thread2 = new ExtendThread("Thread2");

Thread3 = new ExtendThread("Thread3");

Thread4 = new ExtendThread("Thread4");

/ ImplementThread IThread1, IThread2, IThread3, IThread4;

/ IThread1 = new ImplementThread(" IThread1");

/ IThread2 = new ImplementThread(" IThread2");

/ IThread3 = new ImplementThread(" IThread3");

/ IThread4 = new ImplementThread(" IThread4");

/ Thread obj1 = new Thread(IThread1);

/ Thread obj2 = new Thread(IThread2);

/ Thread obj3 = new Thread(IThread3);


/ Thread obj4 = new Thread(IThread4);

[Link]("Starting Threads");

[Link]();

[Link]();

[Link]();

[Link]();

/ [Link]();

/ [Link]();;

/ [Link]();

/ [Link]();

[Link]("Thread has been started");

Output
1.5. File IO
1.5.1. Read Into & Write From File

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

public class ReadFromFile {

String filelocation = "E:\\[Link]";

FileReader fr = null;

BufferedReader br = null;

public ReadFromFile() {}

public void readDateFromFile() throws IOException


{ try {

fr = new FileReader(filelocation);

br = new BufferedReader(fr);

String line="";

while ((line = [Link]()) != null) {

[Link]("line");}

} catch (FileNotFoundException ex) {


[Link]([Link]());

} finally {

if (fr != null) {

[Link]();

[Link]();

}
}}}
[Link]

import [Link];

import [Link];

import [Link];

import [Link];

public class WriteToFile {

String filelocation = "E:\\[Link]";

String outputFile = "E:\\new(copy).txt";

FileInputStream in = null;

FileOutputStream out = null;

public WriteToFile() throws IOException {}

public void writeDataToFile() throws IOException {

try {

in = new FileInputStream(filelocation);

out = new FileOutputStream(outputFile);

int size;

while ((size = [Link]()) != -1) {

[Link](size);

} catch (FileNotFoundException ex) {

[Link]([Link]());

} finally {

[Link]();

[Link]();

}
[Link]

import [Link];

public class FileIO {

public static void main(String[] args) throws IOException {


ReadFromFile rff = new ReadFromFile();

WriteToFile wrf = new WriteToFile();

try {

[Link]();

[Link]();

} catch (IOException ex)


{ [Link]([Link]()
);
}}}

1.5.2. Zip and UnZip File


[Link]

import [Link].*;

import [Link];

public class Zip {

public static void main(String[] args) throws FileNotFoundException, IOException {

FileInputStream fis = new FileInputStream("E:\\[Link]");

FileOutputStream fos = new FileOutputStream("E:\\zip");


DeflaterOutputStream dos = new DeflaterOutputStream(fos);
int data;

while((data = [Link]())!=-1){

[Link](data);

}
[Link]();

[Link]();

[Link]();

}}
[Link]

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class Unzip {

public static void main(String[] args) throws FileNotFoundException, IOException {


FileInputStream fis = new FileInputStream("E:\\zip");

FileOutputStream fos = new FileOutputStream("E:\\[Link]");

InflaterInputStream iis = new InflaterInputStream(fis); int data;

while ((data = [Link]()) != -1) {

[Link](data);

[Link]();

[Link]();

[Link]();

}
2. User Interface Components with swings
2.1. GUI tools (Buttons, Labels, Text fields, Dialog box,
Tooltips, Menus, etc.)

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link]
;

public class GUIToolsDemo extends JFrame implements ActionListener {

private JButton btnSubmit,btnCancel;

private JTextField txtName;

public GUIToolsDemo() {

super("GUIToolsDemo");

Container con = getContentPane();

[Link](new FlowLayout());

JLabel lblName= new JLabel();

[Link]("Name:");

[Link](lblName);

txtName = new JTextField("kkkk");

[Link]("Enter Name...");

[Link](true);

[Link](txtName);

JLabel lblPass= new JLabel("password");

[Link](lblPass);

JPasswordField txtPass= new JPasswordField();

[Link]("*******");

[Link](txtPass);

JLabel lblgender = new JLabel("Gender");


[Link](lblgender);

JRadioButton rdMale = new JRadioButton("Male");

JRadioButton rdFemale = new JRadioButton("Female");

ButtonGroup genderGroup = new ButtonGroup();

[Link](rdMale);

[Link](rdFemale);

[Link](rdMale);

[Link](rdFemale);

JLabel lblCourse = new JLabel("Course");

[Link](lblCourse);

String[] courses = {"java Programming ", "PHP", "ROR",


"[Link]","Python"}; JComboBox cmbCourses = new JComboBox(courses);

[Link](cmbCourses);

JLabel lblComments= new JLabel("Comments");

[Link](lblComments);

JTextArea txtComments= new JTextArea("Comments


here..."); [Link](txtComments);

btnSubmit = new JButton("Submit");

[Link](this);

btnCancel = new JButton("Cancel");

[Link](this);

[Link](btnSubmit);

[Link]("This button does nothing");

[Link](new TransferHandler("text"));

[Link](btnCancel);

JMenuBar mainMenu = new JMenuBar();

JMenu fileMenu = new JMenu("FILE");


JMenuItem newProject = new JMenuItem(" New project");

[Link](newProject);

[Link](fileMenu);

final JFileChooser fc = new JFileChooser();

FileNameExtensionFilter filter = new FileNameExtensionFilter("All Files", "*.*");

[Link](filter);

[Link](this);

JMenu editMenu = new JMenu("EDIT");

JMenuItem copy = new JMenuItem(" copy");

JMenuItem cut = new JMenuItem(" cut");

JMenuItem paste = new JMenuItem("paste");

[Link](newProject);

[Link](cut);

[Link](new ImageIcon("C:\\Users\\Prashant Gautam\\Documents\\


NetBeansProjects\\GUIToolsDemo\\src\\icons/[Link]"));

[Link](copy);

[Link](paste);

[Link](editMenu);

setJMenuBar(mainMenu);

setSize(500, 600);

setVisible(true);

public static void main(String[] args) { GUIToolsDemo guiDemo


= new GUIToolsDemo();
[Link](JFrame.EXIT_ON_CLOSE);
// TODO code application logic here

}
@Override

public void actionPerformed(ActionEvent e) {

if([Link]()==btnSubmit)

String s= [Link]();

[Link]("Submit Button is pressed");

else if([Link]()== btnCancel)

String s="Dummy text";

[Link](s);

/int a= [Link](s);
[Link]("Cancel button is pressed");

Outputs
2.2. Layout Managements
2.2.1. Border Layout
[Link]

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class BorderLayoutDemo extends JFrame implements ActionListener


{ private JButton buttons[];

private String names[] = {"HIDE NORTH", "HIDE SOUTH", "HIDE EAST","HIDE WEST", "HIDE CENTER"};

private BorderLayout layout;

public BorderLayoutDemo() {

super("BorderLayout Demo");

layout = new BorderLayout();

Container con = getContentPane();

[Link](layout);

buttons = new JButton[[Link]];

for (int i = 0; i < [Link]; i++) {

buttons[i] = new JButton(names[i]);

}
[Link](buttons[0], [Link]);

buttons[0].addActionListener(this);

[Link](buttons[1], [Link]);

buttons[1].addActionListener(this);

[Link](buttons[2], [Link]);

buttons[2].addActionListener(this);

[Link](buttons[3], [Link]);

buttons[3].addActionListener(this);

[Link](buttons[4], [Link]);

buttons[4].addActionListener(this);

setSize(400, 400);

setVisible(true);

public static void main(String[] args) { BorderLayoutDemo

app = new BorderLayoutDemo();

[Link](JFrame.EXIT_ON_CLOSE);

@Override

public void actionPerformed(ActionEvent e) {

for (int i = 0; i <= 4; i++) {

if ([Link]() == buttons[i]) {

buttons[i].setVisible(false);

}
Output

2.2.2. Grid Layout


[Link]

import [Link];

import [Link];

import [Link];

import [Link];

public class GridLayoutDemo extends JFrame {

private JButton buttons[];

private String names[] = {"Button1", "Button2", "Button3",

"Button4", "Button5","Button6", "Button7",

"Button8", "Button9"};

private GridLayout layout;


public GridLayoutDemo() {

super("Grid Layout Demo");

layout = new GridLayout(3, 3);

Container con = getContentPane();

[Link](layout);

for (int i = 0; i < [Link]; i++) {

[Link](new JButton("MyButton" + (i + 1)));

setSize(400, 400);

setVisible(true);

public static void main(String[] args) { GridLayoutDemo app =

new GridLayoutDemo();

[Link](JFrame.EXIT_ON_CLOSE);

Output
2.2.3. Flow Layout
[Link]

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class Flowlayout extends JFrame{

private JButton btnLeft,btnRight,btnCenter;

FlowLayout layout;

public Flowlayout(){

super("Flow layout demo");


Container con = getContentPane();

layout = new FlowLayout();

[Link](layout);

[Link](btnLeft = new JButton("LEFT"));

[Link](new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

[Link]([Link]);

[Link](con);

});

[Link](btnRight = new JButton("Right"));


[Link](new ActionListener()
{ @Override

public void actionPerformed(ActionEvent e) {

[Link]([Link]);

[Link](con);

});

[Link](btnCenter = new JButton("Center"));


[Link](new ActionListener()
{ @Override

public void actionPerformed(ActionEvent e) {

[Link]([Link]);

[Link](con);
}

});

setSize(400,400);

setVisible(true);

public static void main(String[] args) { Flowlayout app =


new Flowlayout();
[Link](JFrame.EXIT_ON_CLOSE);

Outputs
3. Events Handling
[Link]

public class GUIEventHandling extends JFrame implements ActionListener {

private String[] countyName = {"Nepal", "India", "USA", "Select Country"};

private JComboBox cmbCountry;

private JTextField txtCodeNumber;

private JTextField txtMobileNumber;

public GUIEventHandling() {

super("GUI EventHandling");

Container con = getContentPane();

[Link](new FlowLayout());

[Link](new JLabel("Country"));

cmbCountry = new JComboBox(countyName);

[Link]("Select Country");

[Link](this);

[Link](cmbCountry);

[Link](new JLabel("Mobile NO:"));

[Link](txtCodeNumber = new JTextField("", 3));

[Link](new JLabel("-"));

[Link](txtMobileNumber = new JTextField("", 10));

setSize(500, 500);

setVisible(true);

public static void main(String[] args)


{ GUIEventHandling App = new
GUIEventHandling();
[Link](JFrame.EXIT_ON_CLOSE);

@Override

public void actionPerformed(ActionEvent e) {

if ([Link]().equals(cmbCountry)) {

if ([Link]().toString() == "Nepal")
{ [Link]("+977");

} else if ([Link]().toString() == "India") {


[Link]("+91");

} else if ([Link]().toString() == "USA")


{ [Link]("+1");

} else {

[Link]("");

} Outputs
[Link] Connectivity

[Link] Programming
5.1. Working with URLs
[Link]
import [Link].*;
import [Link].*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new
URL("[Link]
+
"/[Link]?
name=networking#DOWNLOADIN
G");

[Link]("protocol = " +
[Link]());
[Link]("authority = " +
[Link]());
[Link]("filename = " +
[Link]()); [Link]("host
= " + [Link]());
[Link]("port = " +
[Link]());
[Link]("path
= " + [Link]());
[Link]("query = " +
[Link]());
[Link]("ref
= " + [Link]());

}
}
Output
protocol = http
authority = [Link]
host = [Link]
port = 80
path = /docs/books/tutorial/[Link]
query = name=networking
filename = /docs/books/tutorial/[Link]?
name=networking ref = DOWNLOADING

5.2. TCP sockets


[Link]

import [Link];

import [Link];

import [Link];

import [Link].*;

public class Client {

String message;

public static void main(String[] args) throws IOException {


OutputStream ostream = null;

Socket sock = null;

DataOutputStream dos = null;

String message;

try {

sock = new Socket("[Link]", 5001);

message = "Hello Server ";

ostream = [Link]();

dos = new DataOutputStream(ostream);

[Link](message);

} catch (IOException ex)


{ [Link]([Link]()
);
} finally
{ [Link](
);

[Link]();

[Link]();

[Link]

import [Link];

import [Link];

import [Link];

import [Link].*;

public class Server {

public static void main(String[] args) throws IOException {

ServerSocket serSock = null;

DataInputStream dis = null;

InputStream istream = null;

Socket cSock = null;

try {

serSock = new ServerSocket(5001);

[Link]("Server started!");

cSock = [Link]();

istream = [Link]();

dis = new DataInputStream(istream);

String msg = [Link]();

[Link]("From client :" + msg);


} catch (IOException ex)
{ [Link]([Link]()
);

} finally {

[Link]();

[Link]();

[Link]();

[Link]();

Outputs

6. Servlets
6.1. HTTP Request and Response

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
import [Link];

public class HelloServlet extends HttpServlet {

public HelloServlet(){}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException{

[Link]("text/html;charset= UTF-8");

PrintWriter write = [Link]();

[Link]("HELLO WORLD!!");

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException{

7. Java Server Pages


7.1. JSP Basic
[Link]

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</head>

<body>

<h1>Hello World!!</h1>

</body>

</html>
Output

7.2. Creating and Processing Forms


[Link]

<html>
<head>
<title>Form Handling</title>
</head>
<body>
<form method="post" action ="[Link]">
<table width="400" border="5" align="center">
<tr>
<td colspan="5" align="center"><h1>JSP form
Demo</h1></td>
</tr>
<tr>
<td>User Name:</td>
<td><input type='text' name='name'/></td>
</tr>

<tr>
<td>Phone N0:</td>
<td><input type='text' name='phone'/></td>
</tr>
<tr>

<td colspan='5' align='center'><input type=


'submit' name='submit' value='Done'/></td>

</tr>
</form>
</body>
[Link]
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>

<%--<meta http-equiv="Content-Type" content="text/html;


charset=UTF-8">--%> <title>JSP Page</title>
</head>
<body>
Name= <%= [Link]("name")%>
<br>
Phone=<%= [Link]("phone")%>
</body>
</html>
Outputs
7.3. Session Management
[Link]

<%@page import="[Link]"%>

<%

Integer visitCount = new Integer(0);

String visitCountKey = new String("Visit count");

String userID = new String("prashant");

String UserIDKey = new String("userID");

Date creationTime = new Date([Link]());

Date lastAcessTime = new Date([Link]());

if([Link]()){

[Link](UserIDKey, userID);

[Link](visitCountKey, visitCount);

visitCount= (Integer)[Link](visitCountKey);

visitCount = visitCount+1;

[Link](visitCountKey, visitCount);

creationTime = new Date([Link]());

lastAcessTime = new Date([Link]());

userID = (String)[Link](UserIDKey);

%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</head>

<body>
<form>

<table width='400' border='5' align='center'>

<tr>

<td colspan='5' align='center'><h1>SESSION INFORMATION</h1></td>

</tr>

<tr>

<td>user ID</td>

<td> <%[Link](userID);%></td>

</tr>

<tr>

<td>Session ID</td>

<td> <%[Link]([Link]());%></td>

</tr>

<tr>

<td>Creation Time</td>

<td><%[Link](creationTime);%></td>

</tr>

<tr>

<td>Last Access Time</td>

<td><%[Link](lastAcessTime);%></td>

</tr>

<tr>

<td>Number of Visits</td>

<td><%[Link](visitCount);%></td>

</tr>
<tr>

<td>GOTO:</td>

<td><a href="[Link]"> Link to next page</a></td>

</tr>

</form>

</body>

</html>

[Link]

<%

String user = (String)[Link]("userID");

if(user==null){

%>

<jsp:forward page="[Link]"></jsp:forward>

<%}%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</head>

<body>

<h1>After Session</h1>

<p> <%[Link](user);%></p>

<p><a href="[Link]">Destroy Session</a></p>


</body>

</html>
[Link]

<%

String user = (String)[Link]("userID");

if(user==null){

%>

<jsp:forward page="[Link]"></jsp:forward>

<%}%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</head>

<body>

<h1>After Session</h1>

<p> <%[Link](user);%></p>

<p><a href="[Link]">Destroy Session</a></p>

</body>

</html>
Outputs
8. RMI
8.1. Creating and Executing RMI Application

[Link]

import [Link];

public interface RMIinterface extends Remote {

public int add( int x, int y);

[Link]

import [Link];

import [Link];

public class Client {

public static void main(String[] args) {

try {

Registry reg = [Link]("[Link]",1099);

RMIinterface stub = (RMIinterface) [Link]("key");

int respons=[Link](2,5);

[Link]("SUM="+ respons);

} catch (Exception e) {

[Link]

import [Link];

import [Link];

import [Link];

public class Server implements RMIinterface{


public static void main(String[] args) {

try {

Server s = new Server();

RMIinterface stub = (RMIinterface) [Link](s,

0); Registry reg = [Link](1099); [Link]("key", stub);

[Link]("Server ready");

} catch (Exception e) {

@Override

public int add(int x, int y) {

return (x+y);

Outputs

SUM= 7

Common questions

Powered by AI

Exception handling in Java is implemented through try-catch blocks to address runtime anomalies and ensure robust program execution. In the example, a try block encloses code that could potentially cause an ArithmeticException when dividing by zero. When such an exception occurs, it is caught by the catch block, which outputs "Division by zero" and resets the variable 'a' to zero, allowing the program to continue executing without abrupt termination. This structure exemplifies how Java uses exception handling to maintain program control and data integrity even when errors occur .

Java's structure facilitates object-oriented principles by defining classes and objects that enable data encapsulation. In the Java example provided, classes and objects are central to its implementation. The 'Line' class, for example, contains private variables for points 'BEGIN' and 'END', showcasing encapsulation. The 'Point' class manages X and Y coordinates. The use of setters and getters in the 'Line' and 'Point' classes demonstrate encapsulation, allowing controlled access and modification of the data. Additionally, classes like 'Line' and 'Point' can be instantiated, which illustrates how objects are used to model real-world entities .

Remote Method Invocation (RMI) in Java is significant as it simplifies the development of distributed applications by allowing objects to invoke methods on remote systems seamlessly as if they exist locally. RMI abstracts the underlying network communication, dealing with object serialization, networking, and stream management, so developers can focus on application logic. This is exemplified in RMI applications where business logic is distributed across servers. RMI's use of stubs and skeletons for communication reduces complexity, making it easier to scale applications and integrate distributed resources efficiently .

Implementing interfaces for area and volume calculations promotes a design advantage by ensuring scalability and separation of concerns. The interfaces 'Area' and 'Volume' define 'getArea()' and 'getVolume()' methods, respectively, without providing method implementations, allowing any class implementing these interfaces to define how the calculations should be performed. For instance, 'Circle' implements 'Area', and 'Sphere' implements both 'Area' and 'Volume'. This separation allows each shape class to provide specific logic for area and volume based on its geometric properties, while also promoting consistency and reducing boilerplate code across different subclasses .

The Java File I/O API facilitates file operations through classes like FileInputStream, FileOutputStream, and buffered classes, enabling efficient reading and writing of data. In 'ReadFromFile', FileReader and BufferedReader are used to read text files line by line, while 'WriteToFile' uses FileInputStream and FileOutputStream to copy data. Potential errors such as FileNotFoundException or IOException are managed with try-catch blocks, which ensure that file streams are closed properly to prevent resource leaks. This controlled error management ensures that I/O operations do not lead to resource exhaustion or data corruption .

Using URL and sockets in Java's network programming facilitates communication between programs by enabling the exchange of data across networks. The URL class encapsulates a uniform resource locator used to access resources, allowing the parsing of components like protocol, host, path, etc. Sockets enable the creation of client-server applications, where a 'Client' socket connects to a 'Server' socket on a specified IP address and port. In the provided example, the client sends a message to the server via DataOutputStream and receives it using DataInputStream, facilitating efficient two-way communication. This capability is pivotal in building distributed applications .

Layout management in Java Swing applications plays a crucial role in determining how UI components are arranged within a container. Different layout managers, such as BorderLayout, GridLayout, and FlowLayout, provide distinct strategies for component arrangement. For instance, BorderLayout arranges components in five regions (North, South, East, West, Center), GridLayout divides the container into a grid of equal-sized cells, and FlowLayout arranges components in a directional flow based on container size and order of addition. The choice of layout manager directly impacts the visual layout and responsiveness of the application's interface .

Java's multithreading approach is designed to improve program efficiency by allowing concurrent execution paths. Threads can be created by extending the Thread class or implementing the Runnable interface. In the provided sources, threads are created by both methods, with each thread assigned a random sleep time to simulate execution delay. This concurrency model allows programs to perform multiple tasks simultaneously, such as processing I/O and computation, thereby enhancing resource utilization and responsiveness. The effectiveness of this approach is evidenced by its widespread adoption in Java applications for improved throughput and reduced latency .

Event handling in Java significantly influences user interaction by allowing the application to respond to user-generated events, such as button clicks or text changes. In the example of GUIEventHandling, ActionListener is used to detect actions such as item selection from a JComboBox. When a country is selected, the ActionListeners update the interface to reflect the corresponding country's code, demonstrating real-time interaction based on user input. This mechanism enables dynamic updates and enhances the responsiveness of Java GUI applications, making them more interactive and user-friendly .

HTTP request and response handling in Java servlets involves processing client requests and returning responses via HTTP protocol. When a client sends a request, the servlet receives it through the service method, processes the request data, and uses response objects to send data back to the client. For instance, in 'HelloServlet', data is output through PrintWriter to the response stream. This empowers developers to create dynamic, data-driven web applications as servlets efficiently manage client-server communication, utilize server-side processing capabilities, and handle concurrent user connections, resulting in scalable web solutions .

You might also like