MSC Lab Coa
MSC Lab Coa
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);
}
8| P a g e
private void createMenuBar() {
var menuBar = new JMenuBar();
var exitIcon = new ImageIcon("src/resources/exit.png");
setJMenuBar(menuBar);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
9| P a g e
An Exit icon is displayed in the menu.
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.
11| P a g e
Sol 6.2 - SUB -Menu.
package com.zetcode;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.EventQueue;
public class SubmenuEx extends JFrame {
public SubmenuEx() {
initUI();
}
createMenuBar();
setTitle("Submenu");
setSize(360, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
12| P a g e
var bookmarksMenuItem = new JMenuItem("Import bookmarks...");
var importMailMenuItem = new JMenuItem("Import mail...");
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.
13| P a g e
exitMenuItem.setToolTipText("Exit application");
A tooltip is set to the Exit menu item with the setToolTipText() method.
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
Sol 6.3 - POP- UP- Menu.
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);
15| P a g e
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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
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
JPopupMenu creates a popup menu.
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:
19| P a g e
7. Program to demonstrate JDBC in java
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);
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
//Handle errors for JDBC
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. Program to demonstrate Servlets in java
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");
24| P a g e
// service method
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
8.2 Creating deployment descriptor (web.xml)
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
9. Program to demonstrate JSP in java
<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:
29| P a g e
10. Programs to demonstrate Java Beans in java
30| P a g e
10.1 Accessing JavaBeans
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
10.2: Accessing JavaBeans Properties
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
<p>Student First Name:
</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
Part II: Web Tech
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>");
38| P a g e
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Hello, World</title></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:
42| P a g e
3. Web enabling of databases in java
Now let’s write a simple Java program just to test out some basic database concepts. Note that
this isn’t a server yet, it’s just a regular Java class.
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
public static void main(String[] args){
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
46| P a g e
3.2: For now, let’s make our program fetch results from the table: (People)
import java.sql.Connection;
import java.sql.DriverManager;
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 + ".");
47| P a g e
catch (SQLException e) {
e.printStackTrace();
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.
48| P a g e
4. Multimedia effects on web pages design using Flash in java
Animation welcome =
BasicTextAnimation.defaultFade(
label1,
2500,
"Welcome To",
Color.darkGray);
label1,
3000,
Color.darkGray);
Animation description =
BasicTextAnimations.defaultFade(
label1,
label2,
2000,
-100,
49| P a g e
4.2 Sub program :
Animation all =
Animations.sequential(new Animation[] {
Animations.pause(1000),
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