Adv Java & Web programming Lab msc
Adv Java & Web programming Lab msc
import java.util.*;
class Swap
{
public static void main(String a[])
{
System.out.println("Enter the value of x and y");
Scanner sc = new Scanner(System.in);
/*Define variables*/
int x = sc.nextInt();
int y = sc.nextInt();
System.out.println("before swapping numbers: "+x +" "+ y);
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swapping: "+x +" " + y);
}
}
OUTPUT :
OUTPUT :
22
33
2| P a g e
3. Write a program to implement the exception handling using Java
OUTPUT:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
3| P a g e
4. Write a program to implement the multithreading in using java
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
} }
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
4| P a g e
Output :
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
5| P a g e
5. Write a program to get the basic file attributes using java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.sql.Timestamp;
import java.util.Date;
public class GFG {
public static void main(String args[])
throws IOException
{
// path of the file
String path = "C:/Users/elavi/Desktop/GFG_File.txt";
// creating a object of Path class
Path file = Paths.get(path);
// creating a object of BasicFileAttributes
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime Of File Is = "+ attr.creationTime());
System.out.println("lastAccessTime Of File Is = "+ attr.lastAccessTime());
System.out.println("lastModifiedTime Of File Is = "+ attr.lastModifiedTime());
System.out.println("size Of File Is = "+ attr.size());
System.out.println("isRegularFile Of File Is = "+ attr.isRegularFile());
System.out.println("isDirectory Of File Is = "+ attr.isDirectory());
System.out.println("isOther Of File Is = "+ attr.isOther());
System.out.println("isSymbolicLink Of File Is = "+ attr.isSymbolicLink());
}
}
6| P a g e
OUTPUT :
creationTime Of File Is : 2021-01-28T05:26:41.5201363Z
size Of File IS : 12
7| P a g e
6. Program to demonstrate Menus, sub Menus, Popup Menus, Shortcut Keys, Check
Boxes and Separators in java
package com.zetcode;
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public SimpleMenuEx() {
initUI();
}
private void initUI() {
createMenuBar();
setTitle("Simple menu");
setSize(350, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
setJMenuBar(menuBar);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
9| P a g e
var fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
A menu object is created with the JMenu class. The menus can be accessed via keyboard as
well. To bind a menu to a particular key, we use the setMnemonic() method. In our case, the
menu can be opened with the Alt+F shortcut.
eMenuItem.setToolTipText("Exit application");
This code line creates a tooltip for the menu item.
fileMenu.add(eMenuItem);
menuBar.add(fileMenu);
The menu item is added to the menu object and the menu object is inserted into the menubar.
setJMenuBar(menuBar);
The setJMenuBar() method sets the menubar for the JFrame container.
10| P a g e
Output.
createMenuBar();
setTitle("Submenu");
setSize(360, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
12| P a g e
impMenu.add(newsMenuItem);
impMenu.add(bookmarksMenuItem);
impMenu.add(importMailMenuItem);
fileMenu.add(newMenuItem);
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(impMenu);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
var ex = new SubmenuEx();
ex.setVisible(true);
});
}
}
This example creates a submenu and separates the groups of menu items with a menu
separator.
var impMenu = new JMenu("Import");
fileMenu.add(impMenu);
A submenu is just like any other normal menu. It is created the same way. We simply add a
menu to existing menu.
exitMenuItem.setToolTipText("Exit application");
A tooltip is set to the Exit menu item with the setToolTipText() method.
13| P a g e
var newMenuItem = new JMenuItem("New", iconNew);
This JMenuItem constructor creates a menu item with a label and an icon.
fileMenu.addSeparator();
A separator is a horizontal line that visually separates menu items. This way we can group
items into some logical places.
A separator is created with the addSeparator() method.
Output:
14| P a g e
package com.zetcode;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public PopupMenuEx() {
initUI();
createPopupMenu();
setTitle("JPopupMenu");
setSize(300, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15| P a g e
}
maximizeMenuItem.addActionListener((e) -> {
if (getExtendedState() != JFrame.MAXIMIZED_BOTH) {
setExtendedState(JFrame.MAXIMIZED_BOTH);
maximizeMenuItem.setEnabled(false);
});
popupMenu.add(maximizeMenuItem);
popupMenu.add(quitMenuItem);
addMouseListener(new MouseAdapter() {
@Override
16| P a g e
if (getExtendedState() != JFrame.MAXIMIZED_BOTH) {
maximizeMenuItem.setEnabled(true);
if (e.getButton() == MouseEvent.BUTTON3) {
});
EventQueue.invokeLater(() -> {
ex.setVisible(true);
});
The example shows a popup menu with two commands. The first command maximizes the
window, the second quits the application.
17| P a g e
var maximizeMenuItem = new JMenuItem("Maximize");
maximizeMenuItem.addActionListener((e) -> {
if (getExtendedState() != JFrame.MAXIMIZED_BOTH) {
setExtendedState(JFrame.MAXIMIZED_BOTH);
maximizeMenuItem.setEnabled(false);
});
A popup menu consists of JMenuItems. This item will maximize the frame. The
getExtendedState() method determines the state of the frame. The available states are:
NORMAL, ICONIFIED, MAXIMIZED_HORIZ, MAXIMIZED_VERT, and
MAXIMIZED_BOTH. Once the frame is maximized, we disable the menu item with
setEnabled() method.
popupMenu.add(quitMenuItem);
The menu item is inserted into the popup menu with add().
addMouseListener(new MouseAdapter() {
@Override
if (getExtendedState() != JFrame.MAXIMIZED_BOTH) {
maximizeMenuItem.setEnabled(true);
18| P a g e
if (e.getButton() == MouseEvent.BUTTON3) {
});
The popup menu is shown where we clicked with the mouse button. The getButton() method
returns which, if any, of the mouse buttons has changed state.
MouseEvent.BUTTON3 enables the popup menu only for the right mouse clicks. We enable
the maximize menu item once the window is not maximized.
Output:
import java.sql.*;
// Database credentials
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
20| P a g e
stmt = conn.createStatement();
String sql;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
//Display values
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
21| P a g e
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
22| P a g e
Output:
C:\>javac FirstExample.java
C:\>
C:\>java FirstExample
Connecting to database...
Creating statement...
C:\>
23| P a g e
8.1 Creating the index.html page
For the sake of simplicity, this page will just have a button invoke life cycle. When you will
click this button it will call LifeCycleServlet (which is mapped according to the entry in
web.xml file).
<html>
<form action="LifeCycleServlet">
<input type="submit" value="invoke life cycle servlet">
</form>
</html>
import javax.servlet.*;
import java.io.*;
// init method
config = sc;
System.out.println("in init");
// service method
24| P a g e
public void service(ServletRequest req, ServletResponse res)
res.setContenttype("text/html");
PrintWriter pw = res.getWriter();
System.out.println("in service");
// destroy method
System.out.println("in destroy");
return "LifeCycleServlet";
25| P a g e
As discussed in other posts about web.xml file we will just proceed to the creation of it in this
article.
<web-app>
<servlet>
<servlet-name>LifeCycleServlet</servlet-name>
<servlet-class>LifeCycleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LifeCycleServlet</servlet-name>
<url-pattern>/LifeCycleServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-config>
</web-app>
26| P a g e
Output:
27| P a g e
<html>
<head><title>JSPApp</title></head>
<body>
<form>
<legend><b><i>JSP Application<i><b></legend>
out.println(d.toString()); %>
</fieldset>
</form>
</body>
</html>
<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/test.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
28| P a g e
Output:
30| P a g e
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a
scripting variable that can be accessed by both scripting elements and other custom tags used
in the JSP. The full syntax for the useBean tag is as follows −
Here values for the scope attribute can be a page, request, session or application based on your
requirement. The value of the id attribute may be any value as a long as it is a unique name
among other useBean declarations in the same JSP.
<html>
<head>
<title>useBean Example</title>
</head>
<body>
</body>
</html>
OUTPUT:
31| P a g e
Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the get
methods and the <jsp:setProperty/> action to access the set methods. Here is the full syntax −
value = "value"/>
...........
</jsp:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP by the
useBean action. The property attribute is the name of the get or the set methods that should be
invoked.
Following example shows how to access the data using the above syntax −
<html>
<head>
</head>
<body>
</jsp:useBean>
32| P a g e
<jsp:getProperty name = "students" property = "firstName"/>
</p>
</p>
<p>Student Age:
</p>
</body>
</html>
OUTPUT
Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the
following result will be displayed −
Student Age: 10
33| P a g e
1. Design of the Web pages using various features of HTML and DHTML in java
<html>
<head>
<title>
DHTML with JavaScript
</title>
<script type="text/javascript">
function dateandtime()
{
alert(Date());
}
</script>
</head>
<body bgcolor="orange">
<font size="4" color="blue">
<center> <p>
Click here # <a href="#" onClick="dateandtime();"> Date and Time </a>
# to check the today's date and time.
</p> </center>
</font>
</body>
</html>
34| P a g e
OUTPUT:
35| P a g e
1.2: JavaScript in DHTML
<html>
<head>
<title>
getElementById.style.property example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the following different buttons. </p>
<script type="text/javascript">
function change_Color(newColor) {
</script>
</body>
</html>
36| P a g e
Output:
Explanation:
In the above code, we changed the color of a text by using the following syntax:
Statement: document.getElementById('demo').style.property=new_value;.
37| P a g e
2. Client server programming using servlets, ASP and JSP on the server side and java
script
// To save as "<CATALINA_HOME>\webapps\helloservlet\WEB-INF\src\mypkg\
HelloServlet.java"
package mypkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@Override
response.setContentType("text/html;charset=UTF-8");
// Allocate a output writer to write the response message into the network socket
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<body>");
out.println("</body>");
out.println("</html>");
} finally {
Compilation
// Compile the source file and place the class in the specified destination directory
------------------------------------------------------------------------------------------------------------
39| P a g e
2.1 Create a configuration file called "web.xml", and save it under "webapps\
helloservlet\WEB-INF", as follows:
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>mypkg.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>
----------------------------------------------------------------------------
40| P a g e
The "web.xml" is called web application deployment descriptor. It provides the configuration
options for that particular web application, such as defining the the mapping between URL and
servlet class.
Take note that EACH servlet requires a pair of <servlet> and <servlet-mapping> elements to
do the mapping, via an arbitrary but unique <servlet-name>. Furthermore, all the <servlet>
elements must be grouped together and placed before the <servlet-mapping> elements (as
specified in the XML schema).
Start a web browser (Firefox, IE or Chrome), and issue the following URL (as configured in
the "web.xml"). Assume that Tomcat is running in port number 8080.
http://localhost:8080/helloservlet/sayhello
41| P a g e
Output:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
try {
System.out.println("Connecting to database.");
catch (SQLException e) {
e.printStackTrace();
System.out.println("Done.");
}.
43| P a g e
Compile and run
Compile and run this class. Make sure derby.jar is on your classpath when you run this code!
jdbc:derby specifies the type of database we’re connecting to. In this case, we’re connecting to
a Derby database.
Output:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
44| P a g e
try {
System.out.println("Connecting to database.");
String connectionUrl =
"jdbc:derby:C:/Users/kevin/Desktop/DerbyDatabase";
catch (SQLException e) {
e.printStackTrace();
System.out.println("Done.");
45| P a g e
Output:
Table: People
3.2: For now, let’s make our program fetch results from the table: (People)
import java.sql.Connection;
import java.sql.DriverManager;
46| P a g e
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
try {
System.out.println("Connecting to database.");
String connectionUrl =
"jdbc:derby:C:/Users/kevin/Desktop/DerbyDatabase";
while(resultSet.next()){
System.out.println(name + " was born in " + birthYear + ". Their favorite color is " +
favoriteColor + ".");
catch (SQLException e) {
e.printStackTrace();
47| P a g e
System.out.println("Done.");
} }
Output:
Table: People
Now our program uses SQL to fetch results from our database, and it loops over those results
to print the information:
Connecting to database.
Done.
Animation welcome =
48| P a g e
BasicTextAnimation.defaultFade(
label1,
2500,
"Welcome To",
Color.darkGray);
label1,
3000,
Color.darkGray);
Animation description =
BasicTextAnimations.defaultFade(
label1,
label2,
2000,
-100,
Animation all =
Animations.sequential(new Animation[] {
Animations.pause(1000),
49| P a g e
welcome,
Animations.pause(1000),
theJGoodiesAnimation,
Animations.pause(1000),
description,
Animations.pause(1000),
features,
Animations.pause(1000),
featureList,
Animations.pause(1500),
});
Output:
50| P a g e