[go: up one dir, main page]

0% found this document useful (0 votes)
10 views58 pages

Java Lab Mannual

The document is a laboratory manual for Advanced Programming in Java, detailing a series of experiments for II CSE A & B students. It includes various programming tasks such as implementing constructors, function overloading, inheritance, exception handling, and GUI development using JavaFX. Each section outlines the aim, algorithm, and source code for the experiments, demonstrating practical applications of Java programming concepts.

Uploaded by

jasmineflora2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views58 pages

Java Lab Mannual

The document is a laboratory manual for Advanced Programming in Java, detailing a series of experiments for II CSE A & B students. It includes various programming tasks such as implementing constructors, function overloading, inheritance, exception handling, and GUI development using JavaFX. Each section outlines the aim, algorithm, and source code for the experiments, demonstrating practical applications of Java programming concepts.

Uploaded by

jasmineflora2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

ADVANCED PROGRAMMING JAVA LABORATORY

LAB MANUAL
II CSE A & B
II Year / IV Semester
LIST OF EXPERIMENTS

1. Program to implement constructors and destructors with array of objects.

2. Program to demonstrate function overloading.

3. Program to implement different types of inheritances like multiple, Multilevel and hybrid.

4. I/O Program to demonstrate the use of abstract classes.

5. Program to demonstrate I/O streams and functions.

6. Program to perform all possible type conversions.

7. Program to demonstrate exception handling technique.

8. Program to implement networking concepts.

9. Program to design and implement JDBC.

10. Program to design an event handling event for simulating a simple calculator.

11. Build GUI based application development using JavaFX.


TABLE OF CONTENTS

SL.NO TITLE PAGE NO


1 CLASSES AND OBJECTS
1(A) SIMPLE STUDENT CLASS WITHOUT ACCESS SPECIFIERS
1(B)(i) SIMPLE STUDENT CLASS WITH ACCESS SPECIFIERS
1(B)(ii) SIMPLE STUDENT CLASS WITH ACCESS SPECIFIERS

2 CONSTRUCTOR AND DESTRUCTOR

3 FUNCTION OVERLOADING
A) SINGLE INHERITANCE
B) MULTILEVEL INHERITANCE
4 C) HIERARCHICAL INHERITANCE
D) HYBRID INHERITANCE
E) MULTIPLE INHERITANCE

5 ABSTRACT CLASS

6 I/O STREAMS

7 TYPE CONVERSION

8
EXCEPTION HANDLING – DIVIDE BY ZERO
9 EVENT HANDLING- CALCULATOR

10 JDBC

11 REMOTE METHOD INVOCATION

12 NETWORKING – TCP ONE WAY COMMUNICATION

13 Build GUI based application development using javafx.


1.(A) CLASSES AND OBJECTS- SIMPLE STUDENT CLASS WITHOUT ACCESS SPECIFIERS

AIM:
To write a Java program to implement a simple student class without access specifiers.

ALGORITHM:
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.
6. Print the two data members of student class.
7. Stop the program

SOURCE CODE

package javaapplication1;

/**
*
* @author
MitStaff */

//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[])
{
// Object Creation For Class
student s=new student();
s.regno = 100;
s.name = "John Marshal";

System.out.println("Reg No " + s.regno);


System.out.println("Name " + s.name);
}
}
OUTPUT

RESULT

Thus the Java program to implement a simple student class without access specifiers
have been completed successfully and the output is verified.
1.(B)(i) CLASSES AND OBJECTS - SIMPLE STUDENT CLASS WITH ACCESS SPECIFIERS

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

ALGORITHM:
1. Start the program.
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 .
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;

/**
*
* @author
MitStaff */

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

public class J2bSimpleClass


{
public static void main(String args[])
{
student s=new student();
s.getdata();
s.showdata();

//s.regno = 10; //ERROR: regno is private


}
}

OUTPUT

RESULT

Thus the Java program to implement a simple student class with access specifiers have been
completed successfully and the output is verified.
1.(B)(ii) CLASSES AND OBJECTS - SIMPLE STUDENT CLASS WITH ACCESS SPECIFIERS

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

ALGORITHM:
1. Start the program.
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;

/**
*
* @author
MitStaff */

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

RESULT

Thus the Java program to implement a simple student class with access specifiers have been
completed successfully and the output is verified.
2(A) CONSTRUCTOR AND DESTRUCTOR –Types of Constructors

AIM:

To write a Java program to demonstrate Constructor and Destructor.

ALGORITHM:
1. Start the program.
2. Declare the class name as Shape with data members and member functions.
3. The default constructor Shape initializes the data members with default values.
4. The member function displayDimension() displays with the initialized values.
5. Create a main class ConstAndDest.
6. Create 4 instances (nodim,line,rectangle1,cuboid,rectangle2)of Shape class.
7. Objects nodim,line,rectangle1 and cuboid invokes default ,one ,two, three parameterized
constructors respectively.
8. Object rectangle2 invokes copy constructor to copy the data member values of object
rectangle1.
9. Call the displayDimension() method with objects, which displays the assigned values.
10. Stop the program
SOURCE CODE

package javaapplication5;

/**
*
* @author
MitStaff */
// PROGRAM TO IMPLEMENT DEFAULT, PARAMETERISED & COPY CONSTRUCTOR

class Shape
{
//variables declared within class are INSTANCE VARIABLES
private int length;
private int breadth;
private int height;

//DEFAULT CONSTRUCTOR
Shape()
{
System.out.println("\n No-Argument Constructor (i.e.) Default Constructor is invoked");
}

//PARAMETERISED CONSTRUCTOR WITH ONE ARGUMENT


Shape(int l)
{
//variables are LOCAL VARIABLES , if
// 1. PASSED AS ARGUMENTS
// 2. declared within constructor (i.e. in LOCAL SCOPE)
System.out.println("\none-Argument Constructor is
invoked"); length=l;
}

//PARAMETERISED CONSTRUCTOR WITH TWO ARGUMENT


Shape(int l, int b)
{
System.out.println("\n two-Argument Constructor is invoked");
length=l;
breadth=b;
}

//PARAMETERISED CONSTRUCTOR WITH THREE ARGUMENT


Shape(int length, int breadth, int height) {

//here length denotes LOCAL VARIABLE AND this.length denotes INSTANCE VARIABLE
System.out.println("\n three-Argument Constructor is invoked"); this.length=length;

this.breadth=breadth;
this.height=height;
}

//COPY CONSTRUCTOR
Shape(Shape s)
{
System.out.println("\n Copy Constructor is invoked");
length=s.length;
breadth=s.breadth;
height=s.height;
}

//MEMBER FUNCTION OF THE CLASS shape


void displayDimension()
{
System.out.println("length is "+length+" breadth is "+breadth+" height is "+height );
}
}

public class ConstAndDest


{

public static void main(String[] args)


{
Shape nodim = new Shape();
System.out.println("Object nodim's Details are");
nodim.displayDimension();

Shape line = new Shape(5);


System.out.println("Object line's Details are");
line.displayDimension();

Shape rectangle1 = new Shape(3,5);


System.out.println("Object rectangle1's Details
are"); rectangle1.displayDimension();

Shape cuboid = new Shape(4,5,6);


System.out.println("Object cuboid's Details are");
cuboid.displayDimension();

Shape rectangle2 = new Shape(rectangle1);


System.out.println("Object rectangle2's(i.e., copy of rectangle1) Details
are"); rectangle2.displayDimension();
}
}

OUTPUT

RESULT

Thus the constructors and destructors program executed and verified successfully.
2(B) CONSTRUCTOR AND DESTRUCTOR – with Array of Objects

AIM:

To write a Java program to demonstrate Constructor and Destructor with Array of Objects.

ALGORITHM:
11. Start the program.
12. Declare the class name as Student with data members and member functions.
13. The default constructor Student initializes the data members with end user values.
14. The member function showData() displays with the initialized values.
15. Create a main class CandDwithAoO.
16. Create array of instances variables of Student class.
17. For created references allocate memory using new keyword in a for loop, which
automatically initializes the data members.
18. Call the showData () method with objects, which displays the assigned values.
19. Stop the program
SOURCE CODE

package javaapplication4;
import java.util.Scanner;

class Student
{
String name;
int rollno;

Student()
{
Scanner sin = new Scanner(System.in);
System.out.println("Enter Name : ");
name=sin.next();
System.out.println("Enter Roll No : ");
rollno=sin.nextInt();
}

void showData()
{
System.out.println("Student name is "+name);
System.out.println("Student rollno is "+rollno);
}
}

public class CandDwithAoO


{
public static void main(String [] args)
{
Student [] Students = new Student[100];
int i, count;
Scanner in=new Scanner(System.in) ;
System.out.println("Enter the number of students :");
count=Integer.parseInt(in.next());

for(i=0;i<count;i++)
{
System.out.println("ENTER DETAILS FOR
STUDENT"+(i+1)); Students[i]=new Student();
}

System.out.println("LIST OF STUDENTS WITH DETAILS ARE AS FOLLOWS:");


for(i=0;i<count;i++)
{
System.out.println("Student "+(i+1)+" details");
Students[i].showData();
}
}
}

OUTPUT

RESULT

Thus the constructors and destructors program executed and verified successfully.
3 FUNCTION OVERLOADING

AIM:

To write a Java program to demonstrate Function Overloading.

ALGORITHM:

1. Start the program.


2. Declare the class name as CalcVolume with data members and member functions.
3. Define the method named calculate three times each having three different parameters
but with same name.
4. calculate(int) calculates the volume of cube.
5. calculate(float,int) calculates volume of cylinder.
6. calculate(int,int) calculates volume of pyramid.
7. Create a main class OverloadingProgram and create instance of class CalcVolume.
8. Create a switch case with three choices volume of cube,cylinder and pyramid and a
default case.
9. Case 1: contains calculate(int) which displays the volume of cube.
10. Case 2: contains calculate(float,int) which displays the volume of cylinder.
11. Case 3: contains calculate(int,int) which displays the volume of pyramid.
12. Case 4: exit
13. Default for giving choices out of range.
14. Choice=4 then stop the program

SOURCE CODE

package javaapplication6;

import java.util.Scanner;

class VolumeCalculator //Class Declaration


{
void calculate(int a) //Overloaded Function to find volume of cube
{
System.out.println("\tVolume of Cube is(a*a*a):\t" + (a*a*a) +"\n");
}
void calculate(float r,int h) //Overloaded Function to find volume of cylinder
{
System.out.println("\tVolume of cylinder is(3.14*r*r*h):\t"+ 3.14*r*r*h +"\n");
}
void calculate(int basearea,int h) //Overloaded Function to find volume of pyramid
{
System.out.println("\tVolume of pyramid is((1/3)*B*h):\t"+ (((float)1/3)*basearea*h) +"\n");
}
}

public class FuncOvrldingDemo {


public static void main(String[] args) {
// TODO code application logic here
VolumeCalculator v=new VolumeCalculator(); //Object
declaration int a,l,b,ba,h,ch; //Variable Declaration float r;

Scanner sin = new Scanner(System.in);


do
{
System.out.println("To Find Volumes ");
System.out.println("1. Cube\t2. Cylinder\t3. Pyramid\t4. Exit");
System.out.print("Enter your choice:"); ch=sin.nextInt();

switch(ch)
{
case 1:
System.out.print("Enter the side of the cube:");
a=sin.nextInt();
v.calculate(a);
break;
case 2:
System.out.print("Enter the radius of the cylinder:");
r=sin.nextFloat();
System.out.print("Enter the height of the cylinder:");
h=(int) sin.nextFloat();
v.calculate(r,h);
break;
case 3:
System.out.print("Enter the length of base of the
pyramid:"); l=sin.nextInt();
System.out.print("Enter the breadth of base of the pyramid:");
b=sin.nextInt();
ba=l*b;
System.out.print("Enter the height of the
pyramid:"); //h=(int)sin.next();
//ERROR : INCOMPATIBLE TYPES - string cannot be converted to integer
h=Integer.parseInt(sin.next());
//if no Wrapper Class used then ERROR : INCOMPATIBLE TYPES - string
cannot //be converted to integer
v.calculate(ba,h);
break;
case 4:
System.exit(0);
break;
default:
System.out.println("\n\tINCORRECT CHOICE\nTRY AGAIN");
}
}while(ch!=4);
}
}
OUTPUT

RESULT

Thus the function overloading program executed and verified successfully.


4(A) SIMPLE SINGLE INHERITANCE

AIM:
To write a Java program to implement single inheritance using simple methods.

ALGORITHM:

1. Start the program.


2. Declare the base class A.
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

RESULT

Thus the program for single inheritance executed and verified successfully.
4(B) STUDENT INFORMATION SYSTEM USING SINGLE INHERITANCE

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

ALGORITHM:

1. Start the program.


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();
System.out.println("Enter mark5");
m5 = in.nextInt();
}
}
class exam extends student //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 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();
}
}
OUTPUT

RESULT

Thus the program for Student Information System using single inheritance executed
and verified successfully.
4(C) STUDENT INFORMATION SYTEM USING MULTILEVEL INHERITANCE

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

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

System.out.println("Enter mark5");
m5 = in.nextInt();
}
}

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
r.getmarks();
r.calculation();
r.show();
}

OUTPUT

RESULT

Thus the Student Information System using multilevel inheritance has been executed and
verified successfully.
4(D) HIERARCHICAL INHERITANCE

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");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
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

RESULT

Thus the program for hierarchical inheritance executed and verified successfully
4(D) HYBRID INHERITANCE

AIM:
To write a java program to implement hybrid inheritance

ALGORITHM

1. Start the program.


2. Declare interface A and declare methodA().
3. Declare interface B that extends from interface A and declare methodB().
4. Declare interface C that extends from interface A and declare methodC().
5. Declare class D that implements interface B and C.
6. Define the above mentioned methods with some message.
7. Create object for class D and call methodA(),methodB() and methodC().
8. Stop the program

SOURCE CODE

interface A

{
public void methodA();
}

interface B extends A
{
public void methodB();
}

interface C extends A
{
public void methodC();
}

class D implements B, C
{

public void methodA()


{
System.out.println("MethodA");
}

public void methodB()


{
System.out.println("MethodB");
}

public void methodC()


{
System.out.println("MethodC");
}

public static void main(String args[])


{
D obj1= new D();
obj1.methodA();
obj1.methodB();
obj1.methodC();
}

OUTPUT

RESULT

Thus the program to implement hybrid inheritance executed and verified successfully.
4(E) MULTIPLE INHERITANCE

AIM:
To write a java program to implement multiple inheritance

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

RESULT

Thus the program to implement multiple inheritance executed and verified successfully.
5 ABSTRACT CLASS

AIM:

To write a java program to demonstrate the use of abstract classes.

ALGORITHM:

1. Create an abstract class Shape


2. Declare display() as abstract method
3. Create circle class by extending shape class and override the display() method
4. Create rectangle class by extending shape class and override the display() method
5. Create triangle class by extending shape class and override the display() method
6. Create circle object and assign it to shape object reference and call display method
7. Create rectangle object and assign it to shape object reference and call display method
8. Create triangle object and assign it to shape object reference and call display method
9. Stop the program

SOURCE CODE

abstract class Shape


{

abstract void display();

class Circle extends Shape


{

void display()
{
System.out.println("You are using circle class");
}

class Rectangle extends Shape


{

void display()
{
System.out.println("You are using rectangle class");
}

class Triangle extends Shape


{

void display()
{
System.out.println("You are using triangle class");
}

class ShapeAbstract
{

public static void main(String args[])


{

Shape s = new Circle();


s.display();

s = new Rectangle();

s.display();

s = new Triangle();
s.display();
}

}
OUTPUT

RESULT

Thus the use of abstract class program executed and verified successfully
6 I/O STREAMS

AIM:

To write a java program to demonstrate simple i/o streams and its methods

ALGORITHM:

1. Start the program.


2. Create class TinyEdit.
3. Create a BufferedReader object br using the InputStreamReader.
4. Create a string array object str[].
5. Createth an integer variable i and initialize it to 0
6. Get the i string of str[] using the method readLine() of br .
7. If the entered string contains the substring “exit” then goto step 10.
8. Increment the value of i by one.
9. Goto step 6.
10. Create an integer variable i and initialize it to 0.
11. Display the content of the string array object str[i] using the standard console output
method.
th
12. If the i string of str[] contains the substring “exit” then goto step 15.
13. Increment the value of i by one.
14. Goto step 11.
15. Stop the program.

SOURCE CODE

import java.io.*;
class stream1
{
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));
String str[] = new String[100];
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
for (int i = 0; i< 100; i++)
{
str[i] = br.readLine();
if (str[i].equals("stop"))
{
break;
}
}
System.out.println("\nHere is your file:"); // display the lines
for (int i = 0; i< 100; i++)
{
if (str[i].equals("stop"))
{
break;
}
System.out.println(str[i]);
}
}
}
OUTPUT

RESULT

Thus the i/o stream demonstration program executed and verified successfully.
7 TYPE CONVERSION

AIM:

To write a java program to perform all possible type conversions.

ALGORITHM:

1. Create a class Test


2. Convert string to integer using Integer.parseInt() method
3. Convert integer to string using Integer.toString() method
4. Convert xxx datatype to string using xxx.toString() method
5. Convert string to xxx datatype using xxx.parsexxx() method
6. Convert string to other types using valueOf() method
7. Convert datatype1 to datatype2 using external type casting
8. Stop the program

SOURCE CODE

class type1 {

public static void main(String[] args) {


// Casting conversion (5.4) of a float literal to
// type int. Without the cast operator, this would
// be a compile-time error, because this is a
// narrowing conversion (5.1.3):

float fmin = Float.NEGATIVE_INFINITY;


float fmax = Float.POSITIVE_INFINITY;
int i = (int) 12.5f;
int f = 1;

int x = Integer.parseInt("9");
double c = Double.parseDouble("5");
int b = Integer.parseInt("444", 10); // 10 indicates decimal
int b1 = Integer.parseInt("444", 16); // 16 indicates hexa-decimal

// String conversion (5.4) of i's int value:


System.out.println("(int)12.5f==" + i);

// Assignment conversion (5.2) of i's value to type


// float. This is a widening conversion (5.1.2): float f = i;
// String conversion of f's float value:
System.out.println("after float widening: " + f);

// Numeric promotion (5.6) of i's value to type


// float. This is a binary numeric promotion.
// After promotion, the operation is float*float: System.out.print(f);
f = f * i;
//Two string conversions of i and f:
System.out.println("*" + i + "==" + f);

// Method invocation conversion (5.3) of f's value


// to type double, needed because the method Math.sin
// accepts only a double argument:
double d = Math.sin(f);

// Two string conversions of f and d:


System.out.println("Math.sin(" + f + ")==" + d);
System.out.println("long: " + (long) fmin + ".." + (long) fmax);
System.out.println("int: " + (int) fmin + ".." + (int) fmax);
System.out.println("short: " + (short) fmin + ".." + (short) fmax);
System.out.println("char: " + (int) (char) fmin + ".." + (int) (char) fmax);
System.out.println("byte: " + (byte) fmin + ".." + (byte) fmax);
System.out.println(x);

System.out.println(c);
System.out.println(b);
System.out.println(b1);

OUTPUT

RESULT

Thus the type conversion program executed and verified successfully.


8 EXCEPTION HANDLING – DIVIDE BY ZERO

AIM:

To write a java program to demonstrate exception handling technique.

ALGORITHM:

1. Create a class DivNumbers.


2. Create a main class J6aException with object “d” of type DivNumbers.
3. Invoke the division function using object “d” with two set of different inputs.
4. Try dividing a numeric value by another numeric vlaue in the try block of division
function.
5. Print the result of division.
6. Otherwise Try dividing a numeric value by 0 in the try block
7. Catch the exception as Arithmetic exception and print the result as “Divide by
Zero error”.
8. Use finally block to print default statements inside the try & catch block.
9. Stop the Program.

SOURCE CODE

classDivNumbers
{
public void division(int num1, int num2)
{
int result;
int[] data = {1,2,3};
try
{
result = num1 / num2;
System.out.println("Result:"+result);
//System.out.println(data[5]);
}
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");
}
}
public class J6aException
{
public static void main(String args[])
{
DivNumbers d = new DivNumbers();
d.division(25, 5);
d.division(25, 0);
}
}

OUTPUT

RESULT:
Thus the exception handling program executed and verified successfully.
9 EVENT HANDLING- CALCULATOR

AIM:

To write a java program to implement event handling event for simulating a simple
calculator.

ALGORITHM:

1. Create the calculator class


2. Create a frame using JFrameclass and a panel using JPanel class
3. Create the labels ,text fields and buttons to the panel
4. Create the class Action that extends the class WindowAdapter and implements the
interface ActionListener and TextListener.
5. Perform the addition operation in actionPerformed() method by overriding it.
6. Set the value for the second textbox if not entered in the textValueChanged() method.
7. Create the object in the main() method and call the other methods.
8. Finally compile and run the program

CODING:
import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

class Calc extends JFrame


{

private JTextFieldtextfield;

private booleanresultshown = true;

private String prevOp = "=";

int result = 0;

public Calc()
{

textfield = new JTextField("", 12);


textfield.setHorizontalAlignment(JTextField.RIGHT);

NumberListenernumberListener = new NumberListener();


JPanelbuttonPanel = new JPanel();

buttonPanel.setLayout(new GridLayout(4, 4));

String[] numbers = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};

for (int i = 0; i<numbers.length; i++)


{

JButton button = new JButton(numbers[i]);


button.addActionListener(numberListener);

buttonPanel.add(button);

OperatorListeneroperatorListener = new OperatorListener();

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(4, 4));

String[] opOrder = {"+", "-", "*", "/", "AC", "sin", "cos", "log", "tan", "1/x", "x^y", "="};

for (int i = 0; i<opOrder.length; i++)


{

JButton button = new JButton(opOrder[i]);

button.addActionListener(operatorListener);

panel.add(button);

JPanel pan = new JPanel();


pan.setLayout(new BorderLayout(4, 4));
pan.add(textfield, BorderLayout.NORTH);
pan.add(buttonPanel, BorderLayout.CENTER);
pan.add(panel, BorderLayout.EAST);
this.setContentPane(pan);
this.pack();
this.setTitle("Calculator");
this.setResizable(false);

class OperatorListener implements ActionListener


{
public void actionPerformed(ActionEvent e)
{

int val = Integer.parseInt(textfield.getText());

if (e.getActionCommand().equals("sin"))
{
textfield.setText("" + Math.sin(val));
}
else if (e.getActionCommand().equals("cos"))
{
textfield.setText("" + Math.cos(val));
}
else if (e.getActionCommand().equals("log"))
{
textfield.setText("" + Math.log(val));
}
else if (e.getActionCommand().equals("tan"))
{
textfield.setText("" + Math.tan(val));
}
else if (e.getActionCommand().equals("1/x"))
{
textfield.setText("" + 1.0 / val);
}
else if (e.getActionCommand().equals("AC"))
{
textfield.setText("0");
result = 0;
}
else
{
if (prevOp.equals("="))
{
result = val;
}
else if (prevOp.equals("+"))
{
result = result + val;
}
else if (prevOp.equals("-"))
{
result = result - val;
}
else if (prevOp.equals("*"))
{
result = result * val;
}
else if (prevOp.equals("/"))
{
result = result / val;
}
else if (prevOp.equals("x^y"))
{
int k = 1;
for (int i = 1; i<= val; i++)
{
k = k * result;
}
result = k;
}
prevOp = e.getActionCommand();
textfield.setText("" + result);
resultshown = true;
}
}
}
class NumberListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String digit = event.getActionCommand();
if (resultshown)
{
textfield.setText(digit);
resultshown = false;
}
else
{
textfield.setText(textfield.getText() + digit);
}
}
}
}

class Calculator
{
public static void main(String[] args)
{
Calc cal = new Calc();
cal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cal.setVisible(true);
}
}

OUTPUT

RESULT

Thus the simulation of calculator program executed and verified successfully.


13 JDBC

AIM:

To write a java program to design and implement JDBC

ALGORITHM:

1. Create a class StudentSwingJdbc which extends the class JFrame and implements the
ActionListener.
2. Create the panel using JPanel.
3. Use textboxes and labels for rollno, name,department, mark1, mark2, mark3.
4. Add the buttons „Save‟ and „Exit‟.
5. Use the JDBC database connection in the AddStudent() method to add the new student
details by using insert command.
6. Check if the marks are greater than 50 and if it is true, print the result as “PASS” and if
it isfalse, print the result as “FAIL”.
7. Create the object for the class in the main() method.
8. Now compile and run the program to see the result.

CODING:

importjava.awt.*;
importjavax.swing.*;
importjava.awt.event.*;
importjava.sql.*;

public class StudentSwingJDBC extends JFrame implements ActionListener


{
JLabellblRollno,lblName,lblDept,lblMark1,lblMark2,lblMark3;
JTextFieldtxtRollno,txtName,txtDept,txtMark1,txtMark2,txtMark3;
JButtonsave,exit;

StudentSwingJDBC()
{
super("StudentSwingJDBC");
JPanel panel = new JPanel(new GridLayout(10, 2));
lblRollno= new JLabel("RollNo");
panel.add(lblRollno);
txtRollno= new JTextField();
panel.add(txtRollno);

lblName= new JLabel("Name");


panel.add(lblName);
txtName= new JTextField();
panel.add(txtName);

lblDept= new JLabel("Dept");


panel.add(lblDept);
txtDept= new JTextField();
panel.add(txtDept);

lblMark1= new JLabel("Mark 1");


panel.add(lblMark1);
txtMark1= new JTextField();
panel.add(txtMark1);

lblMark2= new JLabel("Mark 2");


panel.add(lblMark2);
txtMark2= new JTextField();
panel.add(txtMark2);

lblMark3= new JLabel("Mark 3");


panel.add(lblMark3);
txtMark3= new JTextField();
panel.add(txtMark3);

save = new JButton("Save");


panel.add(save);
save.addActionListener(this);

exit = new JButton("Exit");


panel.add(exit);
exit.addActionListener(this);

add(panel);
setSize(500, 400);
this.setVisible(true);

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==save)
{
AddStudent();
JOptionPane.showMessageDialog(this,"Student information updated successfully");
}
else if(e.getSource()==exit)
{
this.dispose();
}
}
public void AddStudent()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
/* C:\Program Files\glassfish-
4.1.1\glassfish\lib\install\templates\resources\jdbc\oracle_type4_datasource.xml*/
/* "jdbc:oracle:thin:@DB_HOSTNAME:1521:DATABASE_NAME"*/
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system",
"user");
int rollno = Integer.parseInt(txtRollno.getText());
String name = txtName.getText();
String department = txtDept.getText();
int mark1 = Integer.parseInt(txtMark1.getText());
int mark2 = Integer.parseInt(txtMark2.getText());
int mark3 = Integer.parseInt(txtMark3.getText());
int total = mark1 + mark2 + mark3;
String result;
if(mark1 >=50 && mark2 >=50 && mark3 >=50)
{
result = "Pass";
}
else
{
result = "Fail";
}
PreparedStatementps=con.prepareStatement("INSERT INTO mec.mitstudent (rollno,
name, department,mark1,mark2,mark3,total,result) VALUES (?,?,?,?,?,?,?,?)");
ps.setInt(1,rollno);
ps.setString(2,name);
ps.setString(3,department);
ps.setInt(4,mark1);
ps.setInt(5,mark2);
ps.setInt(6,mark3);
ps.setInt(7,total);
ps.setString(8,result);
ps.executeQuery();
ps.close();
con.close();
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(this, ex);
}
}

public static void main(String[] args)


{
StudentSwingJDBC ss = new StudentSwingJDBC();
ss.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

OUTPUT
RESULT

Thus the java database connectivity program executed and verified successfully.
14 REMOTE METHOD INVOCATION

AIM:
To write a java program to design and implement RMI

ALGORITHM:

1. Create an interface named FactInterface


2. Declare fact method in the FactInterface
3. Create FactImplementation class by implementing FactInterface interface
and define fact method
4. Create RmiServer class and create an object for FactImplementation class
5. Bind that object in the rmiregistry using Naming.rebind() method and
display server ready
6. Create RmiClient class and lookup into the server‟s registry for the object
using
Naming.lookUp() method
7. Get the object from server and typecasting it as reference
8. Using that object, invoke fact method and display the output
9. Stop the program

CODING:

//Fact Interface
importjava.rmi.*;
importjava.rmi.server.*;
public interface FactInterface extends Remote
{
publicintfact(int n) throws RemoteException;
}
//Fact Implementation
importjava.rmi.*;
importjava.rmi.server.*;
public class FactImplementation extends UnicastRemoteObject
implements FactInterface
{
Public FactImplementation() throws RemoteException { }
public int fact(int n) throws RemoteException
{
int f = 1;
for(inti = 1; i<= n; i++)
{
f = f * i;
}
return f;
}
}
//RMI Server
importjava.rmi.*;
import java.net.*;
public class RmiServer
{
public static void main(String args[]) throws RemoteException
{
try
{
FactImplementation fi = new FactImplementation();
Naming.rebind("Server", fi);
System.out.println("Server ready");
}
catch(Exception e)
{
System.out.println("Exception:" + e);
}
}
}
//RMI client
importjava.rmi.*;
import java.io.*;
public class RmiClient
{
public static void main(String args[]) throws RemoteException
{
try
{
BufferedReaderbr = new BufferedReader(new
InputStreamReader(System.in)); System.out.println("Enter the server name
or ip address");
String url = br.readLine();
String host="rmi://" + url + "/server"; FactInterface
serv = (FactInterface) Naming.lookup(host);
System.out.println("Enter a number:"); int n =
Integer.parseInt(br.readLine());
int fact = serv.fact(n);
System.out.println("Factorial of " + n + " is " + fact);}
catch(Exception e)
{
System.out.println("Error " + e);
}
}
}
OUTPUT

RESULT

Thus the RMI using factorial method program executed and verified successfully.
15 NETWORKING – TCP ONE WAY COMMUNICATION

AIM:

To write a java program for one way communication using TCP

ALGORITHM:

Server Program:

1. Start.
2. Import the java.net and java.io packages.
3. Declare a new class called “TcpOneWayChatServer”.
4. Within class “TcpOneWayChatServer”, create a ServerSocket object
called “ss” with the port number 8000.
5. Create a Socket object called “s” by using the accept() method, which
listens for a connection to be made to this server socket and accepts it.
6. Create a new BufferedReader object, which acts as an input stream to
the server from the client.
7. Create a new PrintStream object, which acts as an output stream to the client from
the server.
8. Display the message “Server ready...” on the server window.
9. Repeat the following steps:
i. Prompt for the message to be sent from server to client.
ii. Read in the message to be sent from the user.
iii. Send the message to the client using the PrintStream object.
iv. If the message equals the string “end”, then close the input and
output streams and exit the loop.
10. Stop

Client Program:

1. Start.
2. Import the java.net, java.io, and java.util packages.
3. Create a new class called “TcpOneWayClient”.
4. Inside “TcpOneWayClient”, create a new Socket object called “s” with port number
8000.
5. Create a new BufferedReader object which acts as the input stream to the client
from the server.
6. Repeat the following steps:
i. Read in the input from the server to the client using the BufferedReader object.
ii. Display the message received.
iii. If the string received equals “end”, then close the input and output streams
and exit the loop.
7. Stop.

CODING:
//TcpOneWayChatServer
import java.io.*;
import java.net.*;
class TcpOneWayChatServer
{
public static void main(String a[])throws
IOException {
ServerSocket ss = new ServerSocket(8000);
Socket s=ss.accept();

BufferedReaderkeyIn = new BufferedReader(new


InputStreamReader(System.in)); PrintStreamsocOut = new
PrintStream(s.getOutputStream());
while(true)
{
System.out.print("Message: ");
String str = in.readLine();
if(str.equals("bye"))
{
break;
}
socOut.println(str);
}
}
}

//TcpOneWayChatClient
import java.io.*;
import java.net.*;
class TcpOneWayChatClient
{
public static void main(String args[])throws
IOException {
Socket c = new Socket("localhost", 8000);
BufferedReadersocIn=new BufferedReader(new
InputStreamReader(c.getInputStream()));
String str;
while(true)
{
str = socIn.readLine();
System.out.println("Message Received: " + str);
}
}
}
OUTPUT

RESULT

Thus the one way communication using TCP program executed and verified successfully.
16 Build GUI-Based Application Development Using JavaFX

AIM:

To design and implement a Sign In GUI application using JavaFX as part of


GUI-based application development

ALGORITHM:

1. Start.
2. Import necessary JavaFX packages for creating the GUI layout and handling events.
3. Define a class HelloApplication extending Application and override the start() method.
4. Set up a GridPane layout and configure padding, spacing, and alignment.
5. Create input fields for "Username" and "Password" with labels and placeholders.
6. Add buttons for "Sign In", "Reset", and "Sign Up" along with a "Remember Me"
checkbox and a "Forgot Password?" hyperlink.
7. Implement event handling:
o Sign In button checks hardcoded credentials.
o Reset button clears all fields.
o Forgot Password link simulates sending reset instructions.
o Sign Up button redirects (placeholder action).
8. Display success or failure messages based on user input.
9. Set the scene, size it to 400x300 pixels, and show the window.
10. Stop.

CODING:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class HelloApplication extends Application {

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Sign In");

// Layout setup
GridPane grid = new GridPane();
grid.setPadding(new Insets(15, 15, 15, 15));
grid.setVgap(10);
grid.setHgap(10);
grid.setAlignment(Pos.CENTER);

// Username Label &TextField


Label userLabel = new Label("Username:");
TextFielduserInput = new TextField();
userInput.setPromptText("Enter your username");

// Password Label &PasswordField


Label passLabel = new Label("Password:");
PasswordFieldpassInput = new PasswordField();
passInput.setPromptText("Enter your password");

// Remember Me Checkbox
CheckBoxrememberMe = new CheckBox("Remember Me");

// Buttons for Sign In, Reset, and Sign Up


Button signInButton = new Button("Sign In");
Button resetButton = new Button("Reset");
Button signUpButton = new Button("Sign Up");

// Horizontal button layout


HBoxbuttonBox = new HBox(10, signInButton, resetButton, signUpButton);
buttonBox.setAlignment(Pos.CENTER);

// Forgot Password Link


Hyperlink forgotPassword = new Hyperlink("Forgot Password?");

// Status/Message Label
Label messageLabel = new Label();

// Event handling logic


signInButton.setOnAction(e -> {
String username = userInput.getText();
String password = passInput.getText();

// Basic authentication check


if (username.equals("admin") &&password.equals("password")) {
messageLabel.setText("Login successful!");
} else {
messageLabel.setText("Invalid credentials");
}
});

// Reset button clears the fields


resetButton.setOnAction(e -> {
userInput.clear();
passInput.clear();
messageLabel.setText("");
});

// Sign Up button placeholder action


signUpButton.setOnAction(e ->System.out.println("Redirecting to sign up..."));

// Forgot password link action


forgotPassword.setOnAction(e ->messageLabel.setText("Reset instructions sent!"));

// Add components to the grid layout


grid.addRow(0, userLabel, userInput);
grid.addRow(1, passLabel, passInput);
grid.addRow(2, rememberMe);
grid.addRow(3, buttonBox);
grid.addRow(4, forgotPassword);
grid.addRow(5, messageLabel);

// Set scene and show stage


Scene scene = new Scene(grid, 400, 300);
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}

NOTE:
SETUP PROCEDURE
1. Install JDK and JavaFX SDK:
o Download and install the JDK from Oracle or use OpenJDK.
o Download the JavaFX SDK from https://openjfx.io and extract it to a known
location.
2. Set Up the IDE:
o Use an IDE like IntelliJ IDEA, Eclipse, or NetBeans.
o Add JavaFX SDK .jar files to your project’s library or classpath.
o Add VM options:
--module-path "path_to_javafx/lib" --add-modules javafx.controls,javafx.fxml
3. Write, Compile, and Run:
o Copy the provided Java code into a file named HelloApplication.java.
o Compile with:
javac --module-path "path_to_javafx/lib" --add-modules javafx.controls
HelloApplication.java
o Run with:
java --module-path "path_to_javafx/lib" --add-modules javafx.controls
HelloApplication
OUTPUT:

RESULT:

Thus, the Sign In GUI-based application using JavaFX was successfully implemented
and verified.

You might also like