0% found this document useful (0 votes)
16 views85 pages

Cse (Aiml) - Java Lab Manual

The Java Programming Lab Manual outlines the curriculum and objectives for students in the Computer Science Department at NSAKCET, focusing on various Java programming concepts and applications. It includes a list of programming exercises, institutional and departmental visions and missions, as well as program educational objectives and outcomes. The manual emphasizes the importance of Java in modern programming and provides an overview of the Java Development Kit and its components.

Uploaded by

tahuraabid1331
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)
16 views85 pages

Cse (Aiml) - Java Lab Manual

The Java Programming Lab Manual outlines the curriculum and objectives for students in the Computer Science Department at NSAKCET, focusing on various Java programming concepts and applications. It includes a list of programming exercises, institutional and departmental visions and missions, as well as program educational objectives and outcomes. The manual emphasizes the importance of Java in modern programming and provides an overview of the Java Development Kit and its components.

Uploaded by

tahuraabid1331
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
You are on page 1/ 85

COMPUTER SCIENCE AND ENGINEERING

DEPARTMENT
JAVA PROGRAMMING

LAB MANUAL

Computer science Department (NSAKCET)


Java Programming Lab Manual

S.NO. CONTENTS PAGE.NO

1. Institute Vision

2. Institute Mission

3. Department Vision

4. Department Mission

5. PEOs

6. Pos

7. PSOs

8. Introduction to Java Programming Laboratory

TABLE OF CONTENT

Computer science Department (NSAKCET)


Java Programming Lab Manual

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.

Computer science Department (NSAKCET)


Java Programming Lab Manual
20. Program to get primary key value (auto-generated keys) from inserted
queries using JDBC
21. Program to create simple JList
22. Java program to create a simple checkbox using JCheck Box
23. Program to create checkbox and itemListener to it.
24. 1. Write servlet application to print current date and time.
2. Html and servlet communication.
3. Auto refresh a page.
4. Demonstrate session tracking.
5. Application for login page.
6. Application for login page.
7. Insert record into database.
8. Count the visits on web page.
9. Insert teacher record in database.

Computer science Department (NSAKCET)


Java Programming Lab Manual
Vision of the Institution:

To impart quality technical education with strong ethics, producing


technically sound engineers capable of serving the society and the nation in a
responsible manner.

Mission of the Institution:

 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.

Computer science Department (NSAKCET)


Java Programming Lab Manual
DepartmentVision

To produce quality IT professionals, with an ability to adapt to ever changing IT needs of


local, national and international arena, through effective teaching & learning, interactions with
alumni and industry.

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.

Computer science Department (NSAKCET)


Java Programming Lab Manual

1. ProgrammeEducationObjectives

1. Graduates will demonstrate technical competence and leadership in


theirchosen fields of employment by identifying, formulating, analyzing
andcreating efficientITsolutions.
2. Graduates will communicate effectively as individuals or team membersand
besuccessfulin variedworking environment.
3. Graduateswilldemonstratelifelonglearningthroughcontinuingeducationandpro
fessional development.
4. Graduates will be successful in providing viable and sustainable
solutionswithinsocietal,professional,environmentaland ethicalcontext

Computer science Department (NSAKCET)


Java Programming Lab Manual
6.ProgrammeOutcomes:
1. Engineeringknowledge:Applytheknowledgeofmathematics,science,engineeringfund
amentalsandanengineeringspecializationtothesolutionofcomplexengineeringproblems.

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.

Computer science Department (NSAKCET)


Java Programming Lab Manual

ProgrammeSpecificOutcomes:

PSO1:TheITgraduateswillworkassoftwareengineersforprovidingsolutionstorealworl
dproblemsusingstructuredandobjectorientedprogramming languagesand
opensourcesoftware.

PSO2: The IT graduates will work as System engineer, Software analyst andTesterfor ITandITes
.

Computer science Department (NSAKCET)


Java Programming Lab Manual

Introduction to JAVA Programming Laboratory

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.

Computer science Department (NSAKCET)


Java Programming Lab Manual

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.

TheJDKhasas itsprimarycomponentsacollectionofprogrammingtools, including:

 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)

Computer science Department (NSAKCET)


Java Programming Lab Manual

 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

Name Width Range

byte 8 –128 to 127

short 16 –32,768 to 32,767

int 32 –2,147,483,648 to 2,147,483,647

long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

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

Computer science Department (NSAKCET)


Java Programming Lab Manual
infection. Prior to Java, most users did not download executable programs frequently,and those
who did scan them for viruses prior to execution. Even so, most users still worriedabout the
possibility of infecting their systems with a virus. In addition to viruses, anothertype of
malicious program exists that must be guarded against. This type of program
cangatherprivateinformation,suchascreditcardnumbers,bankaccountbalances,andpasswords, by
searching the contents of your computer‘s local file system. Java answers bothof these
concernsby providing a ―firewall‖between a networked application and our computer.
When we use a Java-compatible Web browser, we can safely download Java applets
withoutfear of viral infection or malicious intent. Java achieves thisprotection by confining a
Javaprogram to the Java execution environment and not allowing it access to other parts of
thecomputer.
The ability to download applets with confidence that no harm will be done and that nosecurity
will be breached is considered by many to be the single most important aspect ofJava.

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

JDK Software Version: - JDK1.7 Version:

7.1.7.0 40Browser: InternetExplorer

/Google Chrome

2. PATHandCLASSPATH
SettingPATHandCLASSPATHenvironmentvariablesonMicrosoftWindows,Solaris,andLinuxar
easfollows.

Computer science Department (NSAKCET)


Java Programming Lab Manual
InstalltheJavaDevelopmentKit(JDK)software.
Afterinstallingthe software, the JDKdirectorywill havethe structureshown below.

Thebin directorycontains both the compilerand thelauncher.


UpdatethePATHEnvironmentVariable(MicrosoftWindows)
We can run Java applications just fine without setting thePATH environment variable.
Or,wecan optionallyset it as a convenience.
Set the PATH environment variable if we want to be able to conveniently run the
executables(javac.exe, java.exe, javadoc.exe, and so on) from any directory without having to
type thefull path of the command.If we do not set the PATH variable, we needto specify the
fullpath to the executableeverytimewerun it, suchas:
C:\Java\jdk1.7.0\bin\javacMyClass.java
ThePATHenvironmentvariableisaseriesofdirectoriesseparatedbysemicolons(;).Microsoft
Windows looks for programs in the PATH directories in order, from left to right.We should
have only one bin directory for the JDK in the path at a time (those following
thefirstareignored), soif oneisalreadypresent,wecanupdate that particularentry.
The following is an example of a PATH environment variable:C:\Java\jdk1.7.0\bin;C:\
Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem
ItisusefultosetthePATHenvironmentvariablepermanentlysoitwillpersistafterrebooting. To make
a permanent change to the PATH variable, use the System icon in theControlPanel.
Thepreciseprocedurevaries dependingon the version ofWindows:
WindowsXP
1. SelectStart,selectControlPanel.doubleclickSystem,andselecttheAdvanced
tab.
2. Click Environment Variables. In the section System Variables, find the
PATHenvironmentvariable andselectit.ClickEdit. If
thePATHenvironmentvariabledoesnot exist, clickNew.
3. In the Edit System Variable(or NewSystem Variable) window, specify the
valueofthePATHenvironmentvariable.ClickOK.Closeallremainingwindowsbyclicking
OK.
4. Eclipse IDE.
5. Netbeans IDE.

Program-1:Write a java program to illustrate the concept of class with method overloading.

class Overloading

Computer science Department (NSAKCET)


Java Programming Lab Manual
{

void sum(int a,long b){System.out.println(a+b);}

void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){

Overloading obj=new Overloading();

obj.sum(20,20);//now second int literal will be promoted to long

obj.sum(20,20,20);

Output:

Computer science Department (NSAKCET)


Java Programming Lab Manual
Program-2:Write a java program that reads a line of integers, and then displays each integer, and
the sum of all the integers (Use String Tokenizer class of java.util.

import java.util.*;

class StringTokenizerDemo {

public static void main(String args[]) {

int n;

int sum = 0;

Scanner sc = new Scanner(System.in);

System.out.println("Enter integers with one space gap:");

String s = sc.nextLine();

StringTokenizer st = new StringTokenizer(s, " ");

while (st.hasMoreTokens())

String temp = st.nextToken();

n = Integer.parseInt(temp);

System.out.println(n);

sum = sum + n;

System.out.println("sum of the integers is: " + sum);

sc.close();

Computer science Department (NSAKCET)


Java Programming Lab Manual

Output:

Program-3:

(a) Write a Java program to illustrate the concept of single level inheritance.

class Employee

float sal=60000;

class Main extends Employee

float b=1500;

float temp= sal + b;

public static void main(String args[])

Main ob=new Main();

System.out.println("Salary amount is:"+ob.sal);

System.out.println(" Extra Bonous is:"+ob.temp);

Computer science Department (NSAKCET)


Java Programming Lab Manual
}

Output:

(b) Write a Java program to illustrate the concept of Multi level inheritance.
class Shape {

public void display()


{

System.out.println("Inside display");

class Rectangle extends Shape


{

public void area()


{

System.out.println("Inside area");

Computer science Department (NSAKCET)


Java Programming Lab Manual

class Cube extends Rectangle


{
public void volume()
{
System.out.println("Inside volume");

}
public class Tester
{

public static void main(String[] arguments)


{
Cube cube = new Cube();

cube.display();

cube.area();

cube.volume();
}

}
Output:

Program-4:

Computer science Department (NSAKCET)


Java Programming Lab Manual
(a) Write a java program to demonstrate the Interfaces.

interface Printable{
void print();
}

interface Showable{
void show();
}

class A7 implements Printable,Showable{

public void print(){System.out.println("Hello");}


public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:

(b) Write a java program to demonstrate the Abstract Classes

abstract class Shape{


abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user

Computer science Department (NSAKCET)


Java Programming Lab Manual
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}

class Circle1 extends Shape{


void draw(){System.out.println("drawing circle");}
}

//In real scenario, method is called by programmer or user


class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() method
s.draw();
}
}
Output:

Program-5:Write a java program to implement the concept of exception handling.

public class JavaExceptionExample{


public static void main(String args[]){
try{
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}

}
Output:

Computer science Department (NSAKCET)


Java Programming Lab Manual

Program-6:
(a) Write a java program to illustrate the concept of threading using Thread Class.

class ThreadDemo extends Thread


{
private Thread t;

private String threadName;

ThreadDemo( String name)


{

threadName = name;

System.out.println("Creating " + threadName );

public void run()


{
System.out.println("Running " + threadName );

try
{

for(int i = 4; i > 0; i--)

Computer science Department (NSAKCET)


Java Programming Lab Manual
{

System.out.println("Thread: " + threadName + ", " + i);

Thread.sleep(50);

}
catch (InterruptedException e)
{

System.out.println("Thread " + threadName + " interrupted.");

System.out.println("Thread " + threadName + " exiting.");

public void start ()


{
System.out.println("Starting " + threadName );

if (t == null)
{
t = new Thread (this, threadName);

t.start ();
}
}

public class TestThread


{

public static void main(String args[])


{
ThreadDemo T1 = new ThreadDemo( "Thread-1");

T1.start();

Computer science Department (NSAKCET)


Java Programming Lab Manual
ThreadDemo T2 = new ThreadDemo( "Thread-2");

T2.start();
}
}
Output:

(b) Write a java program to illustrate the concept of threading using Runnable Interface

class MultiThread implements Runnable {

public void run() {


for (int i = 0; i < 10; i++) {
System.out.println("Thread " + Thread.currentThread().getId()+ " is running");
}
}
}

public class JavaApplication4 {

public static void main(String[] args) {


Thread object = new Thread(new MultiThread());
object.start();
for (int i = 0; i < 10; i++) {
System.out.println("Main Thread id: " + Thread.currentThread().getId());
}
}
}

Computer science Department (NSAKCET)


Java Programming Lab Manual
Output:

Program-7: Write a java program to illustrate the concept of Thread synchronization.

//example of java synchronized method


class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

Computer science Department (NSAKCET)


Java Programming Lab Manual
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronization2{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:

Program-8: Write a java program that correctly implements producer consumer problem
using the concept of inter thread communication.
public class ProducerConsumerTest {

public static void main(String[] args) {

CubbyHole c = new CubbyHole();

Computer science Department (NSAKCET)


Java Programming Lab Manual

Producer p1 = new Producer(c, 1);

Consumer c1 = new Consumer(c, 1);

p1.start();

c1.start();

}
}

class CubbyHole {

private int contents;

private boolean available = false;

public synchronized int get() {

while (available == false) {

try {

wait();

} catch (InterruptedException e) {
}

}
available = false;

notifyAll();

return contents;

}
public synchronized void put(int value)
{
while (available == true) {

try {

wait();
}

Computer science Department (NSAKCET)


Java Programming Lab Manual
catch (InterruptedException e) { }

}
contents = value;

available = true;

notifyAll();

class Consumer extends Thread


{
private CubbyHole cubbyhole;

private int number;

public Consumer(CubbyHole c, int number) {

cubbyhole = c;

this.number = number;

}
public void run()
{
int value = 0;

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


{
value = cubbyhole.get();

System.out.println("Consumer #" + this.number + " got: " + value);

}
}

}
class Producer extends Thread
{

private CubbyHole cubbyhole;

Computer science Department (NSAKCET)


Java Programming Lab Manual
private int number;

public Producer(CubbyHole c, int number)


{
cubbyhole = c;

this.number = number;

}
public void run()
{
for (int i = 0; i < 10; i++)
{
cubbyhole.put(i);

System.out.println("Producer #" + this.number + " put: " + i);

try
{
sleep((int)(Math.random() * 100));

} catch (InterruptedException e) {
}
}
}

}
Output:

Program-9:Write a java program to illustrate collection classes like.


(a) Array List:

import java.util.*;

Computer science Department (NSAKCET)


Java Programming Lab Manual
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:

(b) Linked list:

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:

Computer science Department (NSAKCET)


Java Programming Lab Manual

(c) Tree map

import java.util.*;

class TreeMap1{

public static void main(String args[]){

TreeMap<Integer,String> map=new TreeMap<Integer,String>();

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:

Computer science Department (NSAKCET)


Java Programming Lab Manual
(d) Hash map:

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:

Program-10:Write a java program to illustrate Legacy classes like


(a) Vector:
import java.util.*;
public class VectorExample
{
public static void main(String[] args)
{
Vector<String> vec = new Vector<String>();
vec.add("Emma");
vec.add("Adele");
vec.add("Aria");
vec.add("Aidan");
vec.add("Adriana");
vec.add("Ally");
Enumeration<String> data = vec.elements();
while(data.hasMoreElements())
{

Computer science Department (NSAKCET)


Java Programming Lab Manual
System.out.println(data.nextElement());
}
}
}
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());
}
}
}

Computer science Department (NSAKCET)


Java Programming Lab Manual
Output:

(c) Dictionary:

import java.util.*;
public class DictionaryExample
{
public static void main(String[] args)
{
// Initializing Dictionary object
Dictionary student = new Hashtable();

// Using put() method to add elements


student.put("101", "Emma");
student.put("102", "Adele");
student.put("103", "Aria");
student.put("104", "Ally");
student.put("105", "Paul");

//Using the elements() method


for (Enumeration enum1 = student.elements(); enum1.hasMoreElements();)
{
System.out.println("The data present in the dictionary : " + enum1.nextElement());
}

// Using the get() method


System.out.println("\nName of the student 101 : " + student.get("101"));
System.out.println("Name of the student 102 : " + student.get("102"));

//Using the isEmpty() method


System.out.println("\n Is student dictionary empty? : " + student.isEmpty() + "\n");

// Using the keys() method

Computer science Department (NSAKCET)


Java Programming Lab Manual
for (Enumeration enum2 = student.keys(); enum2.hasMoreElements();)
{
System.out.println("Ids of students: " + enum2.nextElement());
}

// Using the remove() method


System.out.println("\nDelete : " + student.remove("103"));
System.out.println("The name of the deleted student : " + student.get("123"));

System.out.println("\nThe size of the student dictionary is : " + student.size());

}
}

Output:

(d) Enumeration interface:

import java.util.Vector;

import java.util.Enumeration;
public class EnumerationTester
{

public static void main(String args[])


{
Enumeration days;

Vector dayNames = new Vector();

Computer science Department (NSAKCET)


Java Programming Lab Manual

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:

Computer science Department (NSAKCET)


Java Programming Lab Manual
Program-11: Write a java program to implement iteration over Collection using.
(a) Iterator interface:
import java.util.Iterator;

// Custom Linked List class using Generics


class List<T> implements Iterable<T> {
Node<T> head, tail;

// add new Element at tail of the linked list in O(1)


public void add(T data)
{
Node<T> node = new Node<>(data, null);
if (head == null)
tail = head = node;
else {
tail.setNext(node);
tail = node;
}
}

// return Head
public Node<T> getHead()
{
return head;
}

// return Tail
public Node<T> getTail()
{
return tail;
}

// return Iterator instance


public Iterator<T> iterator()
{
return new ListIterator<T>(this);
}
}

class ListIterator<T> implements Iterator<T> {


Node<T> current;

// initialize pointer to head of the list for iteration


public ListIterator(List<T> list)
{

Computer science Department (NSAKCET)


Java Programming Lab Manual
current = list.getHead();
}

// returns false if next element does not exist


public boolean hasNext()
{
return current != null;
}

// return current data and update pointer


public T next()
{
T data = current.getData();
current = current.getNext();
return data;
}

// implement if needed
public void remove()
{
throw new UnsupportedOperationException();
}
}

// Constituent Node of Linked List


class Node<T> {
T data;
Node<T> next;
public Node(T data, Node<T> next)
{
this.data = data;
this.next = next;
}

// Setter getter methods for Data and Next Pointer


public void setData(T data)
{
this.data = data;
}

public void setNext(Node<T> next)


{
this.next = next;
}

public T getData()

Computer science Department (NSAKCET)


Java Programming Lab Manual
{
return data;
}

public Node<T> getNext()


{
return next;
}
}

// 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");

// Iterate through the list using For Each Loop


for (String string : myList)
System.out.println(string);
}
}

Output:

(b) List Iterator interface:

// Java program to show the usage of Iterator()


import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

Computer science Department (NSAKCET)


Java Programming Lab Manual
public class JavaIteratorExample1 {
public static void main(String[] args)
{
// create a list
List<String> list = new LinkedList<>();
list.add("Welcome");
list.add("to");
list.add("GFG");

System.out.println("The list is given as : "+ list);

// get the iterator on the list


Iterator<String> itr = list.iterator();

// Returns true if there are more number of


// elements.
while (itr.hasNext()) {
// Returns the next element.
System.out.println(itr.next());
}

// Removes the last element.


itr.remove();
System.out.println("After the remove() method is called : "+ list);
}
}
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.*;

Computer science Department (NSAKCET)


Java Programming Lab Manual

class AboutFile{

public static void main(String[] args){

Scanner input = new Scanner(System.in);

System.out.print("Enter the name of the file:");

String file_name = input.nextLine();

File f = new File(file_name);

if(f.exists())

System.out.println("The file " +file_name+ " exists");

else

System.out.println("The file " +file_name+ " does not exist");

if(f.exists()){

if(f.canRead())

System.out.println("The file " +file_name+ " is readable");

else

System.out.println("The file " +file_name+ " is not readable");

if(f.canWrite())

System.out.println("The file " +file_name+ " is writeable");

else

System.out.println("The file " +file_name+ " is not writeable");

System.out.println("The file type is: " +file_name.substring(file_name.indexOf('.')+1));

System.out.println("The Length of the file:" +f.length());

Computer science Department (NSAKCET)


Java Programming Lab Manual

}
Output:

Program-13: write a java program to illustrate the concept of I/O streams.


// Java code to illustrate standard
// input output streams

import java.io.*;
public class SimpleIO
{

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

// InputStreamReader class to read input


InputStreamReader inp = null;

// Storing the input in inp


inp = new InputStreamReader(System.in);

System.out.println("Enter characters, "+ " and '0' to quit.");


char c;
do {
c = (char)inp.read();
System.out.println(c);

}
while (c != '0');

}
}
Input:

Computer science Department (NSAKCET)


Java Programming Lab Manual

Output:

Program-14: Write a java program to implement serialization concept.


// Java code for serialization and deserialization
// of a Java object
import java.io.*;

class Emp implements Serializable {


private static final long serialversionUID =129348938L;
transient int a;
static int b;
String name;
int age;

// Default constructor
public Emp(String name, int age, int a, int b)
{
this.name = name;
this.age = age;
this.a = a;
this.b = b;
}

public class SerialExample {

Computer science Department (NSAKCET)


Java Programming Lab Manual
public static void printdata(Emp object1)
{

System.out.println("name = " + object1.name);


System.out.println("age = " + object1.age);
System.out.println("a = " + object1.a);
System.out.println("b = " + object1.b);
}

public static void main(String[] args)


{
Emp object = new Emp("ab", 20, 2, 1000);
String filename = "shubham.txt";

// Serialization
try {

// Saving of object in a file


FileOutputStream file = new FileOutputStream
(filename);
ObjectOutputStream out = new ObjectOutputStream
(file);

// Method for serialization of object


out.writeObject(object);
out.close();
file.close();
System.out.println("Object has been serialized\n"+ "Data before Deserialization.");
printdata(object);
// value of static variable changed
object.b = 2000;
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
object = null;
// Deserialization
try {
// Reading the object from a file
FileInputStream file = new FileInputStream
(filename);
ObjectInputStream in = new ObjectInputStream
(file);
// Method for deserialization of object
object = (Emp)in.readObject();
in.close();

Computer science Department (NSAKCET)


Java Programming Lab Manual
file.close();
System.out.println("Object has been deserialized\n"+ "Data after Deserialization.");
printdata(object);
// System.out.println("z = " + object1.z);
}

catch (IOException ex) {


System.out.println("IOException is caught");
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException" +" is caught");
}
}
}

Output:

Program-15: Write a java applet program to implement.


(a) Colour class

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");

Computer science Department (NSAKCET)


Java Programming Lab Manual
l.addItem("Dark Gray");
l.addItem("Gray");
l.addItem("Green");
l.addItem("Light Gray");
l.addItem("Magenta");
l.addItem("Orange");
l.addItem("Pink");
l.addItem("Red");
l.addItem("White");
l.addItem("Yellow");
add(l);
l.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
if(l.getSelectedItem()=="Black")
{
setBackground(Color.black);
}
if(l.getSelectedItem()=="Blue")
{
setBackground(Color.blue);
}
if(l.getSelectedItem()=="Cyan")
{
setBackground(Color.cyan);
}
if(l.getSelectedItem()=="Dark Gray")
{
setBackground(Color.darkGray);
}
if(l.getSelectedItem()=="Gray")
{
setBackground(Color.gray);
}
if(l.getSelectedItem()=="Green")
{
setBackground(Color.green);
}
if(l.getSelectedItem()=="Light Gray")
{
setBackground(Color.lightGray);

Computer science Department (NSAKCET)


Java Programming Lab Manual
}
if(l.getSelectedItem()=="Magenta")
{
setBackground(Color.magenta);
}
if(l.getSelectedItem()=="Orange")
{
setBackground(Color.orange);
}
if(l.getSelectedItem()=="Red")
{
setBackground(Color.red);
}
if(l.getSelectedItem()=="Pink")
{
setBackground(Color.pink);
}

if(l.getSelectedItem()=="White")
{
setBackground(Color.white);
}
if(l.getSelectedItem()=="Yellow")
{
setBackground(Color.yellow);
}
}
}
Output:

(b) Graphics class:


*/
import java.awt.*;
import java.applet.*;
/*

Computer science Department (NSAKCET)


Java Programming Lab Manual
<applet code="Rectanlge" width=300 Height=300>
</applet>
*/
public class Rectanlge extends Applet
{
public void paint(Graphics g)
{
g.drawRect(10,10,60,50);
g.fillRect(100,100,100,0);
g.drawRoundRect(190,10,60,50,15,15);
g.fillRoundRect(70,90,140,100,30,40);
}
}

Output:

Program-16: Write a java applet program for handling.


(a) Mouse events:
/Program to implement mouse events
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

Computer science Department (NSAKCET)


Java Programming Lab Manual

public class Mouseevents extends Applet implements MouseListener,MouseMotionListener


{
/*<applet code="Mouseevents" width=500 height=300></applet>*/
String msg="";
int mousex=0,mousey=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me)


{
mousex=0;
mousey=10;
msg="mouse clicked";
repaint();
}

public void mouseEntered(MouseEvent me)


{
mousex=0;
mousey=10;
msg="mouse entered";
repaint();
}

public void mouseExited(MouseEvent me)


{
mousex=0;
mousey=10;
msg="mouse exited";
repaint();
}

public void mousePressed(MouseEvent me)


{
mousex=me.getX();
mousey=me.getY();
msg="down";
repaint();
}

Computer science Department (NSAKCET)


Java Programming Lab Manual

public void mouseReleased(MouseEvent me)


{
mousex=me.getX();
mousey=me.getY();
msg="up";
repaint();
}

public void mouseDragged(MouseEvent me)


{
mousex=me.getX();
mousey=me.getY();
msg="*";
showStatus("Dragging mouse at "+mousex+" , "+mousey);
repaint();
}

public void mouseMoved(MouseEvent me)


{
showStatus("mouse moving at "+me.getX()+" , "+me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg,mousex,mousey);
}
}
Output:

Computer science Department (NSAKCET)


Java Programming Lab Manual

(b) Key events:

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)

Computer science Department (NSAKCET)


Java Programming Lab Manual
{
tr.setText("key Released"+e.getKeyChar());
}
public void keyPressed(KeyEvent e)
{
int kc;
String s;
kc=e.getKeyCode();
s=e.getKeyText(kc);
tp.setText("Key Pressed"+s);
}
}

Output:

Program-17:Write a java applet program to implement Adapter classes.


(a) Mouse adapter
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);

f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {

Computer science Department (NSAKCET)


Java Programming Lab Manual
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}

public static void main(String[] args) {


new MouseAdapterExample();
}
}
Output:

(b) Windows adapter:


import java.awt.*;
import java.awt.event.*;
public class AdapterExample{
Frame f;
AdapterExample(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});

f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new AdapterExample();
}
}
Output:

Computer science Department (NSAKCET)


Java Programming Lab Manual

(c) Mouse motion adapter:


import java.awt.*;
import java.awt.event.*;
public class MouseMotionAdapterExample extends MouseMotionAdapter{
Frame f;
MouseMotionAdapterExample(){
f=new Frame("Mouse Motion Adapter");
f.addMouseMotionListener(this);

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:

Computer science Department (NSAKCET)


Java Programming Lab Manual

(d) Java key adapter


import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter{
Label l;
TextArea area;
Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);

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());
}

public static void main(String[] args) {


new KeyAdapterExample();
}
}

Output:

Computer science Department (NSAKCET)


Java Programming Lab Manual

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]);

Computer science Department (NSAKCET)


Java Programming Lab Manual
k++;
b[i].setBackground(Color.pink);
b[i].addActionListener(this);
}

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());

Computer science Department (NSAKCET)


Java Programming Lab Manual
t.setText(String.valueOf((p*q))); }

else if(oper.equals("%")){
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p%q))); }
}

else if(str.equals("C")){ p=0;q=0;


t.setText("");
str1="";
t.setText("0");
}

else{ t.setText(str1.concat(str));
str1=t.getText();
}

Output:

Program-19: Write an example for JDBC prepared statement with result set.

Computer science Department (NSAKCET)


Java Programming Lab Manual

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCExample {


static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Employees";
static final String UPDATE_QUERY = "UPDATE Employees set age=? WHERE id=?";

public static void main(String[] args) {


// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement stmt = conn.prepareStatement(UPDATE_QUERY);
){

// Bind values into the parameters.


stmt.setInt(1, 35); // This would set age
stmt.setInt(2, 102); // This would set ID

// Let us update age of the record with ID = 102;


int rows = stmt.executeUpdate();
System.out.println("Rows impacted : " + rows );

// Let us select all the records and display them.


ResultSet rs = stmt.executeQuery(QUERY);

// Extract data from result set


while (rs.next()) {
// Retrieve by column name
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();

Computer science Department (NSAKCET)


Java Programming Lab Manual
}
}
}
Output:

Program-20:Program to get primary key value (auto-generated keys) from inserted queries
using JDBC
Step 1: creating a tableclass.

CREATE TABLE Sales(


ID INT PRIMARY KEY AUTO_INCREMENT,
ProductName VARCHAR (20),
CustomerName VARCHAR (20),
DispatchDate date,
DeliveryTime time,
Price INT,
Location VARCHAR(20)
);
Step 2: Following JDBC program inserts 3 records into the Sales table (created above) using
Prepared Statement, retrieves and displays the auto-incremented values generated by it.

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");

Computer science Department (NSAKCET)


Java Programming Lab Manual
System.out.println("Connection established......");
//Query to Insert values to the sales table
String insertQuery = "INSERT INTO Sales (ProductName, CustomerName, DispatchDate,
DeliveryTime, Price, Location) VALUES (?, ?, ?, ?, ?, ?)";
//Creating a PreparedStatement object
PreparedStatement pstmt =
con.prepareStatement(insertQuery,Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, "Key-Board");
pstmt.setString(2, "Raja");
pstmt.setDate(3, new Date(1567315800000L));
pstmt.setTime(4, new Time(1567315800000L));
pstmt.setInt(5, 7000);
pstmt.setString(6, "Hyderabad");
pstmt.addBatch();
pstmt.setString(1, "Earphones");
pstmt.setString(2, "Roja");
pstmt.setDate(3, new Date(1556688600000L));
pstmt.setTime(4, new Time(1556688600000L));
pstmt.setInt(5, 2000);
pstmt.setString(6, "Vishakhapatnam");
pstmt.addBatch();
pstmt.setString(1, "Mouse");
pstmt.setString(2, "Puja");
pstmt.setDate(3, new Date(1551418199000L));
pstmt.setTime(4, new Time(1551418199000L));
pstmt.setInt(5, 3000);
pstmt.setString(6, "Vijayawada");
pstmt.addBatch();
//Executing the batch
pstmt.executeBatch();
//Auto-incremented values generated by the current PreparedStatement object
ResultSet res = pstmt.getGeneratedKeys();
System.out.println("Auto-incremented values of the column ID generated by the current
PreparedStatement object: ");
while (res.next()) {
System.out.println(res.getString(1));
}
}
}
Output:

Computer science Department (NSAKCET)


Java Programming Lab Manual

Program-21: Program to create simple JList.


import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}}
Output:

Computer science Department (NSAKCET)


Java Programming Lab Manual

Program-22: Java program to create a simple checkbox using JCheck Box.


import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:

Computer science Department (NSAKCET)


Java Programming Lab Manual
Program-23: Program to create checkbox and itemListener to it.
/ importing necessary packages
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample2
{
// constructor to initialize
CheckboxExample2() {
// creating the frame
Frame f = new Frame ("CheckBox Example");
// creating the label
final Label label = new Label();
// setting the alignment, size of label
label.setAlignment(Label.CENTER);
label.setSize(400,100);
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100, 150, 50, 50);
// adding the checkbox to frame
f.add(checkbox1);
f.add(checkbox2);
f.add(label);

// adding event to the checkboxes


checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])

Computer science Department (NSAKCET)


Java Programming Lab Manual
{
new CheckboxExample2();
}
}
Output:

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.*;

public class DisplayingDate extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException{
PrintWriter pw = response.getWriter();
Date today = new Date();
pw.println("<html>"+"<body><h1>Today Date is</h1>");
pw.println("<b>"+ today+"</b></body>"+ "</html>");
}
}
Step-2: xml file for above program
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>

Computer science Department (NSAKCET)


Java Programming Lab Manual
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>DateDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/DateDisplay</url-pattern>
</servlet-mapping>
</web-app>
Output:

2. Html and servlet communication.


Step -1: create html file
<head>
<script type="text/javascript">
function send(){
frm.submit();
}
</script>
</head>
<body>
<h1 style='text-align: center'>HTML to Servlet using JavaScript</h1>
<h2 style='text-align: center'>Select Programming Language and Get
Creator Name</h2>
<form action='langurl' name='frm' method='post'>
Select Language :: <select name='language' onchange='send()'>
<option value='' selected>--Select--</option>
<option value='0'>C</option>
<option value='1'>C++</option>
<option value='2'>Java</option>
<option value='3'>Python</option>
</select>
</form>

Computer science Department (NSAKCET)


Java Programming Lab Manual
</body>
Step-2: write java servlet program
package com.kp.servlet;

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;

public class LangServlet extends HttpServlet {


@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

// variables
PrintWriter pw = null;
int langCode = 0;
String creators[] = null;

// creators
creators = new String[] {
"Dennis Ritchie", "Bjarne Stroustrup",
"James Gosling", "Guido van Rossum"};

// set content type


resp.setContentType("text/html");

// get PrintWriter
pw = resp.getWriter();

// get form data


langCode = Integer.parseInt(req.getParameter("language"));

// 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>");

Computer science Department (NSAKCET)


Java Programming Lab Manual

// 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:

Computer science Department (NSAKCET)


Java Programming Lab Manual

3. Auto refresh a page.

<html>

<head>

<script type = "text/JavaScript">

<!--
function AutoRefresh( t ) {

setTimeout("location.reload(true);", t);

}
//-->

</script>
</head>
<body onload = "JavaScript:AutoRefresh(5000);">

<p>This page will refresh every 5 seconds.</p>

</body>
</html>
Output:

Computer science Department (NSAKCET)


Java Programming Lab Manual

4. Demonstrate session tracking

Step-1 create java servlet page.


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


public class SessionDemo extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("Surendra");

// Check if this is new comer on your web page.


if (session.isNew())
{
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
}
else
{
visitCount = (Integer)session.getAttribute(visitCountKey);

Computer science Department (NSAKCET)


Java Programming Lab Manual
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();

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>");

Computer science Department (NSAKCET)


Java Programming Lab Manual
}
}
Step-2 create xml file web.xml
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>SessionDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>

Output:
First output

After refreshing the application

Computer science Department (NSAKCET)


Java Programming Lab Manual

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);
}

Computer science Department (NSAKCET)


Java Programming Lab Manual
}
Output:

Program-2: object comparison


public class ObjectComparisonExample
{
public static void main(String[] args)
{
//creating constructor of the Double class
Double x = new Double(123.45555);
//creating constructor of the Long class
Long y = new Long(9887544);
//invoking the equals() method
System.out.println("Objects are not equal, hence it returns " + x.equals(y));
System.out.println("Objects are equal, hence it returns " + x.equals(123.45555));
}
}
Output:

Program-3: finding the largest number.


import java.util.Scanner;
public class LargestNumberExample1
{
public static void main(String[] args)
{
int a, b, c, largest, temp;
//object of the Scanner class
Scanner sc = new Scanner(System.in);
//reading input from the user
System.out.println("Enter the first number:");
a = sc.nextInt();
System.out.println("Enter the second number:");
b = sc.nextInt();
System.out.println("Enter the third number:");
c = sc.nextInt();
//comparing a and b and storing the largest number in a temp variable
temp=a>b?a:b;

Computer science Department (NSAKCET)


Java Programming Lab Manual
//comparing the temp variable with c and storing the result in the variable
largest=c>temp?c:temp;
//prints the largest number
System.out.println("The largest number is: "+largest);
}
}
Output:

Program-4: print pattern


public class RightTrianglePattern
{
public static void main(String args[])
{
//i for rows and j for columns
//row denotes the number of rows you want to print
int i, j, row=6;
//outer loop for rows
for(i=0; i<row; i++)
{
//inner loop for columns
for(j=0; j<=i; j++)
{
//prints stars
System.out.print("* ");
}
//throws the cursor in a new line after printing each line
System.out.println();
}
}
}
Output:

Computer science Department (NSAKCET)


Java Programming Lab Manual

Program-5: finding GCD of two numbers.


public class FindGCDExample1
{
public static void main(String[] args)
{
//x and y are the numbers to find the GCF
int x = 12, y = 8, gcd = 1;
//running loop form 1 to the smallest of both numbers
for(int i = 1; i <= x && i <= y; i++)
{
//returns true if both conditions are satisfied
if(x%i==0 && y%i==0)
//storing the variable i in the variable gcd
gcd = i;
}
//prints the gcd
System.out.printf("GCD of %d and %d is: %d", x, y, gcd);
}
}
Output:

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: ");

Computer science Department (NSAKCET)


Java Programming Lab Manual
a = scanner.nextInt();
System.out.print("Enter the second number: ");
b = scanner.nextInt();
System.out.println("Before swapping:");
System.out.println("a = " +a +", b = " +b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("After swapping:");
System.out.print("a = " +a +", b = " +b);
}
}
Output:

Program-7: checking whether the number is positive or negative


import java.util.Scanner;
public class CheckPositiveOrNegativeExample2
{
public static void main(String[] args)
{
int num;
//object of the Scanner class
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
//reading a number from the user
num = sc.nextInt();
//checks the number is greater than 0 or not
if(num>0)
{
System.out.println("The number is positive.");
}
//checks the number is less than 0 or not
else if(num<0)

Computer science Department (NSAKCET)


Java Programming Lab Manual
{
System.out.println("The number is negative.");
}
//executes when the above two conditions return false
else
{
System.out.println("The number is zero.");
}
}
}
Output:

Beyond syllabus:
Program-1: ATM program
//import required classes and packages
import java.util.Scanner;

//create ATMExample class to implement the ATM functionality


public class ATMExample
{
//main method starts
public static void main(String args[] )
{
//declare and initialize balance, withdraw, and deposit
int balance = 100000, withdraw, deposit;

//create scanner class object to get choice of user

Computer science Department (NSAKCET)


Java Programming Lab Manual
Scanner sc = new Scanner(System.in);

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:");

//get choice from user


int choice = sc.nextInt();
switch(choice)
{
case 1:
System.out.print("Enter money to be withdrawn:");

//get the withdrawl money from user


withdraw = sc.nextInt();

//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:

System.out.print("Enter money to be deposited:");

//get deposite amount from te user


deposit = sc.nextInt();

Computer science Department (NSAKCET)


Java Programming Lab Manual

//add the deposit amount to the total balanace


balance = balance + deposit;
System.out.println("Your Money has been successfully depsited");
System.out.println("");
break;

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:

Computer science Department (NSAKCET)


Java Programming Lab Manual

Program-2: sorting array elements in ascending order


public class SortAsc {
public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;

//Displaying elements of original array


System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

//Sort the array in ascending order


for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println();

//Displaying elements of array after sorting


System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++) {

Computer science Department (NSAKCET)


Java Programming Lab Manual
System.out.print(arr[i] + " ");
}
}
}
Output:

Program-3: finding frequency of odd and even number in matrix


public class OddEven
{
public static void main(String[] args) {
int rows, cols, countOdd = 0, countEven = 0;

//Initialize matrix a
int a[][] = {
{4, 1, 3},
{3, 5, 7},
{8, 2, 6}
};

//Calculates number of rows and columns present in given matrix


rows = a.length;
cols = a[0].length;

//Counts the number of even elements and odd elements


for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(a[i][j] % 2 == 0)
countEven++;
else
countOdd++;
}
}

System.out.println("Frequency of odd numbers: " + countOdd);


System.out.println("Frequency of even numbers: " + countEven);
}

Computer science Department (NSAKCET)


Java Programming Lab Manual
}
Output:

Program-4: to find subset of all strings


public class AllSubsets {
public static void main(String[] args) {

String str = "FUN";


int len = str.length();
int temp = 0;
//Total possible subsets for string of size n is n*(n+1)/2
String arr[] = new String[len*(len+1)/2];

//This loop maintains the starting character


for(int i = 0; i < len; i++) {
//This loop adds the next character every iteration for the subset to form and add it to the
array
for(int j = i; j < len; j++) {
arr[temp] = str.substring(i, j+1);
temp++;
}
}

//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:

Computer science Department (NSAKCET)


Java Programming Lab Manual

Program-5: linear search in java


public class LinearSearchExample{
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}
Output:

Program-6 selection sort in java


public class SelectionSortExample {
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){

Computer science Department (NSAKCET)


Java Programming Lab Manual
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}

public static void main(String a[]){


int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();

selectionSort(arr1);//sorting array using selection sort

System.out.println("After Selection Sort");


for(int i:arr1){
System.out.print(i+" ");
}
}
}
Output:

Computer science Department (NSAKCET)

You might also like