Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Java Lab

hjhyj

Uploaded by

harishini142003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Lab

hjhyj

Uploaded by

harishini142003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

P

-J
IT
V
M
JAVA PROGRAMMING

LAB MANUAL

II YEAR

IV SEMESTER

ACADEMIC YEAR: 2023-2024


P
-J
LIST OF EXPERIMENTS

S. No Name Of Experiment No. of Sessions

IT
Simple Java Program
1 Factorial of a given number
Class and Objects
2(a) Simple Student Class Without Access Specifiers
2(b)
2(c)
V
Simple Student Class With Access Specifiers
Student details using class & Object with Access
Specifiers
Exception Handling
M
3(a) Arithmetic Exception
3(b) ArrayIndexOutofBound Exception
3(c) User Defined Exception
Inheritance
4(a) Single Inheritance
4(b) Multilevel Inheritance
4(c) Hierarchical Inheritance
5(a) Interface
5(b) Multiple Inheritance
6 Package
Event Handling
7(a) Item Event Handling
7(b) Mouse Event Handling
7(c) Action Event Handling
8 File Handling
Thread
9(a) Single Thread
9(b) Multi Thread
10 AWT Control
11 Applets
12 RMI
13 JDBC
Content Beyond the Syllabus
14 TCP one way communication
15 Moving Object

STAFF – IN CHARGE HOD PRINCIPAL


P
Ex. No: 1 FACTORIAL

-J
Aim: To create a Java Program to compute the factorial of a given
number.

IT
Algorithm
1. Start the program.
2. Declare the class 'Factorial' with the data members 'n','i','f'.

V
3. Create an object for the Scanner to get the input value.
4. Read the input value for 'n' by using object.
5. Compute the factorial value using iteration.
M
6. Display the factorial value.
7. Stop the program.

Source Code

import java.util.Scanner;
class Factorial
{
public static void main(String arg[])
{
Scanner in = new Scanner (System.in);
int n, i, f=1;
System.out.println(“Enter the n value:”);
n = in.nextInt();
for(i=1; i<=n ; i++)
{
f = f * i;
}
System.out.println(“Factorial is “ +f);
}
}
Output

Result
Thus the Java program to compute the Factorial of a given number has been created and
executed successfully.

Viva Questions

1. What is the use of scanner in java?


P
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace

-J
by default. It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

IT
2. What are the methods used in scanner class?

Method Description

V
public String next() it returns the next token from the scanner.
M
public String nextLine() it moves the scanner position to the next line and returns the
value as a string.

public byte nextByte() it scans the next token as a byte.

public short nextShort() it scans the next token as a short value.

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

public double nextDouble() it scans the next token as a double value.

3. What are the packages used for Scanner class?


java.util.Scanner

Ex.No:2(a) CLASSES AND OBJECTS - SIMPLE STUDENT CLASS WITHOUT


ACCESS SPECIFIERS
P
-J
AIM:
To write a Java program to implement a simple student class without access specifiers.

ALGORITHM:

IT
1. Start the program.
2. Create a class Student with two data members with default access specifier.
3. Create another class named J2aSimpleClass.
4. Create an object of type student inside the main() of J2aSimpleClass.
5. Assign values to the data members of student class inside the J2aSimpleClass.

V
6. Print the two data members of student class.
7. Stop the program
M
SOURCE CODE

package javaapplication1;
//if access specifiers are not specified then the class members are Visible to the package, the
default.
//No modifiers are needed.

class student
{
int regno;
String name;
}

public class J2aSimpleClass


{
public static void main(String args[])
{
student s=new student(); //Object Creation For Class
s.regno = 100;
s.name = "John Marshal";
System.out.println("Reg No " + s.regno);
System.out.println("Name " + s.name);
}
}

OUTPUT
P
-J
IT
V
M

RESULT
Thus the Java program to implement a simple student class without access specifiers
have been completed successfully and the output is verified.
P
Ex.No:2(b)(i) CLASSES AND OBJECTS - SIMPLE STUDENT CLASS WITH ACCESS

-J
SPECIFIERS

AIM:

IT
To write a Java program to implement a simple student class with access specifiers.

ALGORITHM:
1. Start the program.

V
2. Create a class Student with two data members with private access specifier.
3. Create two methods to get values for data members and to display the data member
values.
M
4. Create an object of type student inside the main() of J2bSimpleClass.
5. Assign values to the data members of student class through getdata() function.
6. Print the two data members of student class using showdata() funtion.
7. Stop the program

SOURCE CODE
package javaapplication2;
//Note: private - Can access inside the class (Not access by object, Not access by derived class)

import java.util.Scanner;
class student
{
private int regno;
private String name;

void getdata()
{
Scanner in = new Scanner(System.in);
System.out.println ("Enter the Register Number");
regno = in.nextInt();
System.out.println ("Enter the Name");
name = in.next();
}

void showdata()
{
System.out.println("Reg No " + regno);
System.out.println("Name " + name);
}
}
P
public class J2bSimpleClass

-J
{
public static void main(String args[])
{
student s=new student();

IT
s.getdata();
s.showdata();
//s.regno = 10; //ERROR: regno is private
}
}

V
M
OUTPUT

RESULT
Thus the Java program to implement a simple student class with access specifiers have
been completed successfully and the output is verified.
P
-J
Ex.No:2(b)(ii) CLASSES AND OBJECTS - SIMPLE STUDENT CLASS WITH

IT
ACCESS SPECIFIERS
AIM:
To write a Java program to implement a simple student class with access specifiers.
ALGORITHM:

V
1. Start the program.
M
2. Create a class student with its data member and member function
3. Get marks and regno as Integer data type and name as String data type from user using
getdata().
4. Calculate the result in calculation().
5. Display Student details using show() function.
6. Create a main class J2cSimpleClass and create instances of student class.
7. Using the instance call the above mentioned methods and find out whether the result of an
student is PASS or FAIL.
8. Stop the program

SOURCE CODE

package javaapplication3;
import java.util.Scanner;
class student
{
private String name,result;
private int regno,m1,m2,m3,total;
private float percentage;

void getdata()
{
Scanner in = new Scanner(System.in);
System.out.println ("Enter the Register Number");
regno = in.nextInt();
System.out.println ("Enter the Name");
name = in.next();
System.out.println ("Enter mark1");
m1 = in.nextInt();
System.out.println ("Enter mark2");
m2 = in.nextInt();
System.out.println ("Enter mark3");
m3 = in.nextInt();
}

void calculation()
{
total=m1+m2+m3;
percentage=(total)/3;
if(m1>=50 && m2>=50 && m3>=50)
{
result="PASS";
}
P
else

-J
{
result="FAIL";
}
}

IT
void show()
{
System.out.println ("\t\t\tStudent Details");
System.out.println ("Name = "+name);

V
System.out.println ("Register Number = "+regno);
System.out.println ("Marks of 1st Subject = "+m1);
System.out.println ("Marks of 2nd Subject = "+m2);
M
System.out.println ("Marks of 3rd Subject = "+m3);
System.out.println ("Total Marks = "+total);
System.out.println ("Result = "+result);
System.out.println ("Percentage = "+percentage+"%");
}
}

class J2cSimpleClass
{
public static void main(String[] args)
{
student s=new student();
System.out.println ("\t\t\tStudent Information System");
s.getdata();
s.calculation();
s.show();
}
}
P
-J
OUTPUT

IT
V
M

RESULT
P
Thus the Java program to implement a simple student class with access specifiers have

-J
been completed successfully and the output is verified.

IT
V
1. Difference between == and .equals ()?
Viva Question
M
"equals" is the member of object class which returns true if the content of objects are
same whereas "==" evaluate to see if the object handlers on the left and right are pointing to the
same object in memory.

2. What are the common uses of "this" keyword in java ?


"this" keyword is a reference to the current object and can be used for following -
 Passing itself to another method.
 Referring to the instance variable when local variable has the same name.
 Calling another constructor in constructor chaining.

3. How are this() and super() used with constructors?


 this() is used to invoke a constructor of the same class.
 super() is used to invoke a superclass constructor.

4. Differentiate between a Class and an Object?


A class is a blueprint or prototype that defines the variables and the methods
(functions) common to all objects of a certain kind.
class <class_name>{
field;
method;
}
An object is a specimen of a class. Software objects are often used to model real-world
objects you find in everyday life.
ClassName ReferenceVariable = new ClassName();

5. Uses of Super Keyword?


 Super keyword is used to invoke the base class constructor from subclass constructor.
 It is also used to give the name of a particular thread.
 It is used to access the instance variable of base class.
P
-J
IT
Ex. no: 3(a) ARITHMETIC EXCEPTION

Aim: To create a java program for the concept of Arithmetic Exception.

Algorithm
V
1. Start the program.
M
2. Create the class DivNumbers.
3. Define the division method and create a try block.
4. Assign the difference types of exception in this method.
5. Create a main class and execute the program.
6. Stop the program.

Source code

import java.io.*;
class DivNumbers
{
public void division(int num1, int num2)
{
int result;
try
{
result = num1 / num2;
System.out.println("Result:"+result);
}
catch (ArithmeticException e)
{
System.out.println("Exception: "+ e);
}
catch(Exception e)
{
System.out.println("Exception:" + e);
}
finally //Optional block
{
System.out.println("Finally");
}
System.out.println("End");
}
}
P
-J
IT
class ExceptionPrg
{
public static void main(String args[])
{

V
DivNumbers d = new DivNumbers();
d.division(25, 5);
M
d.division(25, 0);
}
}

Output

Result
Thus to create a java program to implement the concept of exception handling was
successfully implemented and verified.
P
-J
IT
Viva Question

1. What are important methods of Java Exception Class?

V
Exception and all of it’s subclasses doesn’t provide any specific methods and all of the
methods are defined in the base class Throwable.
1. String getMessage() – This method returns the message String of Throwable and the
M
message can be provided while creating the exception through it’s constructor.
2. String getLocalizedMessage() – This method is provided so that subclasses can override
it to provide locale specific message to the calling program. Throwable class
implementation of this method simply use getMessage() method to return the exception
message.
3. synchronized Throwable getCause() – This method returns the cause of the exception
or null id the cause is unknown.
4. String toString() – This method returns the information about Throwable in String
format, the returned String contains the name of Throwable class and localized message.
5. void printStackTrace() – This method prints the stack trace information to the standard
error stream, this method is overloaded and we can pass PrintStream or PrintWriter as
argument to write the stack trace information to the file or stream.

2. What is difference between throw and throws keyword in Java?


throws keyword is used with method signature to declare the exceptions that the method
might throw whereas throw keyword is used to disrupt the flow of program and handing over the
exception object to runtime to handle it.

3. What are different scenarios causing “Exception in thread main”?


Some of the common main thread exception scenarios are:
 Exception in thread main java.lang.UnsupportedClassVersionError: This
exception comes when your java class is compiled from another JDK version and you
are trying to run it from another java version.
 Exception in thread main java.lang.NoClassDefFoundError: There are two
variants of this exception. The first one is where you provide the class full name with
.class extension. The second scenario is when Class is not found.
 Exception in thread main java.lang.NoSuchMethodError: main: This exception
comes when you are trying to run a class that doesn’t have main method.
 Exception in thread “main” java.lang.ArithmeticException: Whenever any
exception is thrown from main method, it prints the exception is console. The first
part explains that exception is thrown from main method, second part prints the
exception class name and then after a colon, it prints the exception message.

4. What is StackOverflowError?
The StackOverFlowError is an Error Object thorwn by the Runtime System when it
Encounters that your application/code has ran out of the memory. It may occur in case of
recursive methods or a large amount of data is fetched from the server and stored in some object.
This error is generated by JVM.
P
-J
IT
Ex. no: 3(b) ARRAYINDEXOUTOFBOUND EXCEPTION

V
Aim: To create a java program for the concept of ArrayIndexOutofBound Exception.

Algorithm:
M
1. Start the program.
2. Create the class Main.
3. Define the main method and create a try block.
4. Inside the try block declare array elements and print the value of array elements.
5. Assign the difference types of exception in this method.
6. Execute the program
7. Stop the program.

Source code
import java.io.*;
public class Main
{
public static void main (String args[])
{
int array[]={20,20,40};
int num1=15,num2=10;
int result=10;
try
{
result = num1/num2;
System.out.println("The result is" +result);
for(int i =5;i >=0; i--)
{
System.out.println("The value of array is" +array[i]);
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array is out of Bounds"+e);
}
catch (ArithmeticException e)
{
System.out.println ("Can't divide by Zero"+e);
}
}
}
P
-J
IT
OUTPUT:

V
M

Result
Thus to create a java program to implement the concept of exception handling was
successfully implemented and verified.
P
-J
IT
Ex. no: 3(c) Exception Handling by creating user defined exceptions.

Aim: To create a java program for the concept of User defined Exception
Algorithm:

V
1. Start the program.
2. Create the class MyException and inheriting Exception class and get the message.
M
3. Define the main method in userdef class and create a try block to throw user defined exception.
4. Assign the catch block to catch the exception from the user defined and try block.
5. Execute the program
6. Stop the program.
Program:

import java.io.*;
import java.util.*;
import java.lang.Exception;

class MyException extends Exception


{
MyException(String message)
{
super(message);
}
}

class userdef
{
public static void main(String a[])
{
int age;
Scanner s=new Scanner(System.in);
try
{
System.out.println("Enter the age (above 15 abd below 25) :");
age=s.nextInt();
if(age<15 || age> 25)
{
throw new MyException("Number not in range");
}
System.out.println(" the number is :" +age);
}
catch(MyException e)
{
System.out.println("Caught MyException");
System.out.println(e.getMessage());
}
catch(Exception e)
{
System.out.println(e);
}
}
P
}

-J
IT
Output

V
M

Result
Thus to create a java program to implement the concept of user defined exception was
successfully implemented and verified.
P
-J
IT
Viva Question
1. What is Exception Handling?

V
Exception Handling is a mechanism to handle runtime errors. It is mainly used to handle
checked exceptions.
M
2. Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be
followed by either a catch block OR a finally block. And whatever exceptions are likely to be
thrown should be declared in the throws clause of the method.

3. What is difference between Checked Exception and Unchecked Exception?


1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are
checked at compile-time.

2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at
compile-time.

4. What is finally block? Can finally block be used without catch?


Yes, by try block. Finally must be followed by either try or catch. finally block will not be
executed if program exits(either by calling System.exit() or by causing a fatal error that causes
the process to abort)

5. What is the difference between error and exception in java?


Errors are mainly caused by the environment in which an application is running. For
example, OutOfMemoryError happens when JVM runs out of memory. Where as exceptions are
mainly caused by the application itself. For example, NullPointerException occurs when an
application tries to access null object.

6. What is array index out of bound exception?


The index of an array is an integer value that has value in interval [0, n-1], where n is the
size of the array. If a request for a negative or an index greater than or equal to size of array is
made, then the JAVA throws a ArrayIndexOutOfBounds Exception.
P
-J
IT
Ex.No:4(a) SIMPLE SINGLE INHERITANCE
AIM:
To write a Java program to implement single inheritance using simple methods.

ALGORITHM:

1.
2. V
Start the program.
Declare the base class A.
M
3. Declare and define the function methodA() that prints message “Base class method”.
4. Declare the other class B as derived class of base class A.
5. Declare and define the function methodB() that prints “Child class method “.
6. Create the class result derived from student and marks.
7. Declare the derived class object and call the functions .
8. Stop the program

SOURCE CODE

package exp4a;

class A {
public void methodA() {
System.out.println("Base class method");
}
}

class B extends A {
public void methodB() {
System.out.println("Child class method");
}

public static void main(String args[]) {


B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

OUTPUT
P
RESULT

-J
Thus the program for single inheritance executed and verified successfully.

IT
Ex.No:4(a)(ii) STUDENT INFORMATION SYSTEM USING SINGLE INHERITANCE

AIM:
To write a Java program to implement Student Information system using single
inheritance concept.

ALGORITHM:
V
1. Start the program.
M
2. Declare the base class student.
3. Declare and define the function getdata() that gets student information.
4. Declare the other class exam as derived class of base class student.
5. Declare and define the function calculation() & show() to calculate and print the result
respectively.
6. Declare the derived class object and call the functions .
7. Stop the program

SOURCE CODE

package exp4b;

// private - Can access in the current class (Not object, Not derived class)
// protected - Can access in the current class, derived class and object (not other package)
// public - Can access in the current class, derived class, object and other package
// Single Inheritance: A -> B
// extends - Inherits from base class

import java.util.Scanner;

class student
{

protected int regno, m1, m2, m3, m4, m5; //Data Member Declaration
protected String name, dept;

void getdata() //Function to get student details


{
Scanner in = new Scanner(System.in);

System.out.println("Enter the Register Number");


regno = in.nextInt();
System.out.println("Enter the Name");
name = in.next();

System.out.println("Enter mark1");
m1 = in.nextInt();
System.out.println("Enter mark2");
m2 = in.nextInt();
System.out.println("Enter mark3");
m3 = in.nextInt();
System.out.println("Enter mark4");
m4 = in.nextInt();
P
System.out.println("Enter mark5");

-J
m5 = in.nextInt();
}
}

IT
class exam extends student //Deriving new class from base class
{

private int total; //Data Member Declaration


private String result;

V
private float average;

void calculation()
M
{
total = m1 + m2 + m3 + m4 + m5;
average = (total) / 5;
if (m1 >= 50 && m2 >= 50 && m3 >= 50 && m4 >= 50 && m5 >= 50)
{
result = "PASS";
}
else
{
result = "FAIL";
}
}

void show()
{
System.out.println("\t\t\tStudent Details");
System.out.println("Name = " + name);
System.out.println("Register Number = " + regno);
System.out.println("Marks of 1st Subject = " + m1);
System.out.println("Marks of 2nd Subject = " + m2);
System.out.println("Marks of 3rd Subject = " + m3);
System.out.println("Marks of 4th Subject = " + m4);
System.out.println("Marks of 5th Subject = " + m5);
System.out.println("Total Marks = " + total);
System.out.println("Result = " + result);
System.out.println("Percentage = " + average + "%");
}
}
class J3bInheritance
{
public static void main(String[] args)
{
exam ex = new exam();
System.out.println("STUDENT INFORMATION");
ex.getdata(); //Calling Base class function using derived object
ex.calculation();
ex.show();
}
}
M OUTPUT

V
IT
-J
P
P
RESULT

-J
Thus the program for Student Information System using single inheritance executed
and verified successfully.

IT
V
M
Viva Question
1. What is the use of super keyword?
The super keyword is similar to this keyword. It is used to differentiate the
members of superclass from the members of subclass, if they have same names.
It is used to invoke the superclass constructor from subclass.
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.

2. What is single inheritance?


A class extends another one class only then we call it a single inheritance.

3. Can we implement Multiple Inheritance in java?


Yes, we can implement multiple inheritances using interface in java

4. Define Inheriatnce.
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called parent or super class and
the new class is called child or subclass.

5. Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
P
-J
IT
Ex.No: 4(b)

V STUDENT INFORMATION SYTEM USING MULTILEVEL


INHERITANCE
M
AIM:
To write a Java program to implement Student Information System using multilevel
inheritance concept.

ALGORITHM:
1. Start the program.
2. Declare the base class student.
3. Declare and define the function getdata() that gets student name and regno.
4. Declare the other class marks as derived class of base class student.
5. Declare and define the function getmarks() inside derived class marks to get student
marks.
6. Declare the other class result as derived class of derived class marks.
7. Declare and define the function calculation() & show() inside the exam class to
calculate and print the result respectively.
8. Declare the derived class (result)object and call the functions .
9. Stop the program

SOURCE CODE

import java.util.Scanner;

class student
{
protected int regno; //Data Member Declaration protected
String name, dept;

void getdata() //Function to get student details


{
Scanner in = new Scanner(System.in);
System.out.println("Enter the Register Number");
regno = in.nextInt();
System.out.println("Enter the Name");
name = in.next();
}
}

class marks extends student //Deriving new class from base class
{
protected int m1, m2, m3, m4, m5;//Data Member Declaration

void getmarks() //Function to get student marks


{
Scanner in = new Scanner(System.in);
P
System.out.println("Enter mark1");

-J
m1 = in.nextInt();
System.out.println("Enter mark2");
m2 = in.nextInt();
System.out.println("Enter mark3");

IT
m3 = in.nextInt();
System.out.println("Enter mark4");
m4 = in.nextInt();
System.out.println("Enter mark5");
m5 = in.nextInt();

}
}

V
M
class result extends marks //Deriving new class from base class
{
private int total; //Data Member Declaration
private String result;
private float average;

void calculation()
{
total = m1 + m2 + m3 + m4 + m5;
average = (total) / 5;
if (m1 >= 50 && m2 >= 50 && m3 >= 50 && m4 >= 50 && m5 >= 50)
{
result = "PASS";
}
else
{
result = "FAIL";
}
}

void show()
{
System.out.println("\t\t\tStudent Details");
System.out.println("Name = " + name);
System.out.println("Register Number = " + regno);
System.out.println("Marks of 1st Subject = " + m1);
System.out.println("Marks of 2nd Subject = " + m2);
System.out.println("Marks of 3rd Subject = " + m3);
System.out.println("Marks of 4th Subject = " + m4);
System.out.println("Marks of 5th Subject = " + m5);
System.out.println("Total Marks = " + total);
System.out.println("Result = " + result);
System.out.println("Percentage = " + average + "%");
}
}

class J3cMultipleLevelInheritance
{
public static void main(String args[])
{
result r = new result();
System.out.println("STUDENT INFORMATION");
r.getdata(); //Calling Base class function using derived object
P
r.getmarks();

-J
r.calculation();
r.show();
}
}

IT
OUTPUT

V
M

RESULT

Thus the Student Information System using multilevel inheritance has been executed and
verified successfully.

Viva Question

1. What is multi level inheritance?


Multilevel inheritance refers to a mechanism in OO technology where one can inherit
from a derived class, thereby making this derived class the base class for the new class. As
you can see in below flow diagram C is subclass or child class of B and B is a child class of
A.
P
-J
IT
Ex.No:4(c) V HIERARCHICAL INHERITANCE
M
AIM:
To write a Java program to implement Hierarchical inheritance.

ALGORITHM:
1. Start the program.
2. Declare the base class class A with methodA() that prints “method of Class A”
3. Declare the derived class class B that extends from class A with methodB() that
prints” method of Class B “.
4. Declare the derived class class C that exrends from class A with methodC() that
prints” method of Class C“.
5. Declare the derived class class D that exrends from class A with methodD() that
prints” method of Class D“.
6. Declare a main class MyClass and create objects for class B , C , D.
7. Using those objects call method().
8. Stop the program

SOURCE CODE

class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}

class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
P
}

-J
class C extends A
{
public void methodC()
{

IT
System.out.println("method of Class C");

}
}

class D extends A
{
V
public void methodD()
M
{

System.out.println("method of Class D");


}
}

class MyClass
{
public void methodB()
{
System.out.println("method of Class B");
}
}

public static void main(String args[])


{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}

OUTPUT
P
-J
RESULT

IT
Thus the program for hierarchical inheritance executed and verified successfully.

V Viva Question
M
1. What is Inheritance in Java?
Answer: Inheritance is an Object oriented feature which allows a class to inherit
behavior and data from other class. For example, a class Car can extend basic feature of
Vehicle class by using Inheritance.
2. What is the difference between Polymorphism and Inheritance?
Answer: Both Polymorphism and Inheritance goes hand on hand, they help each other
to achieve their goal. Polymorphism allows flexibility, you can choose which code to run at
runtime by overriding. See the detailed answer for m ore details.

3. What happens if both, super class and sub class, have a field with same name.
Super class field will be hidden in the sub class. You can access hidden super class field
in sub class using super keyword.
4. Can a class extend more than one classes or does java support multiple inheritance? If
not, why?
No, a class in java can not extend more than one classes or java does not support
multiple inheritance. To avoid ambiguity, complexity and confusion, java does not supports
multiple inheritance. For example, If Class C extends Class A and Class B which have a
method with same name, then Class C will have two methods with same name. This causes
ambiguity and confusion for which method to use. To avoid this, java does not supports
multiple inheritance.
5. What is static method?
o A static method belongs to the class rather than object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o Static method can access static data member and can change the value of it.
6. Why main method is static?
Object is not required to call static method if It were non-static method,jvm creats
object first then call main() method that will lead to the problem of extra memory allocation.
7. Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
8. Main advantage of using Inheritance?
Using this feature you can reuse features, less memory wastage, less time required to
develop and application and improve performance of application.
P
-J
IT
Ex.No :5(a) INTERFACE

V
Aim: To create a Java Program to compute the Interface program
M
Algorithm
1. Start the program.
2. Create the Interface from ISports.
3. Create the class Cricket implements from ISports class.
4. Define a data member void setTeam and showRessult.
5. Create a class Hokey implements from ISports class.
6. Define a datat member void showTeam and showResult.
7. Create main class Sports.
8. Declare the objects for class cricket and hockey.
9. Stop the program.
Source Code

interface ISports
{
public void SetTeam(String t1,String t2, int score1, int score2);
public void ShowResult();
}
int team1Runs,team2

class Cricket implements ISports


{
String team1,team2Runs;
public void SetTeam(String t1,String t2, int r1, int r2)
{
team1 = t1;
team2 = t2;
team1Runs = r1;
team2Runs = r2;
}

public void ShowResult()


{
System.out.println(team1 + "-" + team1Runs + " Runs");
System.out.println(team2 + "-" + team2Runs + " Runs");
}
}

class Hockey implements ISports


{
String team1,team2;
int team1Goals,team2Goals;
public void SetTeam(String t1,String t2, int r1, int r2)
{
P
team1 = t1;

-J
team2 = t2;
team1Goals = r1;
team2Goals = r2;
}

IT
public void ShowResult()
{
System.out.println(team1 + "-" + team1Goals + " Goals");
System.out.println(team2 + "-" + team2Goals + " Goals");

}
}

V
M
class Sports
{
public static void main(String args[])
{
Cricket c = new Cricket();
Hockey h = new Hockey();
c.SetTeam("India", "England",240,220);
h.SetTeam("India", "Germany",3,2);
c.ShowResult();
h.ShowResult();
}
}

Output

Result
P
Thus the Java Program to implement the concept of Interface has been created and

-J
executed successfully.

IT
Ex.No:5(b) MULTIPLE INHERITANCE

AIM:
V
To write a java program to implement multiple inheritance
M
ALGORITHM

1. Start the program.


2. Declare interface Printable and declare print().
3. Declare interface Showable that extends from interface Printable and declare show().
4. Declare class A7 that implements interface Printable and Showable.
5. Define the above mentioned methods with some message.
6. Create object for class A7 and call methods print() and show().
7. Stop the program

SOURCE CODE

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();
}
}
P
-J
IT
OUTPUT
V
M

RESULT

Thus the program to implement multiple inheritance executed and verified successfully.
P
-J
IT
Viva Question

1. What is Runtime Polymorphism?


Runtime polymorphism or dynamic method dispatch is a process in which a call to an

V
overridden method is resolved at runtime rather than at compile-time.
In this process, an overridden method is called through the reference variable of a super
class. The determination of the method to be called is based on the object being referred to by the
M
reference variable.

2. What is interface?
An interface in java is a blueprint of a class. It has static constants and abstract methods
only. The interface in java is a mechanism to achieve fully abstraction. There can be only
abstract methods in the java interface not method body. It is used to achieve fully abstraction
and multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.

3. Can you declare an interface method static?


No, because methods of an interface are abstract by default, and static and abstract
keywords can't be used together.

4. Why use interface


Here are mainly three reasons to use interface. They are given below.
1. It is used to achieve fully abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.

5. What is difference between abstract class and interface?

Abstract class Interface

1)An abstract class can have method body Interface have only abstract methods.
(non-abstract methods).

2)An abstract class can have instance An interface cannot have instance
variables. variables.

3)An abstract class can have constructor. Interface cannot have constructor.

4)An abstract class can have static methods. Interface cannot have static methods.

5)You can extends one abstract class. You can implement multiple interfaces.
P
-J
IT
Ex. No: 6 PACKAGE

AIM:
To write a java program to implement the concept of user defined packages.

ALGORITHM:

V
1. Start the program
2. Create the user defined package name as addsub and muldiv seperately.
M
3. Inside the package declare the method add() and sub() with parameters.
4. Inside the other package declare the method mul() and div() with parameters.
5. Declare the method as public to access in other classes.
6. Create the main class TestPackage.
7. Import the packages in the TestPackage class.
8. Create the object for the class to call the methods.
9. Stop the program.

Source Code
package addsub;
public class addsub
{
public void add(int a,int b)
{
int c=a+b;
System.out.println("The sum of two number is:"+c);
}
public void sub(int a,int b)
{
int c=a-b;
System.out.println("The difference of two number is:"+c);
}
}

package muldiv;
public class muldiv
{
public void mul(int a,int b)
{
int c=a*b;
System.out.println("The mul of two number is:"+c);
}
public void div(int a,int b)
{
int c=a/b;
System.out.println("The division of two number is:"+c);
}
}
P
-J
IT
import addsub.addsub;
import muldiv.muldiv;
class Testpackage
{
public static void main(String ar[])
{

V
addsub a=new addsub();
a.add(10,5);
M
a.sub(10,5);
muldiv m=new muldiv();
m.mul(10,5);
m.div(10,5);
}
}

Output

Result
Thus to create the user defined package concept using java program was successfully
implemented and verified.
P
-J
Viva Question

IT
1. Which package is always imported by default?
No. It is by default loaded internally by the JVM. The java.lang package is always
imported by default.

V
2. What do you understand by package access specifier?
 Public: Anything declared as public can be accessed from anywhere.
 Private: Anything declared in the private can’t be seen outside of its class.
M
Default: It is visible to subclasses as well as to other classes in the same package.

3. What is the package name for Exception , Error and Throwable classes?
Ans: java.lang

4. Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

5. How to access package from another package?


There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.

6. Define Package class.


The package class provides methods to get information about the specification and
implementation of a package. It provides methods such as getName(), getImplementationTitle(),
getImplementationVendor(), getImplementationVersion() etc.

7. To make a Java package named pkg:


1. Make a directory named pkg.
2. Put all the .java files for the classes and interfaces in the directory pkg.
3. Begin each of the .java files with a package declaration:
package pkg;
4. Compile the files by running javac from pkg's parent directory. For example,
javac pkg/*.java
5. Access the classes and interfaces of package pkg from other packages by importing its
definitions with an import line in every .java file that uses them:
import pkg;
6. Tell the Java interpreter how to find package pkg by putting pkg's parent directory on the
classpath, or by running the interpreter from that directory. If the full or relative
pathname of pkg's parent directory is pname, then java -cp pname ... will put pname on
the classpath and make package pkg accessible. If you have several packages in different
parent directories, separate the names with colons: java -cp pname:name2:dir3 .
P
-J
Ex.no: 7(a) ITEM EVENT HANDLING

IT
AIM:
To write a java program to implement the concept of Item Event Handling.

ALGORITHM:

V
1. Start the program.
2. Create a class ItemEvent .
3. Declare the variables for the class.
M
4. Create a main method and display the outputs by the objects.
5. Display the output by th ButtonClickListener by implementing Action Listener
6. Stop the program

SOURCE CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ItemEvent


{
private JFrame F;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public ItemEvent()
{
prepareGUI();
}
public static void main(String[] args)
{
ItemEvent IT = new ItemEvent();
IT.showEventDemo();
}

private void prepareGUI()


{
F = new JFrame("Item Event Handling");
F.setSize(400,400);
F.setLayout(new GridLayout(3, 1));
F.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
F.add(headerLabel);
F.add(controlPanel);
F.add(statusLabel);
F.setVisible(true);
P
}

-J
private void showEventDemo()
{
headerLabel.setText("Control in action: Button");
Button okButton = new Button("OK");

IT
Button submitButton = new Button("Submit");
Button cancelButton = new Button("Cancel");
okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");

V
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
M
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
F.setVisible(true);
}
private class ButtonClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if( command.equals( "OK" ))
{
statusLabel.setText("Ok Button clicked.");
}
else if( command.equals( "Submit" ) )
{
statusLabel.setText("Submit Button clicked.");
}
else
{
statusLabel.setText("Cancel Button clicked.");
}
}
}
}
P
-J
OUTPUT:

IT
V
M

RESULT:
Thus to create the Item Event Handling concept using java program was successfully
implemented and verified.
P
-J
Ex.no: 7(b) MOUSE EVENT HANDLING

IT
AIM:
To write a java program to implement the concept of Mouse Event Handling.

ALGORITHM:
1. Start the program.

V
2. Create a class MouseEvent .
3. Declare the variables for the class.
4. Create a main method and display the outputs by the objects.
M
5. Display the output by the MouseListenerExample by implementing MouseListener
6. Stop the program

PROGRAM:
import java.awt.*;
import java.awt.event.*;
public class MouseItemListener extends Frame implements MouseListener
{
Label l;
MouseItemListener()
{
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}

public void mouseReleased(MouseEvent e)


{
l.setText("Mouse Released");
}
public static void main(String[] args)
{
new MouseItemListener();
P
}

-J
}

OUTPUT:

IT
V
M

RESULT:
Thus to create the Item Event Handling concept using java program was successfully
implemented and verified.
P
-J
IT
Ex.no: 7(c) ACTION EVENT HANDLING

AIM:
To write a java program to implement the concept of Action Event Handling.

ALGORITHM:

V
1. Start the program.
2. Create a class ActionEvent.
M
3. Declare the variables for the class.
4. Create a main method and display the outputs by the objects.
5. Display the output by the ActionItemListener by implementing ActionListener
6. Stop the program

PROGRAM:
import java.awt.*;
import java.awt.event.*;

public class ActionItemListener


{
public static void main(String[] args)
{
Frame f=new Frame("Action Item Listener");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);

b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome to MVIT.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);

f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

}
}
P
-J
IT
OUTPUT:

V
M

RESULT:
Thus to create the Item Event Handling concept using java program was successfully
implemented and verified.
P
-J
Viva Question

IT
1. What is AWT?
AWT stands for Abstract Window Toolkit and infact it is a package – java.awt. The
classes of this package give the power of creating a GUI environment to the programmer in Java.

2. What is a panel?

V
To have a greater flexibility on the arrangement of components, panels are exetensively
used with layout managers. Components are added to panel and panel in turn can be added to a
container. That is, a panel can work like a container and a component. As container, components
M
can be added to it and as a component, panel can be added to a frame or applet.

3. What is the style of arranging components in a container by FlowLayout manager?


FlowLayout arranges the components (like buttons) on the north (top) side of the
container (like frame) centered. The alignment of center can be changed. The default gap
between the components is 5 pixels which can be changed programmatically.
The elements of a FlowLayout are organized in a top to bottom, left to right fashion.

4. What is the difference between the paint () and repaint() methods?


The paint () method supports painting via a Graphics object.
The repaint () method is used to cause paint() to be invoked by the AWT painting thread.

5. What is grid layout


The elements of a GridLayout are of equal size and are laid out using the square of a grid.

6. What is the difference between Swing and AWT components?


AWT components are heavy-weight, whereas Swing components are lightweight. Hence
Swing works faster than AWT. Heavy weight components depend on the local windowing
toolkit. For example, java.awt.Button is a heavy weight component. Pluggable look and feel
possible using java Swing. Also, we can switch from one look and feel to another at runtime in
swing which is not possible in AWT.
P
-J
IT
Ex no: 8 FILE HANDLING

Aim:
To create a java program for the concept of File Handling

Algorithm
V
1. Start the program
M
2. Declare the class file CopyFile and declare the variables
3. Create a main method and assign the various exception
4. Declare the statements inside the try block
5. Execute the program and display the results
6. Stop the program

SOURCE CODE:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class CreateFile


{
public static void main(String[] args)
{
try{
// Create new file
String content = "This is the content to write into create file";
String path="E:\\Sample.txt";
File file = new File(path);

// If file doesn't exists, then create it


if (!file.exists()) {
file.createNewFile();
}
else
{
System.out.println("File already exists.");
}

FileWriter fw = new FileWriter(file.getAbsoluteFile());

BufferedWriter bw = new BufferedWriter(fw);

// Write in file
bw.write(content);

// Close connection
bw.close();
// Read from file
FileReader fr=new FileReader(file.getAbsoluteFile());
int i;
P
while((i=fr.read())!=-1)

-J
System.out.println((char)i);
fr.close();
}
catch(Exception e){

IT
System.out.println(e);
}
}
}

OUTPUT

V
M
RESULT:
Thus to create the File handling concept using java program was successfully
implemented and verified.

Viva Question

1. What is file writer method and constructor for file writer?


Java FileWriter class is used to write character-oriented data to the file.
 FileWriter(String file)
 FileWriter(File file)
Methods:
 public void write(String text)
 public void write(char c)
 public void flush()
 public void close()

2. Whst is file reader?


Java FileReader class is used to read data from the file. It returns data in byte format like
FileInputStream class.
Methods of file reader class
1. public int read()
2. public void close()

3. Tell something about BufferedWriter? What are flush() and close() used for ?
A Buffer is a temporary storage area for data. The BufferedWriter class is an output
stream. It is an abstract class that creates a buffered character-output stream.

Flush() is used to clear all the data characters stored in the buffer and clear the buffer.

Close() is used to closes the character output stream.

4. Which is the abstract parent class of FileWriter ?


OutputStreamWriter
P
5. Define Stream.

-J
A stream can be defined as a sequence of data. There are two kinds of Streams −
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.

IT
Ex no: 9(a) SINGLE THREAD

Aim:

Algorithm V
To write a java program to implement the concept of threading.
M
1. Start the program.
2. Declare a sub-class "MyThread" and inherit the concept of threading.
3. Using the "run()" method, display the string.
4. Inside the main class "FirstThread", create an object for the sub-class.
5. Then using the object, the sub-class is invoked using the method "start()".
6. Stop the program.

Source code
class MyThread extends Thread
{
public void run()
{
System.out.println("Hello World!");
}
}

class FirstThread
{
public static void main(String [] args )
{
MyThread t = new MyThread();
t.start();
}
}

Output

Result
Thus to create the single thread using java program was successfully implemented and
verified
P
-J
IT
V
1. What is Thread in Java?
Viva Question

The thread is an independent path of execution. It's way to take advantage of multiple
M
CPU available in a machine. By employing multiple threads you can speed up CPU bound task.
For example, if one thread takes 100 milliseconds to do a job, you can use 10 thread to reduce
that task into 10 milliseconds. Java provides excellent support for multithreading at the language
level, and it's also one of the strong selling points.

2. What is the difference between Thread and Process in Java?


The thread is a subset of Process, in other words, one process can contain multiple
threads. Two process runs on different memory space, but all threads share same memory space.
Don't confuse this with stack memory, which is different for the different thread and used to store
local data to that thread.

3. How do you implement Thread in Java?


At the language level, there are two ways to implement Thread in Java. An instance
of java.lang.Thread represent a thread but it needs a task to execute, which is an instance
of interface java.lang.Runnable.
Since Thread class itself implement Runnable, you can override run() method either by
extending Thread class or just implementing Runnable interface.
For detailed answer and discussion see this article.

4. When threads are not lightweight process in java?


Threads are lightweight process only if threads of same process are executing
concurrently. But if threads of different processes are executing concurrently then threads
are heavy weight process.

5. What is life cycle of Thread, explain thread states? (Important)


Thread states/ Thread life cycle is very basic question, before going deep into concepts
we must understand Thread life cycle.
Thread has following states
 New
 Runnable
 Running
 Waiting/blocked/sleeping
 Terminated (Dead)
P
-J
IT
Ex.no: 9(b) MULTI THREAD

Aim:

V
To write a java program to implement the concept of multithreading.
M
Algorithm
1. Start the program.
2. Create 3 classes A,B and C by extending the Thread class.
3. Create Threadtest class and create main method in it.
4. Inside the main method by using run() method call the Thread class.
5. Then using the objects, the sub-class is invoked using the "start()" method.
6. Stop the program.

Source code
class A extends Thread
{
public void run()
{
System.out.println("thread A is started:");
for(int i=1;i<=5;i++)
{
System.out.println("\t from thread A:i="+i);
}
System.out.println("exit from thread A:");
}
}
class B extends Thread
{
public void run()
{
System.out.println("thread B is started:");
for(int j=1;j<=5;j++)
{
System.out.println("\t from thread B:j="+j);
}
System.out.println("exit from thread B:");
}
}
class C extends Thread
{
public void run()
{
System.out.println("thread C is started:");
for(int k=1;k<=5;k++)
{
System.out.println("\t from thread C:k="+k);
}
System.out.println("exit from thread C:");
P
}

-J
}

IT
class Threadtest
{
public static void main(String arg[])
{

V
new A().start();
new B().start();
M
new C().start();
}
}

Output

Result
Thus to create the multithread using java program was successfully implemented and
verified.
P
-J
IT
Viva Question

V
1. What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Its main
advantage is:
M
o Threads share the same address space.
o Thread is lightweight.
o Cost of communication between processes is low.

2. What does join() method?


The join() method waits for a thread to die. In other words, it causes the currently running
threads to stop executing until the thread it joins with completes its task.

3. What is difference between wait() and sleep() method?


wait() sleep()
1) The wait() method is defined in The sleep() method is defined in
Object class. Thread class.
2) wait() method releases the lock. The sleep() method doesn't releases
the lock.

5. What are the benefits of multi-threaded programming?


In Multi-Threaded programming, multiple threads are executing concurrently that
improves the performance because CPU is not idle incase some thread is waiting to get some
resources. Multiple threads share the heap memory, so it’s good to create multiple threads to
execute some task rather than creating multiple processes. For example, Servlets are better in
performance than CGI because Servlet support multi-threading but CGI doesn’t.

6. Can we call run() method of a Thread class?


Yes, we can call run() method of a Thread class but then it will behave like a normal
method. To actually execute it in a Thread, we need to start it using Thread.start() method.
P
-J
IT
Ex. No: 10 AWT CONTROLS

Aim: V
M
To create a Java program to implement the concept of AWT controls.

Algorithm
1. Start the program.
2. Declare the class AwtControl extends from the class Frame and implements from the
ActionListener.
3. create a Labels, TextField, Choice,Checkbox, List, button, Panel, TextArea.
4. Define the method AwtControl and create the caption for those variables.
5. Define a method called actionPerformed for the action that is to be performed.
6. Define another method windowClosing for closing the window.
7. Create the object for class AwtControl in the main and execute.
8. Stop the program.

Source Code
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class AwtControl extends Frame implements ActionListener
{
Label l1,l2,l3,l4,l5,l6,l7;
TextField t1,t2,t3,t4;
Choice ch1;
Checkbox cb1,cb2;
CheckboxGroup cbg;
List lt;
Button b1, b2;
Panel p1;
TextArea ta;
public AwtControl()
P
{

-J
setLayout(new GridLayout(12,2));
ta= new TextArea(10,20);
l1=new Label("Student ID");

IT
l2=new Label("Name");
l3=new Label("College");
l4=new Label("Department");

V
l5=new Label("Gender");
l6=new Label("Extra Activities");
M
t1=new TextField(20);
t2=new TextField(20);
t3=new TextField(20);
ch1=new Choice();
ch1.addItem("CSE");
ch1.addItem("IT");
ch1.addItem("MCA");
ch1.addItem("ECE");
cbg=new CheckboxGroup();
cb1= new Checkbox("Male",cbg,true);
cb2=new Checkbox("Female",cbg, true);
p1= new Panel();
p1.add(cb1);
p1.add(cb2);
lt= new List();
lt.addItem("Sports");
lt.addItem("Graphics");
lt.addItem("Mobile Technology");
b1=new Button("Show");
b1.addActionListener(this);
b2=new Button("Exit");
b2.addActionListener(this);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(l4);
P
add(ch1);

-J
add(l5);
add(p1);
add(l6);

IT
add(lt);
add(b1);
add(b2);

} V
add(ta);
M
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b2)
{
System.exit(0);
}
ta.setText("");
ta.append(t1.getText() + "\n");
ta.append(t2.getText() + "\n");
ta.append(t3.getText() + "\n");
ta.append(ch1.getSelectedItem() + "\n");
ta.append(cbg.getSelectedCheckbox().getLabel() + "\n");
ta.append(lt.getSelectedItem() + "\n");
}
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0);
}
public static void main(String arg[])
{
AwtControl control = new AwtControl();
control.setSize(600,600);
control.setVisible(true);
}
}
P
-J
IT
Output

V
M

Result
P
Thus the Java Program to implement the concept of AWT controls has been created and executed

-J
successfully.

Viva Question

IT
1. What is AWT?
AWT stands for Abstract Window Toolkit and infact it is a package – java.awt. The

2.
V
classes of this package give the power of creating a GUI environment to the programmer in Java.

What is the super class of all components of Java?


It is java.awt.Component.
M
3. What is component?
By definition, the subclass of a java.awt.Component class is known as a component. A
component can be a Button or TextField etc. Using the component, a programmer can interact
with the running Java program (instead of using the traditional keyboard input) and can pass two
numbers to get the product or pass user name and password for validation.

4. What is a container?
By definition, the subclass of a java.awt.Container class is known as a container. A
container can be a Frame or Applet or Dialog box etc. A container holds the components. If
a button is to be displayed to the user, it must be added to a container.

5. What is a panel?
To have a greater flexibility on the arrangement of components, panels are exetensively
used with layout managers. Components are added to panel and panel in turn can be added to a
container. That is, a panel can work like a container and a component. As container, components
can be added to it and as a component, panel can be added to a frame or applet.

6. What is the method used to place some text in the text field?
setText(String str) method of TextField class.

7. What is the method used to get the data entered by the user in the text field?
getText() method of TextField class.

8. What is the method used to change the characters entered by the user in the text field
(used for password)?
setEchoChar(char ch) of TextField class.

9. How to make the text field non-editable by the user (user cannot enter anything)?
setEditable(boolean state) of TextField class. This type of text field is used only to
display text to the user.

10. What is the method used to change the foreground (text) color of components like text
field?
setForeground(Color clr) of java.awt.Component class.

11. What is the method used to know the label of the button clicked by the user?
getActionCommand() method of ActionEvent class.

12. What is the super class of TextField and TextArea?


java.awt.TextComponent (a subclass of java.awt.Component).

13. What is the method used to change the text of a Label?


P
setText(String str) method of Label class.

-J
14. What is the method used to retrieve the text of a Label?
getText() method of Label class.

IT
15. How many ways you can align the label in a container?
3 ways. The variables defined in Label class LEFT, RIGHT and CENTER
are used to change the alignment. Default alignment is left.

V
16. What is the method used to change the label of a button?
setLabel(String str) method of Button class.
M
17. What is the method used to retrieve the label of a button?
getLabel() method of Button class.

18. What is HeadlessExceptin?


It is an unchecked exception. This runtime exception is thrown when the
code that is dependent on the hardware like keyboard, display or mouse is called in
an environment that does not support a keyboard, display or mouse.

19. What is the listener used to handle the events of a text field?
java.awt.event.ActionListener interface
P
-J
Ex.no:11 APPLET

IT
AIM:
To write a java program to design and implement applet.

ALGORITHM:

V
1. Create a class Shape which extends the class Applet.
2. Initialize the thread using init() method and start it using start() method.
3. Draw different shapes such as oval, line and rectangle in the paint() method.
M
4. The stop() method is used to stop the thread
5. The destroy() method is used to destroy the thread.
6. Compile and run the program to verify the result

CODING:

//Applet Program to display Date & Time


import java.applet.*;
import java.awt.*;
import java.util.*;

/*<applet code="DigitalClock.class" width="300" height="200"> </applet> */

public class DigitalClock extends Applet implements Runnable


{
Thread t,t1;
Font font1;

public void init()


{
setBackground(Color.lightGray);
font1 = new Font( "Serif", Font.BOLD, 30 );
}

public void start()


{
t = new Thread(this);
t.start();
}

public void run()


{
t1 = Thread.currentThread();
while(t1 == t)
{
repaint();
try
{
t1.sleep(1000);
}
catch(InterruptedException e)
{
P
}

-J
}
}

public void paint(Graphics g)

IT
{
g.setColor(Color.blue);
g.setFont( font1 );
g.drawString(" DIGITAL CLOCK ", 25, 50);

V
Calendar cal = new GregorianCalendar();

String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));


M
String month = String.valueOf(cal.get(Calendar.MONTH)+1);
String year = String.valueOf(cal.get(Calendar.YEAR));
g.drawString(day + " / " + month + " / " + year, 85, 98);

String hour = String.valueOf(cal.get(Calendar.HOUR));


String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" + minute + ":" + second, 100, 148);
}
}

OUTPUT

RESULT
Thus the applet program executed and verified successfully.
P
Viva Question

-J
1. What is the super class of all containers?
It is java.awt.Container.

2. What is a layout manager?

IT
A layout manager dictates the style of arranging the components in a container.

3. What is the style of GridLayout?


The whole container like frame is divided into rows and columns forming a grid of cells.

V
Each cell can accomodate one component. That is, in a grid of 3 rows and 4 columns, we can
place 12 components. The default gap of 0 pixels can be changed.

4. What is the method used to change the background color of components like text field?
M
setBackground(Color clr) of java.awt.Component class.

5. Define Applet.
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.

6. State the Life Cycle of an Applet.


 init − This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
 start − This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.
 stop − This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
 destroy − This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
 paint − Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the java.awt.
P
Ex.no:12 REMOTE METHOD INVOCATIONS

-J
Aim:
To develop a program for performing arithmetic operations like addition, subtraction,
multiplication and division of RMI.

IT
Procedure:
Step 1: Create AllServerIntf.java which defines the remote interface that is provided by
the server.
Step 2: This file contains four methods that accept two double arguments and returns the

V
calculated value.
Step 3: The second file to be created is AllServerImpl.java which implements the remote
interface.
M
Step 4: This java file extends unicast remote object which provides functionality that is
needed to make object available from remote machines.
Step 5: The next file created is AllServer.java which will update the rmi registry on that
machine.This is done by rebind () method of naming class.
Step 6: The last file is AllClient.java which implements the client side of this distributed
application.
Step 7: This file requires four command line arguments which are IP address, two
arguments from the computation and the arithmetic operator name.
Step 8: Compile and execute the program according to the settings given below.

Settings:

Step one:
Enter and compile the source code
The compilation of the source code can be done by command line, as shown here:
javac AllServerIntf.java
javac AllServerImpl.java
javac AllServer.java
javac AllClient.java
Step Two:
Generate Stubs and Skeletons
To generate Stubs and Skeletons, we use a tool called the RMI compiler, which is
invoked from the command line,
rmic AllServerImpl

Step Three:
Install Files on the Client and Server Machines
Copy AllClient.class, AllServerImpl_Stub.class and AllServerIntf.class to a
directory on the client machine.

Copy AllServerIntf.class, AllServerImpl.class, AllServerImpl_Skel.class,


AllServerImpl_Stub and AllServer.class to a directory on the server machine.
P
Step Four:

-J
Start the RMI Registry on the Server Machine
The JDK provides a program called rmiregistry, which executes on the server
machine. It maps names to object references. Start the RMI Registry from the command
line as show below:

IT
start rmiregistry

Step fine:
Start the Server
The server code is started from the command line:

Step Six:
V java AllServer
M
Start the Client
The client code can be invoked by the command line by using one of the two
formats shown below:
java AllClient localhost 5 4 add
java AllClient 172.16.11.162 5 4 add

PROGRAM CODING:

AllserverIntf.java:
import java.rmi.*;
public interface AllServerIntf extends Remote
{
double add(double d1,double d2)throws RemoteException;
double sub(double d1,double d2)throws RemoteException;
double mul(double d1,double d2)throws RemoteException;
double div(double d1,double d2)throws RemoteException;
}

AllServerImpl.java:
import java.rmi.*;
import java.rmi.server.*;
public class AllServerImpl extends UnicastRemoteObject implements AllServerIntf
{
public AllServerImpl() throws RemoteException
{
}
public double add(double d1,double d2) throws RemoteException
{
return d1+d2;
}
public double sub(double d1,double d2) throws RemoteException
{
P
return d1-d2;

-J
}
public double mul(double d1,double d2) throws RemoteException
{
return d1*d2;

IT
}
public double div(double d1,double d2) throws RemoteException
{
return d1/d2;
}
}

AllClient.java:
V
M
import java.rmi.*;
public class AllClient
{
public static void main(String args[])
{
try
{
String allserverURL="rmi://"+args[0]+"/AllServer";
AllServerIntf allserverintf=(AllServerIntf)Naming.lookup(allserverURL);
System.out.println("the first number is"+args[1]);
double d1=Double.valueOf(args[1]).doubleValue();
System.out.println("the second number is:"+args[2]);
double d2=Double.valueOf(args[2]).doubleValue();
if(args[3].equals("add"))
{
System.out.println("the sum is:"+allserverintf.add(d1,d2));
}
else if(args[3].equals("sub"))
{
System.out.println("the sum is:"+allserverintf.sub(d1,d2));
}
else if(args[3].equals("mul"))
{
System.out.println("the sum is:"+allserverintf.mul(d1,d2));
}
else if(args[3].equals("div"))
{
System.out.println("the sum is:"+allserverintf.div(d1,d2));
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
P
}

-J
}
}

AllServer.java:

IT
import java.rmi.*;
import java.net.*;
public class AllServer
{
public static void main(String args[])
{
V
try
{
M
AllServerImpl allserverimpl = new AllServerImpl();
Naming.rebind("AllServer",allserverimpl);
}
catch(Exception e)
{
System.out.println("Exception :"+e);
}
}
}

OUTPUT
RMI REGISTRY:
P
SERVER SIDE:

-J
IT
V
M
CLIENT SIDE:

ADDITION:
P
SUBRACTION:

-J
IT
MULTIPLICATION:
V
M

DIVISION:

RESULT:
Thus the program for performing arithmetic operations like addition, subtraction,
multiplication and division using RMI has been executed and verified.
P
EX NO: 13 JAVA DATABASE CONNECTIVITY

-J
Aim:
To create a java program for the concept of JDBC.

IT
ALGORITHM:
1. Start the program
2. Create form HomePage, NewUSer,ViewResult
3. Create form using awt control, Swing components
4. Create the database and tables in mysql

V
5. Add package mysql-connector.jar file.
6. Execute the program and display the output
7. Stop the program
M
HomePage.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class HomePage extends JFrame implements ActionListener
{
JButton reg, view;
HomePage()
{
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("HomePage ");
reg = new JButton("Registration");
view = new JButton("viewResult");
reg.addActionListener(this);
view.addActionListener(this);
reg.setBounds(100, 30, 200, 30);
view.setBounds(100, 70, 200, 30);
add(reg);
add(view);
setVisible(true);
setSize(400, 400);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == reg)
{
new NewUser();
}
else
{
P
new ViewResult();

-J
}
}
public static void main(String args[])
{

IT
new HomePage();
}
}

NewUser.java

import java.awt.*;V
import javax.swing.*;

import java.awt.event.*;
M
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewUser extends JFrame implements ActionListener
{
JLabel l1, l2, l3, mark1, mark2, mark3;
JTextField tf1, tf2, tf3, tf4, tf5;
JButton submit, btn2;
NewUser()
{
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Registration Form in Java");
l1 = new JLabel("Registration Form in Windows Form:");
l1.setForeground(Color.blue);
l1.setFont(new Font("Serif", Font.BOLD, 20));
l2 = new JLabel("Name:");
l3 = new JLabel("Register Number:");
mark1 = new JLabel("Mark1:");
mark2= new JLabel("Mark2:");
mark3= new JLabel("Mark3:");
tf1 = new JTextField();
tf2 = new JTextField();
tf3 = new JTextField();
tf4 = new JTextField();
tf5 = new JTextField();
submit = new JButton("Submit");
btn2 = new JButton("Back");
submit.addActionListener(this);
btn2.addActionListener(this);
l1.setBounds(100, 30, 400, 30);
l2.setBounds(80, 70, 200, 30);
l3.setBounds(80, 110, 200, 30);
P
mark1.setBounds(80, 150, 200, 30);

-J
mark2.setBounds(80, 190, 200, 30);
mark3.setBounds(80, 230, 200, 30);
tf1.setBounds(300, 70, 200, 30);
tf2.setBounds(300, 110, 200, 30);

IT
tf3.setBounds(300, 150, 200, 30);
tf4.setBounds(300, 190, 200, 30);
tf5.setBounds(300, 230, 200, 30);
submit.setBounds(50, 350, 100, 30);
btn2.setBounds(170, 350, 100, 30);
add(l1);
add(l2);
add(tf1);
V
M
add(l3);
add(tf2);
add(mark1);
add(tf3);
add(mark2);
add(tf4);
add(mark3);
add(tf5);
add(submit);
add(btn2);
setVisible(true);
setSize(700, 700);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == submit)
{
String name=String.valueOf(tf1.getText());
int regno=Integer.parseInt(tf2.getText());
int m1=Integer.parseInt(tf3.getText());
int m2=Integer.parseInt(tf4.getText());
int m3=Integer.parseInt(tf5.getText());
String connectionUrl = "jdbc:mysql://localhost:3306/db";
String dbUser = "root";
String dbPwd = "root";
Connection conn;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(connectionUrl,dbUser,dbPwd);
//Statement stmt = conn.createStatement();
PreparedStatement st=conn.prepareStatement("INSERT INTO
marksheet(name,regno,mark1,mark2,mark3) VALUES(?,?,?,?,?)");
P
st.setString(1,name);

-J
st.setInt(2,regno);
st.setInt(3,m1);
st.setInt(4,m2);
st.setInt(5,m3);

IT
st.executeUpdate();
if (conn != null)
{
conn.close();
conn = null;

}
}
V
System.out.println("student details Inserted successfully");
M
catch (SQLException sqle)
{
System.out.println("SQL Exception thrown: " + sqle);
}
catch (ClassNotFoundException ex)
{
Logger.getLogger(NewUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
new HomePage();
}
}
}

ViewResult.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

class ViewResult extends JFrame implements ActionListener


{
JLabel l1,l2,l3,l4,l5;
JTextField tf1;
JButton btn1, btn2;
ViewResult()
{
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("VIEW ");
l1 = new JLabel("REG NO:");
P
l2=new JLabel("NAME");

-J
l3=new JLabel("Mark1");
l4=new JLabel("Mark2");
l5=new JLabel("Mark3");
l1.setForeground(Color.blue);

IT
l1.setFont(new Font("Serif", Font.BOLD, 20));
tf1 = new JTextField();
btn1 = new JButton("Submit");
btn2 = new JButton("Back");
btn1.addActionListener(this);

V
btn2.addActionListener(this);
l1.setBounds(100, 30, 400, 30);
tf1.setBounds(100, 70, 200, 30);
M
l2.setBounds(100,110,400,60);
l3.setBounds(100,150,400,60);
l4.setBounds(100,190,400,60);
l5.setBounds(100,230,400,60);
btn1.setBounds(50, 350, 100, 30);
btn2.setBounds(170, 350, 100, 30);
add(l1);
add(tf1);
add(l2);
add(l3);
add(l4);
add(l5);
add(btn1);
add(btn2);
setVisible(true);
setSize(700, 700);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == btn1)
{
String regno=tf1.getText();
String connectionUrl = "jdbc:mysql://localhost:3306/db";
String dbUser = "root";
String dbPwd = "root";
Connection conn;
ResultSet rs;
String queryString = "select * from marksheet where regno='"+regno+"'";
try
{
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(queryString);
P
while(rs.next())

-J
{
l2.setText("Name="+rs.getString("name"));
l3.setText("Mark1="+rs.getInt("mark1"));
l4.setText("Mark2="+rs.getInt("mark2"));

IT
l5.setText("Mark3="+rs.getInt("mark3"));
}
if (conn != null)
{
conn.close();

}
} V conn = null;
M
catch (SQLException sqle)
{
System.out.println("SQL Exception thrown: " + sqle);
}
}
else
{
new HomePage();
}
}

OUTPUT

HOME PAGE
P
NEW USER

-J
IT
V
M

VIEW RESULT
P
-J
IT
V
M

Result
Thus to create a java program to implement the JDBC was successfully implemented and
verified.
P
Viva Question

-J
1. What is JDBC connectivity?
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.

IT
2. What is a JDBC DriverManager?
JDBC DriverManager is a class that manages a list of database drivers. It matches
connection requests from the java application with the proper database driver using
communication subprotocol.

V
3. What is JDBC Driver?
JDBC Driver is a software component that enables java application to interact with the
M
database.
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

4. What are the steps to connect to the database in java?


o Registering the driver class
o Creating connection
o Creating statement
o Executing queries
o Closing connection

5. What are the JDBC API components?


The java.sql package contains interfaces and classes for JDBC API.
Interfaces:
o Connection
o Statement
o PreparedStatement
o ResultSet
o ResultSetMetaData
o DatabaseMetaData
o CallableStatement etc.
Classes:
o DriverManager
o Blob
o Clob
o Types
o SQLException etc.
6. What are the JDBC statements?
There are 3 JDBC statements.
1. Statement 2. PreparedStatement 3. CallableStatement
P
EX NO: 14 TCP-ONE WAY COMMUNICATION

-J
AIM
To write a java program to implement one way communication using TCP

ALGORITHM

IT
SERVER
Step 1: Start the program.
Step 2: Import the necessary java.net package and other packages.
Step 3: Create objects for ServerSocket, Socket, DataInputStream and PrintStream to

V
transfer the data.
Step 4: The readLine method reads the message .
Step 5: Using PrintStream transfer the data in OutputStream via a port.
M
Step 6: The data is transferred from server until an “end ” string occurs.
Step 7: If an “end ” is encountered, close the socket and exit the program.
Step 8: Stop the program.

CLIENT
Step 1: Start the program.
Step 2: Import the necessary java.net package and other packages.
Step 3: Create objects for Socket and DataInputStream to receive the server data.
Step 4: The getInputStream method gets the data from the socket.
Step 5: The readLine method reads the message received from server.
Step 6: The socket will close, when an end is encountered
Step 8: Stop the program.

SOURCE CODE

SERVER
import java.io.*;
import java.net.*;
import java.util.*;
class TcpOneWayChatServer
{
public static void main(String a[])throws IOException
{
// Establishes connection to the specified IP and Port Number
ServerSocket servsock=new ServerSocket(8000);
// Opens the socket and binds the connection on the port number 8000
Socket sock=servsock.accept();
//DataInputStream dis=new DataInputStream(System.in);
Scanner s=new Scanner(System.in);
PrintStream ps=new PrintStream(sock.getOutputStream());
System.out.println("Connection established successfully!");
System.out.println("You can start sending messages now!");
System.out.println("Enter 'end' to quit");
while(true)
P
{

-J
System.out.println("Enter message to send:");
// reads the input message string from the input device
String str=s.nextLine();
ps.println(str);

IT
//checks for end of message
if(str.equals("end"))
{
//Closes the socket
servsock.close();

}
} V break;
M
}
}

CLIENT
import java.io.*;
import java.net.*;
class TcpOneWayChatClient
{
public static void main(String args[]) throws IOException
{
// Establishes connection to the specified IP and Port Number
Socket sock=new Socket("localHost",8000);
String str;
// Receives the messages from the server
DataInputStream dis=new DataInputStream(sock.getInputStream());
System.out.println("Connection established successfully!");
System.out.println("Listening for server...");
while(true)
{
// Reads the input from server
str=dis.readLine();
System.out.println("Message Received:"+str);
if (str.equals("end"))
{
sock.close(); //Close the socket
break;
}
}
}
}
OUTPUT :
SERVER
P
-J
IT
V
M
CLIENT

Result
Thus to create a java program to implement the TCP one way communication was
successfully implemented and verified.

EX NO: 15 MOVING OBJECT

AIM
P
To write a java program to implement Custom Graphics using key/button to move a

-J
object left or right.

PROGRAM

IT
import java.awt.*; // Using AWT's Graphics and Color
import java.awt.event.*; // Using AWT's event classes and listener interface
import javax.swing.*; // Using Swing's components and containers
/**
* Custom Graphics Example: Using key/button to move a line left or right.
*/
V
@SuppressWarnings("serial")
public class CGMoveALine extends JFrame {
M
// Define constants for the various dimensions
public static final int CANVAS_WIDTH = 400;
public static final int CANVAS_HEIGHT = 140;
public static final Color LINE_COLOR = Color.BLACK;
public static final Color CANVAS_BACKGROUND = Color.CYAN;

// The moving line from (x1, y1) to (x2, y2), initially position at the center
private int x1 = CANVAS_WIDTH / 2;
private int y1 = CANVAS_HEIGHT / 8;
private int x2 = x1;
private int y2 = CANVAS_HEIGHT / 8 * 7;

private DrawCanvas canvas; // The custom drawing canvas (an innder class extends JPanel)

// Constructor to set up the GUI components and event handlers


public CGMoveALine() {
// Set up a panel for the buttons
JPanel btnPanel = new JPanel(new FlowLayout());
JButton btnLeft = new JButton("Move Left ");
btnPanel.add(btnLeft);
btnLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
x1 -= 10;
x2 -= 10;
canvas.repaint();
requestFocus(); // change the focus to JFrame to receive KeyEvent
}
});
JButton btnRight = new JButton("Move Right");
btnPanel.add(btnRight);
btnRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
x1 += 10;
P
x2 += 10;

-J
canvas.repaint();
requestFocus(); // change the focus to JFrame to receive KeyEvent
}
});

IT
// Set up a custom drawing JPanel
canvas = new DrawCanvas();
canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));

V
// Add both panels to this JFrame's content-pane
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
M
cp.add(canvas, BorderLayout.CENTER);
cp.add(btnPanel, BorderLayout.SOUTH);

// "super" JFrame fires KeyEvent


addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent evt) {
switch(evt.getKeyCode()) {
case KeyEvent.VK_LEFT:
x1 -= 10;
x2 -= 10;
repaint();
break;
case KeyEvent.VK_RIGHT:
x1 += 10;
x2 += 10;
repaint();
break;
}
}
});

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Handle the CLOSE button


setTitle("Move a Line");
pack(); // pack all the components in the JFrame
setVisible(true); // show it
requestFocus(); // set the focus to JFrame to receive KeyEvent
}

/**
* Define inner class DrawCanvas, which is a JPanel used for custom drawing.
*/
class DrawCanvas extends JPanel {
P
@Override

-J
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(CANVAS_BACKGROUND);
g.setColor(LINE_COLOR);

IT
g.drawLine(x1, y1, x2, y2); // Draw the line
}
}

// The entry main() method

V
public static void main(String[] args) {
// Run GUI codes on the Event-Dispatcher Thread for thread safety
SwingUtilities.invokeLater(new Runnable() {
M
@Override
public void run() {
new CGMoveALine(); // Let the constructor do the job
}
});
}
}

OUTPUT

You might also like