Java Lab
Java Lab
-J
IT
V
M
JAVA PROGRAMMING
LAB MANUAL
II YEAR
IV SEMESTER
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
-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
-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.
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;
}
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.
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
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.
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 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.
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.
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");
}
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;
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
{
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.
4. Define Inheriatnce.
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
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.
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;
class marks extends student //Deriving new class from base class
{
protected int m1, m2, m3, m4, m5;//Data Member Declaration
-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
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
{
class MyClass
{
public void methodB()
{
System.out.println("method of Class B");
}
}
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
-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
SOURCE CODE
interface Printable
{
void print();
}
interface Showable
{
void show();
}
RESULT
Thus the program to implement multiple inheritance executed and verified successfully.
P
-J
IT
Viva Question
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.
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
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 ItemEvent()
{
prepareGUI();
}
public static void main(String[] args)
{
ItemEvent IT = new ItemEvent();
IT.showEventDemo();
}
-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");
}
-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.*;
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.
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;
// 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
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.
-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.
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.
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.
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.
-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.
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:
-J
}
}
IT
{
g.setColor(Color.blue);
g.setFont( font1 );
g.drawString(" DIGITAL CLOCK ", 25, 50);
V
Calendar cal = new GregorianCalendar();
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.
IT
A layout manager dictates the style of arranging the components in a container.
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.
-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.
-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.*;
-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)
-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.
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)
-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);
/**
* 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
}
}
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