Java Programming
Java Programming
ETCS-357
Semester/Group: 5C8
Lab-1
Topics Covered:
Java is −
1. Object Oriented − In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
2. Platform Independent − unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
3. Simple − Java is designed to be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master.
4. Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
5. Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.
6. Portable − Being architecture-neutral and having no implementation dependent aspects
of the specification makes Java portable. Compiler in Java is written in ANSI C with a
clean portability boundary, which is a POSIX subset.
7. Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
8. Multithreaded − With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.
9. Interpreted − Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.
10. High Performance − with the use of Just-In-Time compilers, Java enables high
performance.
11. Distributed − Java is designed for the distributed environment of the internet.
12. Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-
time information that can be used to verify and resolve accesses to objects on run-time.
Experiment-1
Code:
public class JavaApplication1 {
System.out.println("Hello World!");
Output:
Experiment-2
Code:
public class JavaApplication2 {
char ch = 'a';
System.out.println(str);
System.out.println(str2);
Output:
Experiment-3
Code:
public class JavaApplication3{
String s="hello";
char c = s.charAt(i);
}}
Output:
Experiment-4
Code:
public class JavaApplication4 {
System.out.println(str);
Output:
Experiment-5
Code:
public class JavaApplication5 {
char ch = 'P';
Output:
Experiment-6
Code:
import java.util.Scanner;
int n = sc.nextInt();
int count = 0;
if(n>=1) {
count=1;
System.out.println("2");
for(int i=3;count<n;i++) {
for(int j=2;j<i;j++) {
if(i%j == 0) {
isPrime = false;
break;
if(isPrime == true) {
count++;
System.out.println(i);
Output:
Lab-2
Topics Covered:
• Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
• Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
Experiment-7
Code:
import java.util.Scanner;
char ch = sc.next().charAt(0);
switch(ch) {
case 'a': {
System.out.println("It is a vowel");
break;
case 'e' : {
System.out.println("It is a vowel");
break;
case 'i': {
System.out.println("It is a vowel");
break;
case 'o': {
System.out.println("It is a vowel");
break;
case 'u': {
System.out.println("It is a vowel");
break;
case 'A': {
System.out.println("It is a vowel");
break;
case 'E': {
System.out.println("It is a vowel");
break;
case 'I': {
System.out.println("It is a vowel");
break;
case 'O': {
System.out.println("It is a vowel");
break;
case 'U': {
System.out.println("It is a vowel");
break;
default: {
Output:
Experiment-8
Aim: Write a program to check whether the input year is leap or not.
Code:
import java.util.Scanner;
if(year%4 == 0) {
else {
Output:
Experiment-9
Aim: Write a program that accepts two doubles as its command line arguments.
Multiply these together and display the product.
Code:
public class JavaApplication9 {
double d1 = Double.parseDouble(args[0]);
double d2 = Double.parseDouble(args[1]);
double d3 = d1*d2;
Output:
Experiment-10
Aim: Write a program that accepts one command line argument, display the line
reporting if number is even or odd.
Code:
public class JavaApplication10 {
if(num%2 == 0) {
else {
Output:
Experiment-11
Aim: Write a program to that accepts radius of a circle as its command line
argument and display the area.
Code:
public class JavaApplication11 {
float r = Float.parseFloat(args[0]);
Output:
Experiment-12
Code:
public class JavaApplication12 {
int n = Integer.parseInt(args[0]);
int count = 0;
if(n>=1) {
count=1;
System.out.println("2");
for(int i=3;count<n;i++) {
for(int j=2;j<i;j++) {
if(i%j == 0) {
isPrime = false;
break;
if(isPrime == true) {
count++;
System.out.println(i);
Output:
Lab-3
Topics Covered:
Arrays in Java:
An array is a group of like-typed variables that are referred to by a common name. Arrays in
Java work differently than they do in C/C++. Following are some important point about Java
arrays.
1) push(Object element)
2) pop()
3) peek()
4) empty()
Queue - It’s a linear data structure which follows FIFO(First In First Out) order. The Queue
interface presents in the java.util package and extends the Collection interface. The only the
functions which can be performed in queue data structure are insert at rear, remove from
front, access front and access rear value.
1) add(Object element)
2) offer(Object element)
3) peek()
4) poll()
5) remove()
Method Overloading:
Method overloading is a concept that allows to declare multiple methods with same name but
different parameters in the same class. Method overloading is one of the ways through which
java supports polymorphism. Polymorphism is a concept of object oriented programming that
deals with multiple forms. We will cover polymorphism in separate topics later on. Method
overloading can be done by changing number of arguments or by changing the data type of
arguments. If two or more method have same name and same parameter list but differs in
return type cannot be overloaded.
• Write a program to find the array index or position where sum of numbers
preceding the index is equal to the sum of numbers succeeding the index.
• Write a program that creates and initializes a four element array. Calculate
and display the average of its values.
• Write a program that creates a 2-D array with int values. The first element
should be an array containing 32. The second element should be array
containing 500 and 300. The third element should be an array containing
39, 45 and 600. Declare, initialize, allocate the array and display its
elements.
• Write a program to sort an array.
• Write a program to implement stack and queue concept.
• Using the concept of method overloading, write method for calculating the
area of triangle, circle and rectangle.
Experiment-13
Aim: Write a program to find the array index or position where sum of numbers
preceding the index is equal to the sum of numbers succeeding the index.
Code:
package javaapplication13;
import java.util.Scanner;
int i, j;
leftsum = 0;
leftsum += arr[j];
rightsum = 0;
rightsum += arr[j];
if (leftsum == rightsum)
return i;
return -1;
int n = sc.nextInt();
for(int i=0;i<n;i++) {
arr[i] = sc.nextInt();
System.out.println(ob.equilibrium(arr, arr_size));
Output:
Experiment-14
Aim: Write a program that creates and initializes a four element array. Calculate
and display the average of its values.
Code:
package javaapplication14;
import java.util.Scanner;
float sum = 0;
for(int i=0;i<4;i++) {
arr[i] = sc.nextInt();
for(int i=0;i<4;i++) {
Output:
Experiment-15
Aim: Write a program that creates a 2-D array with int values. The first element
should be an array containing 32. The second element should be array
containing 500 and 300. The third element should be an array containing 39, 45
and 600. Declare, initialize, allocate the array and display its elements.
Code:
package javaapplication15;
import java.util.Scanner;
for(int i=-0;i<3;i++) {
for(int j=0;j<3;j++) {
arr[i][j] = 0;
arr[0][0] = 32;
arr[1][0] = 500;
arr[1][1] = 300;
arr[2][0] = 39;
arr[2][1] = 45;
arr[2][2] = 600;
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
System.out.println();
Output:
Experiment-16
Code:
package javaapplication16;
import java.util.Scanner;
int n = arr.length;
arr[j] = arr[j+1];
arr[j+1] = temp;
int n = sc.nextInt();
for(int i=0;i<n;i++) {
arr[i] = sc.nextInt();
ob.bubbleSort(arr);
for(int i=0;i<n;i++){
System.out.print(arr[i]+" ");
Output:
Experiment-17
package javaapplication21;
import java.util.Stack;
stackOfFriends.push("Aakash");
stackOfFriends.push("Harshit");
stackOfFriends.push("Rishab");
stackOfFriends.push("Sarthak");
System.out.println();
frndAtTop = stackOfFriends.pop();
if(stackOfFriends.empty())
System.out.println("Stack is Empty");
else
Output (Stack):
package javaapplication22;
import java.util.LinkedList;
this.maxSize = size;
front = 0;
rear = -1;
currentSize = 0;
if(isQueueFull()){
System.out.println("Queue is full!");
return;
rear = -1;
queueArray[++rear] = item;
currentSize++;
if(isQueueEmpty()){
if(front == maxSize){
front = 0;
currentSize--;
return temp;
return queueArray[front];
queue.insert(2);
queue.insert(3);
queue.insert(5);
Output (Queue) :
Experiment-18
Aim: Using the concept of method overloading, write method for calculating the
area of triangle, circle and rectangle.
Code:
package javaapplication17;
import java.util.Scanner;
float s = (x+y+z)/2;
void area(double x) {
double z = 3.14 * x * x;
int ch = sc.nextInt();
switch(ch) {
case 1: {
float a = sc.nextFloat();
float b = sc.nextFloat();
float c = sc.nextFloat();
ob.area(a,b,c);
} break;
case 2: {
float a = sc.nextFloat();
float b = sc.nextFloat();
ob.area(a,b);
} break;
case 3: {
double r = sc.nextDouble();
ob.area(r);
} break;
Output:
Lab-4
Topics Covered:
Object is a basic unit of Object Oriented Programming and represents the real life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods.
An object consists of :
Constructors:
Constructors are used to initialize the object’s state. Like methods, a constructor also contains
collection of statements (i.e. instructions) that are executed at time of Object creation. Each
time an object is created using new () keyword at least one constructor (it could be default
constructor) is invoked to assign initial values to the data members of the same class. A
constructor is invoked at the time of object or instance creation.
Static:
To create a static member (block, variable, method, nested class), precede its declaration with the
keyword static. When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object
• Write a program that creates a class circle with instance variables for the
center and radius. Initialize and display its values.
• Write a program to have a constructor in class circle in Experiment-19 to
initialize its variables.
• Write a program to show constructor overloading in Experiment-20.
• Write a program to display the use of ‘this’ keyword.
• Write a program to count the number of instances created for the class.
• Write a program that describes a class person. It should have instance
variables to record name, age and salary. Create a person object. Set and
display its instance variables.
Experiment-19
Aim: Write a program that creates a class circle with instance variables for the
center and radius. Initialize and display its values.
Code:
package javaapplication30;
import java.util.Scanner;
class Circle {
int x,y;
float radius;
c.x = sc.nextInt();
c.y = sc.nextInt();
c.radius = sc.nextFloat();
Output:
Experiment-20
Code:
package javaapplication30;
class Circle {
int x,y;
float radius;
Circle() {
x = 10;
y = 20;
radius = 7;
Output:
Experiment-21
Code:
package javaapplication30;
class Circle {
int x,y;
float radius;
Circle() {
x = 10;
y = 20;
radius = 7;
x = a;
y = b;
radius = c;
Output:
Experiment-22
Code:
package javaapplication30;
class ThisKeyword {
int x,y,z;
ThisKeyword() {
this.x = 10;
this.y = 20;
this.z = 30;
Output:
Experiment-23
Aim: Write a program to count the number of instances created for the class.
Code:
package javaapplication30;
class Count {
int a;
noOfObjects +=1;
Count(int x) {
a = x;
Output:
Experiment-24
Aim: Write a program that describes a class person. It should have instance
variables to record name, age and salary. Create a person object. Set and display
its instance variables.
Code:
package javaapplication30;
import java.util.Scanner;
class Person {
int age;
float salary;
String name;
p.name = sc.nextLine();
p.age = sc.nextInt();
p.salary = sc.nextFloat();
Output:
Lab-5
Topics Covered:
• Inheritance
• Method Overriding
• Super Keyword
Inheritance:
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the mechanism in
java by which one class is allowed to inherit the features (fields and methods) of another class.
• Super Class: The class whose features are inherited is known as super class (or a base
class or a parent class).
• Sub Class: The class that inherits the other class is known as sub class (or a derived class,
extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
Method Overriding:
Overriding is a feature that allows a subclass or child class to provide a specific implementation
of a method that is already provided by one of its super-classes or parent classes. When a
method in a subclass has the same name, same parameters or signature, and same return type
(or sub-type) as a method in its super-class, then the method in the subclass is said to override
the method in the super-class. Method overriding is one of the way by which java achieve Run
Time Polymorphism. The version of a method that is executed will be determined by the object
that is used to invoke it. If an object of a parent class is used to invoke the method, then the
version in the parent class will be executed, but if an object of the subclass is used to invoke the
method, then the version in the child class will be executed. In other words, it is the type of the
object being referred to (not the type of the reference variable) that determines which version
of an overridden method will be executed.
Super Keyword:
The super keyword in java is a reference variable that is used to refer parent class objects. It is
majorly used in the following contexts:
• Use of super with variables: This scenario occurs when a derived class and base class has
same data members.
• Use of super with methods: This is used when we want to call parent class method. So
whenever parent and child classes have same named methods then to resolve
ambiguity we use super keyword.
• Use of super with constructors: super keyword can also be used to access the parent
class constructor. ‘’super’ can call both parametric as well as non-parametric
constructors depending upon the situation.
Experiment-25
Code:
package javaapplication31;
class Parent {
void show() {
System.out.println("Parent's show()");
@Override
void show() {
System.out.println("Child's show()");
obj1.show();
obj2.show();
Output:
Experiment-26
Code:
package javaapplication32;
class one {
System.out.println("Class One");
System.out.println("Class Two");
obj.print_one();
obj.print_two();
Output:
Experiment-27
Code:
package javaapplication33;
class one {
System.out.println("Class One");
System.out.println("Class Two");
System.out.println("Class Three");
obj.print_one();
obj.print_two();
obj.print_three();
Output:
Experiment-28
Code:
package javaapplication34;
class Vehicle {
void message() {
Vehicle() {
void display() {
void message() {
void display2() {
message();
super.message();
Car() {
super();
obj.display();
obj.display2();
Output:
Lab-6
Topics Covered:
• Java Package
• Java Abstraction
• Interfaces
Java Package:
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and namespace management.
java.io − classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.
Creating a Package
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the
package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation
types will be placed in the current default package.
To compile the Java programs with package statements, we have to use -d option as shown
below.
Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder.
Java Abstraction:
Data abstraction is the process of hiding certain details and showing only essential information
to the user. Abstraction can be achieved with either abstract classes or interfaces.
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body
is provided by the subclass (inherited from).
Interfaces:
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.
Along with abstract methods, an interface may also contain constants, default methods, static
methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need
to be defined in the class.
• Write a program that creates an abstract class shape. Let triangle and
rectangle inherit shape. Add necessary functions.
• Write a java package to show dynamic polymorphism and interfaces.
• Write a program that creates interface and implements it.
• Write a program to illustrate interface inheritance.
Experiment-29
Aim: Write a program that creates an abstract class shape. Let triangle and
rectangle inherit shape. Add necessary functions.
Code:
package javaapplication36;
import java.util.Scanner;
import java.lang.Math;
int color;
void getSides() {
length = sc.nextInt();
breadth = sc.nextInt();
void perimeter() {
int ar = 2*(length+breadth);
int a,b,c;
void getSides() {
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
void perimeter() {
int ar = a+b+c;
System.out.println("Perimeter is "+ar);
r.getSides();;
r.perimeter();
t.getSides();
t.perimeter();
Output:
Experiment-30
Code:
package javaapplication37;
import java.util.*;
interface shape {
int l , b;
l = sc.nextInt();
b = sc.nextInt();
int ar = l*b;
int b,h;
b = sc.nextInt();
h = sc.nextInt();
int ar = b*h/2;
r.getSides();
r.area();
t.getSides();
t.area();
d.getSides();
Output:
Experiment-31
Code:
package javaapplication41;
import java.util.*;
interface shape {
int l , b;
l = sc.nextInt();
b = sc.nextInt();
int ar = l*b;
int b,h;
b = sc.nextInt();
h = sc.nextInt();
int ar = b*h/2;
r.getSides();
r.area();
t.getSides();
t.area();
Output:
Experiment-32
Code:
package javaapplication42;
import java.util.*;
interface interfaceA {
void Name();
void Institute();
System.out.println("Inside NAme()");
System.out.println("Inside Institute()");
c.Name();
c.Institute();
Output:
Lab-7
Topics Covered:
• Exception Handling
• Applet
Exception Handling:
An exception is an unwanted or unexpected event, which occurs during the execution of a
program i.e. at run time, which disrupts the normal flow of the program’s instructions.
All exception and errors types are sub classes of class Throwable, which is base class of
hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that
user programs should catch. NullPointerException is an example of such an exception. Another
branch, Error are used by the Java run-time system (JVM) to indicate errors having to do with
the run-time environment itself (JRE). StackOverflowError is an example of such an error.
Whenever inside a method, if an exception has occurred, the method creates an Object known
as Exception Object and hands it off to the run-time system (JVM). The exception object
contains name and description of the exception, and current state of the program where
exception has occurred. Creating the Exception Object and handling it to the run-time system is
called throwing an Exception.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Briefly, here is how they work. Program statements that you think can raise exceptions are
contained within a try block. If an exception occurs within the try block, it is thrown. Your code
can catch this exception (using catch block) and handle it in some rational manner. System-
generated exceptions are automatically thrown by the Java run-time system. To manually
throw an exception, use the keyword throw. Any exception that is thrown out of a method
must be specified as such by a throws clause. Any code that absolutely must be executed after
a try block completes is put in a finally block.
Applet:
An applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at client side. An applet is embedded in an HTML page using the APPLET or
OBJECT tag and hosted on a web server. Applets are used to make the web site more dynamic
and entertaining.
Important points:
Experiment-33
Code:
package javaapplication2;
myException(int a) {
detail = a;
System.out.println("called Compute["+a+"]");
if(a>10) {
System.out.println("Normal Exit");
try {
commute(1);
commute(20);
catch(myException e) {
Output:
Experiment-34
Aim: Create a customized exception and also make use of all the 5 exception
keywords.
Code:
package javaapplication2;
myException(int a) {
detail = a;
System.out.println("called Compute["+a+"]");
if(a>10) {
System.out.println("Normal Exit");
try {
commute(9);
commute(25);
catch(myException e) {
finally {
System.out.println("Inside Finally");
Output:
Experiment-35
Aim: Write an Applet that displays “Hello World” (Background color-black, text
color-blue and your name in the status window).
Code:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
/*
</applet>
*/
setBackground(Color.BLACK);
@Override
g.setColor(Color.BLUE);
showStatus("Aakash Garg");
Output:
Experiment-36
Code:
import java.applet.Applet;
import java.awt.*;
import java.util.*;
/*
</applet>
*/
@Override
new Thread() {
@Override
while (true) {
repaint();
}.start();
@Override
hour -= 12;
g.setColor(Color.white);
g.setColor(Color.black);
double angle;
int x, y;
x = (int)(Math.cos(angle) * 100);
y = (int)(Math.sin(angle) * 100);
g.setColor(Color.red);
x = (int)(Math.cos(angle) * 80);
y = (int)(Math.sin(angle) * 80);
g.setColor(Color.blue);
x = (int)(Math.cos(angle) * 50);
y = (int)(Math.sin(angle) * 50);
g.setColor(Color.black);
Output:
Lab-8
Topics Covered:
• Multithreading
Multithreading:
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Thread creation by extending the Thread class: User create a class that extends
the java.lang.Thread class. This class overrides the run() method available in the Thread class. A
thread begins its life inside run() method. User create an object of our new class and call start()
method to start the execution of a thread. Start() invokes the run() method on the Thread
object.
Thread creation by implementing the Runnable Interface: User create a new class which
implements java.lang.Runnable interface and override run() method. Then user instantiate a
Thread object and call start() method on this object.
Experiment-37
Code:
package javaapplication2;
class CubbyHole {
try {
wait();
} catch (InterruptedException e) {}
available = false;
notifyAll();
return contents;
try {
wait();
} catch (InterruptedException e) { }
contents = value;
available = true;
notifyAll();
cubbyhole = c;
this.number = number;
int value = 0;
value = cubbyhole.get();
cubbyhole = c;
this.number = number;
cubbyhole.put(i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
p1.start();
c1.start();
Output:
Experiment-38
Aim: Write an application that executes two threads. One thread displays “An”
every 1000 milliseconds and other displays “B” every 3000 milliseconds. Create
the threads by extending the Thread class.
Code:
package javaapplication2;
int time;
String name;
time = myTime;
name = myName;
start();
try {
for(int i=0;i<5;i++) {
System.out.println(name);
Thread.sleep(time);
catch(InterruptedException e) {
System.out.println("Execution Interrupted");
try{
Thread.sleep(15000);
catch(InterruptedException e) {
System.out.println("Execution Interrupted");
Output:
Lab-9
Topics Covered:
• AWT Components
• Event Handling
AWT Components:
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in
java. Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS. The java.awt package provides classes for AWT api such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc. The hierarchy of Java
AWT classes are given below.
Event Handling:
Event: Change in the state of an object is known as event i.e. event describes the change in
state of source. Events are generated as result of user interaction with the graphical user
interface components. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the page are the activities that
causes an event to happen.
Types of Event:
Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in Graphical
User Interface. For example clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires,
an operation completion are the example of background events.
Event Handling: Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs. This mechanism has the code which is known as event
handler that is executed when an event occurs. Java Uses the Delegation Event Model to
handle the events. This model defines the standard mechanism to generate and handle the
events.
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to its handler. Java provide as with classes for source object.
• Write a program that illustrates how to process mouse click, enter, exit,
press and release events. The background color changes when the mouse is
entered, clicked, pressed, released or exited.
• Write a program that displays your name whenever the mouse is clicked.
Experiment-39
Aim: Write a program that illustrates how to process mouse click, enter, exit,
press and release events. The background color changes when the mouse is
entered, clicked, pressed, released or exited.
Code:
package javaapplication3;
import java.awt.*;
import java.awt.event.*;
public JavaApplication3( )
addMouseListener(this);
setSize(300,300);
setVisible(true);
setBackground(Color.red);
System.out.println("Mouse is Pressed");
setBackground(Color.blue);
System.out.println("Mouse is Released");
setBackground(Color.green);
System.out.println("Mouse is Clicked");
setBackground(Color.cyan);
System.out.println("Mouse is Entered");
setBackground(Color.magenta);
System.out.println("Mouse is Exited");
new JavaApplication3();
Output:
Exit Enter
Pressed Released
Experiment-40
Aim: Write a program that displays your name whenever the mouse is clicked.
Code:
package javaapplication5;
import java.awt.*;
import java.awt.event.*;
Label l;
JavaApplication5(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
l.setText("Aakash Garg");
new JavaApplication5();
Output:
Lab-10
Topics Covered:
• File Handling
• JDBC
File Handling:
Java FileWriter and FileReader classes are used to write and read data from text files (they
are Character Stream classes).
FileReader is useful to read data in the form of characters from a ‘text’ file.
JDBC:
JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac OS,
and the various versions of UNIX. JDBC stands for Java Database Connectivity, which is a
standard Java API for database-independent connectivity between the Java programming
language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of
executables, such as −
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.
Experiment-41
Aim: Write a program that read from a file and write to file.
Code:
package javaapplication6;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
String str = "File handling in Java. Writing a character stream using fileWriter.";
fw.write(str.charAt(i));
System.out.println("Writing successful");
fw.close();
int ch;
while ((ch=fr.read())!=-1)
System.out.print((char)ch);
fr.close();
}}
Output:
Experiment-42
Aim: Write a program to convert the content of a given file into the uppercase
content of the same file.
Code:
package javaapplication6;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
int ch;
while((ch=fr.read())!=-1) {
if(Character.isLowerCase(ch)) {
fw.write(Character.toUpperCase(ch));
else {
fw.write(ch);
fw.close();
fr.close();
while ((ch=r.read())!=-1) {
w.write(ch);
w.close();
r.close();
while ((ch=f.read())!=-1)
System.out.print((char)ch);
f.close();
Output:
Experiment-43
Code:
package javaapplication8;
import java.sql.*;
try{
String database="student.mdb";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
while(rs.next()){
System.out.println(rs.getString(1));
}catch(Exception ee){System.out.println(ee);}
Output: