Cse (Aiml) - Java Lab Manual
Cse (Aiml) - Java Lab Manual
DEPARTMENT
JAVA PROGRAMMING
LAB MANUAL
1. Institute Vision
2. Institute Mission
3. Department Vision
4. Department Mission
5. PEOs
6. Pos
7. PSOs
TABLE OF CONTENT
Programs:
Write a java program to illustrate the concept of class with method
1. overloading.
Write a java program that reads a line of integers, and then displays
2. each integer, and the sum of all the integers (Use String Tokenizer class
of java.util)
a) Write a Java program to illustrate the concept of single level
3. inheritance.
b) Write a Java program to illustrate the concept of Multi level
inheritance.
a) Write a java program to demonstrate the Interfaces.
4. b) Write a java program to demonstrate the Abstract Classes.
5. Write a java program to implement the concept of exception handling.
a) Write a java program to illustrate the concept of threading using
6. Thread Class.
b) Write a java program to illustrate the concept of threading using
Runnable Interface.
Write a java program to illustrate the concept of Thread
7. synchronization.
Write a java program that correctly implements producer consumer
8. problem using the concept of inter thread communication.
Write a java program to illustrate collection classes like (a) Array List,
9. (b) Linked List, (c) Tree Map, (d) Hash Map.
Write a java program to illustrate Legacy classes like (a) Vector, (b)
10. Hash table, (c) Dictionary (d) Enumeration interface.
(a) Write a java program to implement iteration over Collection using
11. Iterator Interface.
(b) Write a java program to implement iteration over Collection using
Iterator Interface.
Write a java program that reads a file name from the user, and then
12. display information about whether the file exists, whether the file is
readable, whether the file is writable, the type of file and the length of
the file in bytes.
13. Write a java program to illustrate the concept of I/O streams .
14. Write a java program to implement serialization concept
(a) Write a java applet program to implement Color class.
15. (b) Write a java applet program to implement Graphics class.
(a) Write a java applet program for handling mouse events.
16. (b) Write a java applet program for handling key events.
17. Write a java applet program to implement Adapter classes.
Write a Java program that works as a simple calculator. Use a grid
18. layout to arrange buttons for the digits and for the +, -,*, % operations.
Add a text field to display the result
19. Write an example for JDBC prepared statement with result set.
M1: To provide adequate knowledge encompassing sound technical concepts and soft
skills thereby inculcating sound ethics.
M2: To provide a conductive environment to nurture creativity in teaching- learning
process.
M3: To identify and provide opportunities for deserving students of all communities.
M4: To strive and contribute to the needs of the society and the nation by applying
advanced engineering and technical concepts.
DepartmentMission
M1: To provide a holistic learning environment for students through ethical practices.
M2: To provide quality infrastructure through practical exposure to the latest technology
requirements.
M3: To train the students in soft skills to excel in placements and competitive exams at higher
level the industry ready.
M4: To have a healthy Industry - Institute interaction through faculty development programs,
student internships, guest lectures and using latest teaching learning methodologies.
M5: To provide effective platform to meet the industrial requirement and provide research
oriented environment for the faculty to meet the continuous societal needs.
1. ProgrammeEducationObjectives
2. Problemanalysis:Identify,formulate,reviewresearchliterature,andanalyzecomplexeng
ineeringproblemsreachingsubstantiatedconclusionsusingfirstprinciplesof
mathematics,naturalsciences,andengineeringsciences.
3. Design/developmentofsolutions:Designsolutionsforcomplexengineeringproblems
and design system components or processes that meet the specified needswith
appropriate consideration for the public health and safety, and the
cultural,societal,andenvironmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledgeand
research methods including design of experiments, analysis and
interpretationofdata,andsynthesis oftheinformation to providevalid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques,
resources,andmodernengineeringandITtoolsincludingpredictionandmodeling
tocomplexengineeringactivitieswith an understandingof thelimitations.
6. The engineer and society: Apply reasoning informed by the contextual
knowledgetoassesssocietal,health,safety,legalandculturalissuesandtheconsequentresp
onsibilitiesrelevant tothe professionalengineeringpractice.
7. Environmentandsustainability:Understandtheimpactoftheprofessionalengineering
solutions in societal and environmental contexts, and demonstrate
theknowledgeof,and needfor sustainabledevelopment.
8. Ethics:Applyethicalprinciplesandcommittoprofessionalethicsandresponsibilitiesandn
orms ofthe engineeringpractice.
9. Individualandteamwork:Functioneffectivelyasanindividual,andas amemberor leader
indiverseteams,andinmultidisciplinarysettings.
10. Communication: Communicate effectively on complex engineering activities
withtheengineeringcommunityandwithsocietyatlarge,suchas,beingabletocomprehend
and write effective reports and design documentation, make
effectivepresentations,and giveandreceiveclear instructions.
11. Project management and finance: Demonstrate knowledge and understanding
oftheengineeringandmanagementprinciplesandapplythesetoone‘sownwork,asamembe
randleaderinateam,tomanageprojectsandinmultidisciplinaryenvironments.
12. Lifelong learning: Recognize the need for, and have the preparation and ability
toengageinindependentandlifelonglearninginthebroadestcontext of
technologicalchange.
ProgrammeSpecificOutcomes:
PSO1:TheITgraduateswillworkassoftwareengineersforprovidingsolutionstorealworl
dproblemsusingstructuredandobjectorientedprogramming languagesand
opensourcesoftware.
PSO2: The IT graduates will work as System engineer, Software analyst andTesterfor ITandITes
.
JAVA:Javaisahigh-levelprogramminglanguageoriginallydevelopedbySunMicrosystems and
released in 1995. Java runs on a variety of platforms, such as Windows,Mac OS, and the
various versions of UNIX. James Gosling initiated the Java language projectin June 1991 for
use in one of his many set-top box projects. The language, initially calledOak after an oak tree
that stood outside Gosling's office, also went by the name Green andendedup later
beingrenamed as Java, from alistof random words.
LaboratoryObjective
UponsuccessfulcompletionofthisLabthestudentwillbeableto:
1. UnderstandtheconceptofOOPaswellasthepurposeandusageprinciplesofinheritance,poly
morphism, encapsulation andmethod overloading.
2. Understand fundamentals of programming such as variables, conditional and
iterativeexecution,methods, etc.
3. Identify classes, objects, members of a class and the relationships among them
neededforaspecific problem.
4. Understand fundamentals of object-oriented programming in Java, including
definingclasses,invokingmethods, usingclass libraries, etc.
5. Create Java application programs using sound OOP practices (e.g., interfaces
andAPIs)andproperprogramstructuring(e.g.,byusingaccesscontrolidentifies,automaticdo
cumentationthroughcomments, errorexception handling)
6. Havethe abilityto write acomputerprogram tosolvespecifiedproblems.
7. Develop programs using the Java Collection API as well as the Java standard
classlibrary.
8. Usethe JavaSDKenvironmentto create,debugandrun simpleJavaprograms
Overview of Java
JavaIsImportanttotheInternet,TheInternethelpedcatapultJavatotheforefrontofprogramming, and
Java, in turn, has had a profound effect on the Internet. The reason for
thisisquitesimple:Javaexpandstheuniverseofobjectsthatcanmoveaboutfreelyincyberspace. In a
network, two very broad categories of objects are transmitted between theserver
andourpersonalcomputer: passiveinformationanddynamic,activeprograms.
Javacanbeusedtocreatetwotypesofprograms:applicationsandapplets.Anapplicationisa program
that runsonyourcomputer,underthe operating system of that computer.Anapplet is an
application designed to be transmitted over the Internet and executed by a Java-
compatibleWeb browser.
Featuresof JAVA
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
Highperformance
Distributed
Dynamic
JDK:
The Java Development Kit (JDK) is an implementation of either one of the Java SE, Java
EEorJavaMEplatforms.TheJDKincludesaprivateJVMandafewotherresourcestofinishthedevelopment of
aJavaApplication.
applet viewer – this tool can be used to run and debug Java applets without a
webbrowser
apt– theannotation-processingtool.
extcheck – autilitythat detectsJAR file conflicts
idlj – the IDL-to-Java compiler. This utility generates Java bindings from a
given JavaIDLfile.
jabswitch – the Java Access Bridge. Exposes assistive technologies on
MicrosoftWindowssystems.
java – the loader for Java applications. This tool is an interpreter and can interpret
theclass files generated by the javac compiler. Now a single launcher is used for
bothdevelopment and deployment. The old deployment launcher, jre, no longer
comeswithSunJDK, and instead it has been replaced bythisnewjavaloader.
javac–the Javacompiler,which convertssource codeintoJavabytecode
javadoc – the documentation generator, which automatically generates
documentationfromsourcecodecomments
jar – the archiver, which packages related class libraries into a single JAR
file. Thistoolalso helps manageJAR files.
javafxpackager–tooltopackageandsignJavaFX applications
jarsigner–thejar signingandverificationtool
javah–the Cheaderandstubgenerator, usedtowrite nativemethods
javap– the classfiledisassembler
javaws–theJavaWebStartlauncherforJNLPapplications
JConsole–JavaMonitoringand ManagementConsole
jdb–thedebugger
jhat–JavaHeapAnalysis Tool(experimental)
jinfo – This utility gets configuration information from a running Java process
orcrashdump. (experimental)
jmap – This utilityoutputs the memorymap forJavaand can print shared objectmemory
maps or heap memory details of a given process or core dump.(experimental)
jmc– JavaMission Control
jps – Java Virtual Machine Process Status Tool lists the instrumented HotSpot
JavaVirtualMachines (JVMs)on the target system. (experimental)
jrunscript–Javacommand-linescriptshell.
jstack–utilitythat printsJavastacktraces ofJavathreads(experimental)
jstat–JavaVirtualMachinestatistics monitoringtool(experimental)
jstatd–jstatdaemon(experimental)
keytool – toolformanipulatingthe keystore
pack200–JAR compressiontool
policytool – the policy creation and management tool, which can determine policy
fora Java runtime, specifying which permissions are available for code from
varioussources
VisualVM – visual tool integrating several command-line JDK tools and
lightweightperformance and memoryprofilingcapabilities
wsimport–generatesportable JAX-WSartifactsforinvokinga webservice.
xjc–Partofthe JavaAPIforXMLBinding(JAXB)API.Itaccepts
anXMLschemaandgenerates Javaclasses.
1. DataTypes usedinJDK
Eachrowcontainsthedatatypeandsizeandrangeofthedatatype.Thelistofavailabledatatypes inJava
isshownin table below
float 32 1.4e−045to3.4e+038
double 64 4.9e–324to1.8e+308
Char 2 0 to 65,536
Boolean 1 Trueorfalse
1. Security
Aswearelikelyaware,everytimethatwedownloada―normal‖program,weareriskinga viral
The key that allows Java to solve both the security and the portability problems just
describedis that the output of a Java compiler is not executable code. Rather, it is bytecode.
Bytecode isa highly optimized set of instructions designed to be executed by the Java run-time
system,which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM
is aninterpreter for bytecode. This may come as a bit of a surprise. Translating a Java program
intobytecode helps makes it much easier to run a program in a wide variety of environments.
Thereasonis straightforward:onlythe
JVM needs to be implemented for eachplatform. Once therun-time package existsfor
agivensystem,anyJavaprogramcanrunonit.BecausetheexecutionofeveryJavaprogramis under
the control of the JVM, the JVM can contain the program and prevent it fromgenerating side
effects outside of the system. When a program is interpreted, it generally
runssubstantiallyslower thanit wouldrun ifcompiled to executablecode.
2. SystemRequirement
HardwareConfiguration
SystemConfiguration:WindowsXP,IntelXeon3.0GHzCPU,Cache,1GBD
DRRAM
SoftwareConfiguration
/Google Chrome
2. PATHandCLASSPATH
SettingPATHandCLASSPATHenvironmentvariablesonMicrosoftWindows,Solaris,andLinuxar
easfollows.
Program-1:Write a java program to illustrate the concept of class with method overloading.
class Overloading
obj.sum(20,20,20);
Output:
import java.util.*;
class StringTokenizerDemo {
int n;
int sum = 0;
String s = sc.nextLine();
while (st.hasMoreTokens())
n = Integer.parseInt(temp);
System.out.println(n);
sum = sum + n;
sc.close();
Output:
Program-3:
(a) Write a Java program to illustrate the concept of single level inheritance.
class Employee
float sal=60000;
float b=1500;
Output:
(b) Write a Java program to illustrate the concept of Multi level inheritance.
class Shape {
System.out.println("Inside display");
System.out.println("Inside area");
}
public class Tester
{
cube.display();
cube.area();
cube.volume();
}
}
Output:
Program-4:
interface Printable{
void print();
}
interface Showable{
void show();
}
}
Output:
Program-6:
(a) Write a java program to illustrate the concept of threading using Thread Class.
threadName = name;
try
{
Thread.sleep(50);
}
catch (InterruptedException e)
{
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
T1.start();
T2.start();
}
}
Output:
(b) Write a java program to illustrate the concept of threading using Runnable Interface
}
}
Program-8: Write a java program that correctly implements producer consumer problem
using the concept of inter thread communication.
public class ProducerConsumerTest {
p1.start();
c1.start();
}
}
class CubbyHole {
try {
wait();
} catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value)
{
while (available == true) {
try {
wait();
}
}
contents = value;
available = true;
notifyAll();
cubbyhole = c;
this.number = number;
}
public void run()
{
int value = 0;
}
}
}
class Producer extends Thread
{
this.number = number;
}
public void run()
{
for (int i = 0; i < 10; i++)
{
cubbyhole.put(i);
try
{
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}
Output:
import java.util.*;
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
import java.util.*;
class TreeMap1{
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
Output:
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
(b) Hashtable:
import java.util.*;
class HashtableExample
{
public static void main(String args[])
{
Hashtable<Integer,String> student = new Hashtable<Integer, String>();
student.put(new Integer(101), "Emma");
student.put(new Integer(102), "Adele");
student.put(new Integer(103), "Aria");
student.put(new Integer(104), "Ally");
Set dataset = student.entrySet();
Iterator iterate = dataset.iterator();
while(iterate.hasNext())
{
Map.Entry map=(Map.Entry)iterate.next();
System.out.println(map.getKey()+" "+map.getValue());
}
}
}
(c) Dictionary:
import java.util.*;
public class DictionaryExample
{
public static void main(String[] args)
{
// Initializing Dictionary object
Dictionary student = new Hashtable();
}
}
Output:
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester
{
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements())
{
System.out.println(days.nextElement());
}}
Output:
// return Head
public Node<T> getHead()
{
return head;
}
// return Tail
public Node<T> getTail()
{
return tail;
}
// implement if needed
public void remove()
{
throw new UnsupportedOperationException();
}
}
public T getData()
// Driver class
class Main {
public static void main(String[] args)
{
// Create Linked List
List<String> myList = new List<>();
// Add Elements
myList.add("abc");
myList.add("mno");
myList.add("pqr");
myList.add("xyz");
Output:
Program-12: Write a java program that reads a file name from the user, and then display
information about whether the file exists, whether the file is readable, whether the file is
writable, the type of file and the length of the file in bytes.
import java.io.*;
import java.util.*;
class AboutFile{
if(f.exists())
else
if(f.exists()){
if(f.canRead())
else
if(f.canWrite())
else
}
Output:
import java.io.*;
public class SimpleIO
{
}
while (c != '0');
}
}
Input:
Output:
// Default constructor
public Emp(String name, int age, int a, int b)
{
this.name = name;
this.age = age;
this.a = a;
this.b = b;
}
// Serialization
try {
Output:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <APPLET CODE ="ColorClass.class" WIDTH=300 HEIGHT=200></APPLET> */
public class ColorClass extends Applet implements ItemListener
{
Choice l;
public void init()
{
l=new Choice();
l.addItem("Black");
l.addItem("Blue");
l.addItem("Cyan");
if(l.getSelectedItem()=="White")
{
setBackground(Color.white);
}
if(l.getSelectedItem()=="Yellow")
{
setBackground(Color.yellow);
}
}
}
Output:
Output:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE ="AppletKeyboard.class" WIDTH=300 HEIGHT=200></APPLET>
*/
public class AppletKeyboard extends Applet implements KeyListener
{
TextField t,tt,tp,tr;
public void init()
{
t=new TextField(20);
t.addKeyListener(this);
tt=new TextField(70);
tp=new TextField(70);
tr=new TextField(70);
add(t);
add(tt);
add(tr);
add(tp);
}
public void keyTyped(KeyEvent e)
{
tt.setText("key Released"+e.getKeyChar());
}
public void keyReleased(KeyEvent e)
Output:
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}
}
Output:
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.ORANGE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}
Output:
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
Output:
Program-18:Write a Java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -,*, % operations. Add a text field to display the
result.
/Program for implementing a Simple Calculator
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Calculator1" width=300 height=300></applet>*/
public class Calculator1 extends Applet implements ActionListener
{
TextField t;
Button b[]=new Button[15];
Button b1[]=new Button[6];
String op2[]={"+","-","*","%","=","C"};
String str1="";
int p=0,q=0;
String oper;
public void init()
{
setLayout(new GridLayout(5,4));
t=new TextField(20);
setBackground(Color.pink);
setFont(new Font("Arial",Font.BOLD,20));
int k=0;
t.setEditable(false);
t.setBackground(Color.white);
t.setText("0");
for(int i=0;i<10;i++)
{
b[i]=new Button(""+k);
add(b[i]);
for(int i=0;i<6;i++)
{
b1[i]=new Button(""+op2[i]);
add(b1[i]);
b1[i].setBackground(Color.pink);
b1[i].addActionListener(this);
}
add(t);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("+")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("-")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("*")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("%")){ p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
}
else if(str.equals("=")) { str1="";
if(oper.equals("+")) {
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p+q)));}
else if(oper.equals("-")) {
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p-q))); }
else if(oper.equals("*")){
q=Integer.parseInt(t.getText());
else if(oper.equals("%")){
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p%q))); }
}
else{ t.setText(str1.concat(str));
str1=t.getText();
}
Output:
Program-19: Write an example for JDBC prepared statement with result set.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
Program-20:Program to get primary key value (auto-generated keys) from inserted queries
using JDBC
Step 1: creating a tableclass.
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
public class RetrievingData_AutoIncrement_Pstmt {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sample_database";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
Program-24:
1. Write servlet application to print current date and time.
Step-1 code program
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
<web-app>
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
// variables
PrintWriter pw = null;
int langCode = 0;
String creators[] = null;
// creators
creators = new String[] {
"Dennis Ritchie", "Bjarne Stroustrup",
"James Gosling", "Guido van Rossum"};
// get PrintWriter
pw = resp.getWriter();
// result
pw.println("<h1 style='text-align:center'>Creator Name is:: "+
creators[langCode] + "</h1>");
// link to home
pw.println("<h3><a href='page.html'>HOME</a></h3>");
// close stream
pw.close();
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}
Step-3: create xml directory file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation=
"http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_4_0.xsd"
id="WebApp_ID" version="4.0">
<display-name>LanguageApp</display-name>
<welcome-file-list>
<welcome-file>page.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>lang</servlet-name>
<servlet-class>com.kp.servlet.LangServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>lang</servlet-name>
<url-pattern>/langurl</url-pattern>
</servlet-mapping>
</web-app>
Output:
<html>
<head>
<!--
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
//-->
</script>
</head>
<body onload = "JavaScript:AutoRefresh(5000);">
</body>
</html>
Output:
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#e5f7c0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#eadf8c\">\n" +
"<th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
Output:
First output
Basic programs:
Program-1 factorial program using recursion.
class FactorialExample2{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]){
int i,fact=1;
int number=4;//It is the number to calculate factorial
fact = factorial(number);
System.out.println("Factorial of "+number+" is: "+fact);
}
Program-6:
import java.util.Scanner;
public class SwapTwoNumbersExample1
{
public static void main(String args[])
{
int a, b;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
Beyond syllabus:
Program-1: ATM program
//import required classes and packages
import java.util.Scanner;
while(true)
{
System.out.println("Automated Teller Machine");
System.out.println("Choose 1 for Withdraw");
System.out.println("Choose 2 for Deposit");
System.out.println("Choose 3 for Check Balance");
System.out.println("Choose 4 for EXIT");
System.out.print("Choose the operation you want to perform:");
//check whether the balance is greater than or equal to the withdrawal amount
if(balance >= withdraw)
{
//remove the withdrawl amount from the total balance
balance = balance - withdraw;
System.out.println("Please collect your money");
}
else
{
//show custom error message
System.out.println("Insufficient Balance");
}
System.out.println("");
break;
case 2:
case 3:
//displaying the total balance of the user
System.out.println("Balance : "+balance);
System.out.println("");
break;
case 4:
//exit from the menu
System.exit(0);
}
}
}
}
Output:
//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;
System.out.println();
//Initialize matrix a
int a[][] = {
{4, 1, 3},
{3, 5, 7},
{8, 2, 6}
};
//This loop prints all the subsets formed from the string.
System.out.println("All subsets for given string are: ");
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
Output: