OOPS III SEM IT Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 139

DHANALAKSHMI SRINIVASAN COLLEGE OF

ENGINEERING & TECHNOLOGY


(Approved by AICTE & Affiliated to Anna University, Chennai)
East Cost Road, Mamallapuram, Chennai – 603 104

DEPARTMENT OF

INFORMATION TECHNOLOGY

CS3381-OBJECT ORIENTED PROGRAMMING LAB

RECORD NOTE BOOK

Name ...................................................
Reg.No ...................................................
Year/Semester ...................................................
TABLE OF CONTENTS

Ex.No Name of The Program Page No Date Staff Sign

1(a) Linear Search Program

1(b) Binary Search Program

1(c) Selection Sort Program

1(d) Insertion Sort Program


Stack Program Using Classes
2(a)
And Objects
Queue Program Using Classes
2(b)
And Objects
3 Program To Generate Payslip
Program To Calculate Area
4
Using Abstract Class
Program To Calculate Area
5
Using Interface
Program To Implement User
6 (a) Defined Exception Handling for
Negative Amount
Program To Implement User
6 (b)
Defined Exception Handling
Program To Implement
7
Multithreaded Application
8(a) File Creation
8(b) Displaying File Properties

8(c) Write Content Into File

8(d) Read Content From File


9
Generic Programming
10(a) Develop Applications Using
Javafx Controls
10(b)
Develop Applications Using
Javafx Layouts
Develop Applications Using
10(c)
Javafx Menus Additional
Experiments
11 Largest of Three Numbers
12 Implementing String Functions
Javafx Program to create a
13
VBox
14 Javafx Program to draw a line
Javafx Program To create a
15
RadioButton
Javafx Program To create a
16
Checkbox
Java Program to implement
17
function overloading
Java Program To implement
18
Constructor Overloading
Java program to implement
19
multilevel inheritance
20 Fibonacci Series
Ex.No.1(a)
LINEAR SEARCH PROGRAM
Date:

Aim

To develop a Java application to search a key element from multiple elements using Linear
Search

Algorithm:

Step 1: Traverse the array

Step 2: Match the key element with array element

Step 3: If key element is found, return the index position of the array element

Step 4: If key element is not found, return -1

1
PROGRAM

public class LinearSearchExample


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

2
OUTPUT

3
RESULT:

Thus the program for linear search was implemented in java and the output was verified
successfully.

4
Ex.No.1(b)
BINARY SEARCH PROGRAM
Date:

Aim

To develop a Java application to search a key element from multiple elements using Binary
search

Algorithm:

Step 1 - Read the search element from the given list.

Step 2 - Find the middle element in the sorted list.

Step 3 - Compare the search element with the middle element in the sorted list.

Step 4 - If both are matched, then display "Given element is found!!!" and terminate
the function.

Step 5 - If both are not matched, then check whether the search element is smaller or
larger than the middle element.

Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and
5 for the left sublist of the middle element.

Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5
for the right sublist of the middle element.

Step 8 - Repeat the same process until we find the search element in the list or until
sublist contains only one element.

Step 9 - If that element also doesn't match with the search element, then display
"Element is not found in the list!!!" and terminate the function.

5
PROGRAM

class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}

6
OUTPUT:

7
RESULT:

Thus the program for binary search was implemented in java and the output was verified
successfully.

8
Ex.No.1(c)

Date: SELECTION SORT PROGRAM

Aim

To develop a Java application to sort array elements using selection sort

Algorithm
Step 1: Initialize minimum value(min_idx) to location 0
Step 2: Traverse the array to find the minimum element in the array
Step 3: While traversing if any element smaller than min_idx is found then swap both the
values.
Step 4: Then, increment min_idx to point to next element
Step 5: Repeat until array is sorted

9
PROGRAM

public class SelectionSortExample {


public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}

public static void main(String a[]){


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

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

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


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

10
OUTPUT

11
RESULT:

Thus the program for selection sort was implemented in java and the output was verified
successfully.

12
Ex.No.1(d)

Date: INSERTION SORT PROGRAM

Aim

To develop a Java application to sort array elements using insertion sort

Algorithm

Step 1 - If the element is the first element, assume that it is already sorted. Return 1.

Step2 - Pick the next element, and store it separately in a key.

Step3 - Now, compare the key with all elements in the sorted array.

Step 4 - If the element in the sorted array is smaller than the current element, then move to
the next element. Else, shift greater elements in the array towards the right.

Step 5 - Insert the value.

Step 6 - Repeat until the array is sorted.

13
PROGRAM

public class InsertionSortExample {


public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}

public static void main(String a[]){


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

insertionSort(arr1);//sorting array using insertion sort

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


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

14
OUTPUT

15
RESULT:

Thus the program for insertion sort was implemented in java and the output was verified
successfully.

16
Ex.No.2(a)

Date: STACK PROGRAM USING CLASSES AND OBJECTS

Aim

To design a java application to implement array implementation of stack using


classes and objects

Algorithm:

1. Start the program


2. Create the stack operation with method declarations for push and pop.
3. Create the class a stack which implements the methods push and pop. The push
operation inserts an element into the stack and pop operation removes an element
from the top of the stack. Also define the method for displaying the values stored in
the stack.
4. Handle the stack overflow and stack underflow condition.
5. Create the object and invoke the method for push and pop.
6. Stop the program

17
PROGRAM

class Stack {

static final int MAX = 1000;

int top;

int a[] = new int[MAX]; // Maximum size of Stack

boolean isEmpty()

return (top < 0);

Stack()

top = -1;

boolean push(int x)

if (top >= (MAX - 1)) {

System.out.println("Stack Overflow");

return false;

else {

a[++top] = x;

System.out.println(x + " pushed into stack");

return true;

int pop()

if (top < 0) {

18
System.out.println("Stack Underflow");

return 0;

else {

int x = a[top--];

return x;

void print(){

for(int i = top;i>-1;i--){

System.out.print(" "+ a[i]);

// Driver code

class Main {

public static void main(String args[])

Stack s = new Stack();

s.push(10);

s.push(20);

s.push(30);

System.out.println(s.pop() + " Popped from stack");

System.out.print("Elements present in stack :");

s.print();

19
Output:

10 pushed into stack


20 pushed into stack
30 pushed into stack
30 Popped from stack
Top element is: 20
Elements present in stack: 20 10

20
RESULT:

Thus a java application to implement stack has been executed and result is verified.

21
Ex.No.2(b)

Date: QUEUE PROGRAM USING CLASSES AND OBJECTS

Aim

To design a java application to implement array implementation of queue using


classes and objects

Algorithm:

1. Start the program


2. For implementing queue, we need to keep track of two indices, front and rear. We
enqueue an item at the rear and dequeue an item from the front
3. Steps for enqueue:
1. Check the queue is full or not
2. If full, print overflow and exit
3. If queue is not full, increment tail and add the element
4.Steps for dequeue:
1. Check queue is empty or not
2. if empty, print underflow and exit
3. if not empty, print element at the head and increment head
5.Stop the program

22
PROGRAM

// Java program for array

// implementation of queue

// A class to represent a queue

classQueue {

intfront, rear, size;

intcapacity;

intarray[];

publicQueue(intcapacity)

this.capacity = capacity;

front = this.size = 0;

rear = capacity - 1;

array = newint[this.capacity];

// Queue is full when size becomes

// equal to the capacity

booleanisFull(Queue queue)

return(queue.size == queue.capacity);

// Queue is empty when size is 0

23
booleanisEmpty(Queue queue)

return(queue.size == 0);

// Method to add an item to the queue.

// It changes rear and size

voidenqueue(intitem)

if(isFull(this))

return;

this.rear = (this.rear + 1)% this.capacity;

this.array[this.rear] = item;

this.size = this.size + 1;

System.out.println(item+ " enqueued to queue");

// Method to remove an item from queue.

// It changes front and size

intdequeue()

if(isEmpty(this))

returnInteger.MIN_VALUE;

intitem = this.array[this.front];

24
this.front = (this.front + 1)% this.capacity;

this.size = this.size - 1;

returnitem;

// Method to get front of queue

intfront()

if(isEmpty(this))

returnInteger.MIN_VALUE;

returnthis.array[this.front];

// Method to get rear of queue

intrear()

if(isEmpty(this))

returnInteger.MIN_VALUE;

returnthis.array[this.rear];

// Driver class

publicclassTest {

publicstaticvoidmain(String[] args)

25
{

Queue queue = newQueue(1000);

queue.enqueue(10);

queue.enqueue(20);

queue.enqueue(30);

queue.enqueue(40);

System.out.println(queue.dequeue()+ " dequeued from queue\n");

System.out.println("Front item is "+ queue.front());

System.out.println("Rear item is "+ queue.rear());

26
Output

10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
40 enqueued to queue
10 dequeued from queue
Front item is 20
Rear item is 40

27
RESULT:

Thus a java application to implement stack has been executed and result is verified.

28
Ex.No.3

Date: PROGRAM TO GENERATE PAYSLIP

AIM:

To develop a java application to generate pay slip for different category of employees using
the concept of inheritance.

ALGORITHM:

1. Create the class employee with name, Empid, address, mailid, mobileno as members.

2. Inherit the classes programmer, asstprofessor,associateprofessor and professor from


employee class. 3. Add Basic Pay (BP) as the member of all the inherited classes.

4. Calculate DA as 97% of BP, HRA as 10% of BP, PF as 12% of BP, Staff club fund as
0.1% of BP.

5. Calculate gross salary and net salary.

6. Generate payslip for all categories of employees.

7. Create the objects for the inherited classes and invoke the necessary methods to display the
Payslip

29
PROGRAM

import java.util.*;

class employee

int empid;

long mobile;

String name, address, mailid;

Scanner get = new Scanner(System.in);

void getdata()

System.out.println("Enter Name of the Employee");

name = get.nextLine();

System.out.println("Enter Mail id");

mailid = get.nextLine();

System.out.println("Enter Address of the Employee:");

address = get.nextLine();

System.out.println("Enter employee id ");

empid = get.nextInt();

System.out.println("Enter Mobile Number");

mobile = get.nextLong();

void display()

System.out.println("Employee Name: "+name);

System.out.println("Employee id : "+empid);

System.out.println("Mail id : "+mailid);

System.out.println("Address: "+address);

System.out.println("Mobile Number: "+mobile);

30
}

class programmer extends employee

double salary,bp,da,hra,pf,club,net,gross;

void getprogrammer()

System.out.println("Enter basic pay");

bp = get.nextDouble();

void calculateprog()

da=(0.97*bp);

hra=(0.10*bp);

pf=(0.12*bp);

club=(0.1*bp);

gross=(bp+da+hra);

net=(gross-pf-club);

System.out.println("************************************************");

System.out.println("PAY SLIP FOR PROGRAMMER");

System.out.println("************************************************");

System.out.println("Basic Pay:Rs"+bp);

System.out.println("DA:Rs"+da);

System.out.println("PF:Rs"+pf);

System.out.println("HRA:Rs"+hra);

System.out.println("STAFF CLUB FUND:Rs"+club);

System.out.println("GROSS PAY:Rs"+gross);

System.out.println("NET PAY:Rs"+net);

31
}

class asstprofessor extends employee

double salary,bp,da,hra,pf,club,net,gross;

void getasst()

System.out.println("Enter basic pay");

bp = get.nextDouble();

void calculateasst()

da=(0.97*bp);

hra=(0.10*bp);

pf=(0.12*bp);

club=(0.1*bp);

gross=(bp+da+hra);

net=(gross-pf-club);

System.out.println("************************************************");

System.out.println("PAY SLIP FOR ASSISTANT PROFESSOR");

System.out.println("************************************************");

System.out.println("Basic Pay:Rs"+bp);

System.out.println("DA:Rs"+da);

System.out.println("HRA:Rs"+hra);

System.out.println("PF:Rs"+pf);

System.out.println("STAFF CLUB FUND:Rs"+club);

System.out.println("GROSS PAY:Rs"+gross);

System.out.println("NET PAY:Rs"+net);

32
class associateprofessor extends employee

double salary,bp,da,hra,pf,club,net,gross;

void getassociate()

System.out.println("Enter basic pay");

bp = get.nextDouble();

void calculateassociate()

da=(0.97*bp);

hra=(0.10*bp);

pf=(0.12*bp);

club=(0.1*bp);

gross=(bp+da+hra);

net=(gross-pf-club);

System.out.println("************************************************");

System.out.println("PAY SLIP FOR ASSOCIATE PROFESSOR");

System.out.println("************************************************");

System.out.println("Basic Pay:Rs"+bp);

System.out.println("DA:Rs"+da);

System.out.println("HRA:Rs"+hra);

System.out.println("PF:Rs"+pf);

System.out.println("STAFF CLUB FUND:Rs"+club);

System.out.println("GROSS PAY:Rs"+gross);

System.out.println("NET PAY:Rs"+net);

class professor extends employee

33
{

double salary,bp,da,hra,pf,club,net,gross;

void getprofessor()

System.out.println("Enter basic pay");

bp = get.nextDouble();

void calculateprofessor()

da=(0.97*bp);

hra=(0.10*bp);

pf=(0.12*bp);

club=(0.1*bp);

gross=(bp+da+hra);

net=(gross-pf-club);

System.out.println("************************************************");

System.out.println("PAY SLIP FOR PROFESSOR");

System.out.println("************************************************");

System.out.println("Basic Pay:Rs"+bp);

System.out.println("DA:Rs"+da);

System.out.println("HRA:Rs"+hra);

System.out.println("PF:Rs"+pf);

System.out.println("STAFF CLUB FUND:Rs"+club);

System.out.println("GROSS PAY:Rs"+gross);

System.out.println("NET PAY:Rs"+net);

34
}

class salary

public static void main(String args[])

int choice,cont;

do

System.out.println("PAYROLL PROGRAM");

System.out.println(" 1.PROGRAMMER \t 2.ASSISTANT PROFESSOR \t 3.ASSOCIATE


PROFESSOR \t 4.PROFESSOR ");

System.out.println("Enter Your Choice \t");

Scanner c = new Scanner(System.in);

choice=c.nextInt();

switch(choice)

case 1:

programmer p=new programmer();

p.getdata();

p.getprogrammer();

p.display();

p.calculateprog();

break;

case 2:

asstprofessor asst=new asstprofessor();

asst.getdata();

35
asst.getasst();

asst.display();

asst.calculateasst();

break;

case 3:

associateprofessor asso=new associateprofessor();

asso.getdata();

asso.getassociate();

asso.display();

asso.calculateassociate();

break;

case 4:

professor prof=new professor();

prof.getdata();

prof.getprofessor();

prof.display();

prof.calculateprofessor();

break;

System.out.println("Do u want to continue 0 to quit and 1 to continue ");

cont=c.nextInt();

}while(cont==1);

}}

36
OUTPUT:

37
RESULT:

Thus the java application to generate pay slip for different category of employees was
implemented using inheritance and the program was executed successfully.

38
Ex.No.4 PROGRAM TO CALCULATE AREA USING ABSTRACT
CLASS
Date:

AIM:

To write a java program to calculate the area of rectangle,circle and triangle using the concept
of abstract class.

PROCEDURE:

1. Create an abstract class named shape that contains two integers and an empty method
named printarea().

2. Provide three classes named rectangle, triangle and circle such that each one of the classes
extends the class Shape.

3.Each of the inherited class from shape class should provide the implementation for the
method printarea().

4.Get the input and calculate the area of rectangle,circle and triangle .

5. In the shapeclass , create the objects for the three inherited classes and invoke the methods
and display the area values of the different shapes.

39
PROGRAM:

import java.util.*;

abstract class Shape {

public int x,y;

public abstract void printArea();

class Rectangle1 extends Shape {

public void printArea() {

float area;

area= x * y;

System.out.println("Area of Rectangle is " +area);

class Triangle extends Shape {

public void printArea() {

float area;

area= (x * y) / 2.0f;

System.out.println("Area of Triangle is " + area);

class Circle extends Shape {

public void printArea() {

float area;

area=(22 * x * x) / 7.0f;

System.out.println("Area of Circle is " + area);

40
public class AreaOfShapes {

public static void main(String[] args) {

int choice;

Scanner sc=new Scanner(System.in);

System.out.println("Menu \n 1.Area of Rectangle \n 2.Area of Traingle \n 3.Area of


Circle ");

System.out.print("Enter your choice : ");

choice=sc.nextInt();

switch(choice) {

case 1:

System.out.println("Enter length and breadth for area of rectangle : ");

Rectangle1 r = new Rectangle1();

r.x=sc.nextInt();

r.y=sc.nextInt();

r.printArea();

break;

case 2:

System.out.println("Enter bredth and height for area of traingle : ");

Triangle t = new Triangle();

t.x=sc.nextInt();

t.y=sc.nextInt();

t.printArea();

break;

case 3:

System.out.println("Enter radius for area of circle : ");

Circle c = new Circle();

c.x = sc.nextInt();

c.printArea();

41
break;

default:System.out.println("Enter correct choice");

42
OUTPUT:

43
RESULT:

Thus a java program for calculate the area of rectangle, circle and triangle was implemented
and executed successfully.

44
Ex.No.5 PROGRAM TO CALCULATE AREA USING INTERFACE
Date:

AIM:

To write a java program to calculate the area of rectangle and circle using the concept of
interface.

PROCEDURE:

1. Create an abstract class named shape that contains two integers and an empty method
named printarea().

2. Provide two classes named rectangleand circle such that each one of the classes extends the
class Shape.

3. Each of the inherited class from shape class should provide the implementation for the
method printarea().

4. Get the input and calculate the area of rectangle and circle.

5. In the shapeclass , create the objects for the two inherited classes and invoke the methods
and display the area values of the different shapes.

45
PROGRAM

interface Shape

void input();

void area();

class Circle implements Shape

int r = 0;

double pi = 3.14, ar = 0;

@Override

public void input()

r = 5;

@Override

public void area()

ar = pi * r * r;

System.out.println("Area of circle:"+ar);

class Rectangle extends Circle

int l = 0, b = 0;

double ar;

46
public void input()

super.input();

l = 6;

b = 4;

public void area()

super.area();

ar = l * b;

System.out.println("Area of rectangle:"+ar);

public class Demo

public static void main(String[] args)

Rectangle obj = new Rectangle();

obj.input();

obj.area();

47
Output:

$ javac Demo.java
$ java Demo

Area of circle:78.5
Area of rectangle:24.0

RESULT:

Thus a java program for calculate the area using interface was implemented and executed
successfully.

48
Ex.No.6 (a) PROGRAM TO IMPLEMENT USER DEFINED EXCEPTION
HANDLING
Date:

AIM:

To write a java program to implement user defined exception handling

ALGORITHM:

1. Create a class which extends Exception class.

2. Create a constructor which receives the string as argument.

3.Get the Amount as input from the user.

4. If the amount is negative , the exception will be generated.

5. Using the exception handling mechanism , the thrown exception is handled by the catch
construct.

6. After the exception is handled , the string “invalid amount “ will be displayed.

7. If the amount is greater than 0 , the message “Amount Deposited “ will be displayed

49
PROGRAM:

import java.util.Scanner;

class NegativeAmtException extends Exception

String msg;

NegativeAmtException(String msg)

this.msg=msg;

public String toString()

return msg;

public class userdefined

public static void main(String[] args)

Scanner s=new Scanner(System.in);

System.out.print("Enter Amount:");

int a=s.nextInt();

try

if(a<0)

throw new NegativeAmtException("Invalid Amount");

System.out.println("Amount Deposited");

50
}

catch(NegativeAmtException e)

System.out.println(e);

51
OUTPUT:

52
RESULT:

Thus a java program for user defined exception handling was implemented and executed
successfully.

53
Ex.No.6 (b) PROGRAM TO IMPLEMENT USER DEFINED EXCEPTION
HANDLING
Date:

AIM:

To write a java program to implement user defined exception handling

Algorithm:

1.Create a user defined exception class called MyException

2.Throw an exception of user defined type as an argument in main()

3.Exception is handled using try, catch block

4.Display the user defined exception

54
PROGRAM

class MyException extends Exception{

String str1;

MyException(String str2)

str1=str2;

public String toString()

return ("MyException Occurred: "+str1) ;

class example

public static void main(String args[])

try

System.out.println("Starting of try block");

throw new MyException("This is My error Message");

catch(MyException exp)

System.out.println("Catch Block") ;

System.out.println(exp) ;

}}

55
OUTPUT:

56
RESULT:

Thus a java program to implement user defined exception handling has been implemented
and executed successfully.

57
Ex.No.7
PROGRAM TO IMPLEMENT MULTITHREADED
Date: APPLICATION

AIM:
To write a java program that implements a multi-threaded application .

ALGORITHM

1. Create a class even which implements first thread that computes .the square of the number .
2. run() method implements the code to be executed when thread gets executed.
3. Create a class odd which implements second thread that computes the cube of the number.
4.Create a third thread that generates random number.If the random number is even , it
displays
the square of the number.If the random number generated is odd , it displays the cube of the
given number .
5.The Multithreading is performed and the task switched between multiple threads.
6.The sleep () method makes the thread to suspend for the specified time.

58
PROGRAM

MultiThreadRandOddEven.java

import java.util.*;

// class for Even Number

class EvenNum implements Runnable {

public int a;

public EvenNum(int a) {

this.a = a;

public void run() {

System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a);

} // class for Odd Number

class OddNum implements Runnable {

public int a;

public OddNum(int a) {

this.a = a;

public void run() {

System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a);

// class to generate random number

class RandomNumGenerator extends Thread {

public void run() {

int n = 0;

Random rand = new Random();

try {
59
for (int i = 0; i < 10; i++) {

n = rand.nextInt(20);

System.out.println("Generated Number is " + n);

// check if random number is even or odd

if (n % 2 == 0) {

Thread thread1 = new Thread(new EvenNum(n));

thread1.start();

else {

Thread thread2 = new Thread(new OddNum(n));

thread2.start();

// thread wait for 1 second

Thread.sleep(1000);

System.out.println(" ");

catch (Exception ex) {

System.out.println(ex.getMessage());

// Driver class

public class MultiThreadRandOddEven {

public static void main(String[] args) {

RandomNumGenerator rand_num = new RandomNumGenerator();

rand_num.start();

60
Output:

61
RESULT:

Thus multithreading using java program was verified and implemented.

62
Ex.No.8(a)

Date: PROGRAM TO IMPLEMENT FILE CREATION

Aim

Write a java program to create a new file

Algorithm:

Step1: Start the program


Step2: createNewFile() method is used for creating a file
Step3:createNewFile() method returns true when it successfully creates a new file and returns
false when the file already exists

63
PROGRAM

import java.io.File;
// Importing the IOException class for handling errors
import java.io.IOException;
class CreateFile {
public static void main(String args[]) {
try {
// Creating an object of a file
File f0 = new File("D:File1.txt");
if (f0.createNewFile()) {
System.out.println("File " + f0.getName() + " is created successfully.");
} else {
System.out.println("File is already exist in the directory.");
}
} catch (IOException exception) {
System.out.println("An unexpected error is occurred.");
exception.printStackTrace();
}
}
}

64
OUTPUT

RESULT:

Thus a java program to implement File creation has been implemented and executed
successfully.

65
Ex.No.8(b)

Date: PROGRAM TO DISPLAYING FILE PROPERTIES

Aim:
To read and display a file’s properties.

Procedure:
Step 1: Start the program.
Step 2: Import scanner and file classes.
Step 3: Use scanner method to get file name from user.
Step 4: Create a file object.
Step 5: Call the respective methods to display file properties like getName(), getPath() etc.
Step 6: Stop the program

66
Program:

import java.util.Scanner;

import java.io.File;

class fileDemo

public static void main(String[] args)

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

Scanner input = new Scanner(System.in);

String s = input.nextLine();

File f1=new File(s);

System.out.println(" ------------------------ ");

System.out.println("File Name: " +f1.getName());

System.out.println("Path: " +f1.getPath());

System.out.println("Abs Path: " +f1.getAbsolutePath());

System.out.println("This file: " +(f1.exists()?"Exists":"Does not exists"));

System.out.println("File: " +f1.isFile());

System.out.println("Directory: " +f1.isDirectory());

System.out.println("Readable: " +f1.canRead());

System.out.println("Writable: " +f1.canWrite());

System.out.println("Absolute: " +f1.isAbsolute());

System.out.println("File Size: " +f1.length()+ "bytes");

System.out.println("Is Hidden: " +f1.isHidden());

67
Output:
C:\ >javac fileDemo.java
C:\ >java fileDemo
Enter the file name:
fileDemo.java
File Name: fileDemo.java
Path: fileDemo.java
Abs Path: D:\ Ex 08\fileDemo.java
This file: Exists
File: true
Directory: false
Readable: true
Writable: true
Absolute: false
File Size: 895bytes
Is Hidden: false

68
RESULT:

Thus a java program to displaying the file properties has been implemented and executed
successfully.

69
Ex.No.8(c)

Date: PROGRAM TO WRITE CONTENT INTO A FILE

Aim

To develop a java program to write a content into file

Algorithm

Step 1: Start the program.

Step 2: Import scanner and file classes.

Step 3: Use scanner method to get file name from user.

Step 4: Create a file object.

Step 5: Call the respective methods String.getBytes(),FileOutputStream.flush()


,FileOutputStream.close()

Step6:String.getBytes() - returns the bytes array.

Step7:FileOutputStream.flush() - Is used to clear the output steam buffer.

Step8:FileOutputStream.close() - Is used to close output stream (Close the file).

Step9:Stop the program

70
PROGRAM

import java.io.File;

import java.io.FileOutputStream;

import java.util.Scanner;

public class WriteFile {

public static void main(String args[]) {

final String fileName = "file.txt";

try {

File objFile = new File(fileName);

if (objFile.exists() == false) {

if (objFile.createNewFile()) {

System.out.println("File created successfully.");

} else {

System.out.println("File creation failed!!!");

System.exit(0);

//writting data into file

String text;

Scanner SC = new Scanner(System.in);

System.out.println("Enter text to write into file: ");

text = SC.nextLine();

//object of FileOutputStream

FileOutputStream fileOut = new FileOutputStream(objFile);

//convert text into Byte and write into file

fileOut.write(text.getBytes());

fileOut.flush();

fileOut.close();

71
System.out.println("File saved.");

catch (Exception Ex)

System.out.println("Exception : " + Ex.toString());

72
OUTPUT

73
RESULT:

Thus a java program to write the content in the file has been implemented and executed
successfully.

74
Ex.No.8(d)

Date: PROGRAM TO READ CONTENT FROM A FILE

Aim

Write a java program to read content from the file

Algorithm

Step 1: Start the program

Step2: Read the content of the file using FileInputStream

Step3: FileInputStream.read() method which returns an integer value and will read values
until -1 is not found

Step4:Stop the program

75
PROGRAM

import java.io.File;

import java.io.FileInputStream;

public class ReadFile {

public static void main(String args[]) {

final String fileName = "file.txt";

try {

File objFile = new File(fileName);

if (objFile.exists() == false) {

System.out.println("File does not exist!!!");

System.exit(0);

//reading content from file

String text;

int val;

//object of FileOutputStream

FileInputStream fileIn = new FileInputStream(objFile);

//read text from file

System.out.println("Content of the file is: ");

while ((val = fileIn.read()) != -1) {

System.out.print((char) val);

System.out.println();

fileIn.close();

} catch (Exception Ex) {

System.out.println("Exception : " + Ex.toString());

}}

76
OUTPUT

77
RESULT:

Thus the program to read content from file using java program was implemented successfully
and the output was verified.

78
Ex.No.9

Date: GENERIC PROGRAMMING

AIM:

To write a java program to find the maximum value from the given type of elements using a
generic function.

ALGORITHM:

1.Create a class Myclass to implement generic class and generic methods.

2.Get the set of the values belonging to specific data type.

3. Create the objects of the class to hold integer,character and double values.

4. Create the method to compare the values and find the maximum value stored in the array.

5. Invoke the method with integer, character or double values . The output will be displayed
based on the data type passed to the method.

79
PROGRAM

class MyClass<T extends Comparable<T>>

T[] vals;

MyClass(T[] o)

vals = o;

public T min()

T v = vals[0];

for(int i=1; i < vals.length; i++)

if(vals[i].compareTo(v) < 0)

v = vals[i];

return v;

public T max()

T v = vals[0];

for(int i=1; i < vals.length;i++)

if(vals[i].compareTo(v) > 0)

v = vals[i];

return v;

class gendemo

public static void main(String args[])

80
{

int i;

Integer inums[]={10,2,5,4,6,1};

Character chs[]={'v','p','s','a','n','h'};

Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};

MyClass<Integer> iob = new MyClass<Integer>(inums);

MyClass<Character> cob = new MyClass<Character>(chs);

MyClass<Double>dob = new MyClass<Double>(d);

System.out.println("Max value in inums: " + iob.max());

System.out.println("Min value in inums: " + iob.min());

System.out.println("Max value in chs: " + cob.max());

System.out.println("Min value in chs: " + cob.min());

System.out.println("Max value in chs: " + dob.max());

System.out.println("Min value in chs: " + dob.min());

81
OUTPUT

RESULT:

Thus generic programming using java was implemented successfully and output was verified.

82
Ex.No.10(a)

Date: DEVELOP APPLICATIONS USING JAVAFX CONTROLS

Aim:

Write a java program to develop applications using JavaFX controls

Algorithm

Step 1: Creating a Class


Create a Java class and inherit the Application class of the package javafx.application and
implement the start() method
Step 2: Creating a Scene Object
Create a Scene by instantiating the class named Scene which belongs to the
package javafx.scene.
Step 3: Setting the Title of the Stage
You can set the title to the stage using the setTitle() method of the Stage class. The
primaryStage is a Stage object which is passed to the start method of the scene class, as a
parameter.
Step 4: Adding Scene to the Stage
You can add a Scene object to the stage using the method setScene() of the class named
Stage.
Step 5: Displaying the Contents of the Stage
Display the contents of the scene using the method named show() of the Stage class
Step 6: Launching the Application
Launch the JavaFX application by calling the static method launch() of the Application class
from the main method

83
PROGRAM

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import javafx.geometry.Insets;
import javafx.geometry.Pos;

import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.ToggleButton;
import javafx.stage.Stage;

public class Registration extends Application {


@Override
public void start(Stage stage) {
//Label for name
Text nameLabel = new Text("Name");

//Text field for name


TextField nameText = new TextField();

//Label for date of birth


Text dobLabel = new Text("Date of birth");

//date picker to choose date


DatePicker datePicker = new DatePicker();

//Label for gender


Text genderLabel = new Text("gender");

//Toggle group of radio buttons


ToggleGroup groupGender = new ToggleGroup();
RadioButton maleRadio = new RadioButton("male");
maleRadio.setToggleGroup(groupGender);
RadioButton femaleRadio = new RadioButton("female");
femaleRadio.setToggleGroup(groupGender);

//Label for reservation


Text reservationLabel = new Text("Reservation");

84
//Toggle button for reservation
ToggleButton Reservation = new ToggleButton();
ToggleButton yes = new ToggleButton("Yes");
ToggleButton no = new ToggleButton("No");
ToggleGroup groupReservation = new ToggleGroup();
yes.setToggleGroup(groupReservation);
no.setToggleGroup(groupReservation);

//Label for technologies known


Text technologiesLabel = new Text("Technologies Known");

//check box for education


CheckBox javaCheckBox = new CheckBox("Java");
javaCheckBox.setIndeterminate(false);

//check box for education


CheckBox dotnetCheckBox = new CheckBox("DotNet");
javaCheckBox.setIndeterminate(false);

//Label for education


Text educationLabel = new Text("Educational qualification");

//list View for educational qualification


ObservableList<String> names = FXCollections.observableArrayList(
"Engineering", "MCA", "MBA", "Graduation", "MTECH", "Mphil", "Phd");
ListView<String> educationListView = new ListView<String>(names);

//Label for location


Text locationLabel = new Text("location");

//Choice box for location


ChoiceBox locationchoiceBox = new ChoiceBox();
locationchoiceBox.getItems().addAll
("Hyderabad", "Chennai", "Delhi", "Mumbai", "Vishakhapatnam");

//Label for register


Button buttonRegister = new Button("Register");

//Creating a Grid Pane


GridPane gridPane = new GridPane();

//Setting size for the pane


gridPane.setMinSize(500, 500);

//Setting the padding


gridPane.setPadding(new Insets(10, 10, 10, 10));

//Setting the vertical and horizontal gaps between the columns


gridPane.setVgap(5);
gridPane.setHgap(5);

//Setting the Grid alignment

85
gridPane.setAlignment(Pos.CENTER);

//Arranging all the nodes in the grid


gridPane.add(nameLabel, 0, 0);
gridPane.add(nameText, 1, 0);

gridPane.add(dobLabel, 0, 1);
gridPane.add(datePicker, 1, 1);

gridPane.add(genderLabel, 0, 2);
gridPane.add(maleRadio, 1, 2);
gridPane.add(femaleRadio, 2, 2);
gridPane.add(reservationLabel, 0, 3);
gridPane.add(yes, 1, 3);
gridPane.add(no, 2, 3);

gridPane.add(technologiesLabel, 0, 4);
gridPane.add(javaCheckBox, 1, 4);
gridPane.add(dotnetCheckBox, 2, 4);

gridPane.add(educationLabel, 0, 5);
gridPane.add(educationListView, 1, 5);

gridPane.add(locationLabel, 0, 6);
gridPane.add(locationchoiceBox, 1, 6);

gridPane.add(buttonRegister, 2, 8);

//Styling nodes
buttonRegister.setStyle(
"-fx-background-color: darkslateblue; -fx-textfill: white;");

nameLabel.setStyle("-fx-font: normal bold 15px 'serif' ");


dobLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
genderLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
reservationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
technologiesLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
educationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
locationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");

//Setting the back ground color


gridPane.setStyle("-fx-background-color: BEIGE;");

//Creating a scene object


Scene scene = new Scene(gridPane);

//Setting title to the Stage


stage.setTitle("Registration Form");

//Adding scene to the stage


stage.setScene(scene);

//Displaying the contents of the stage


stage.show();

86
}
public static void main(String args[]){
launch(args);
}
}

87
OUTPUT

88
RESULT:

Thus a java application was developed successfully using JavaFX and the output was
verified.

89
Ex.No.10(b)

Date: DEVELOP APPLICATIONS USING JAVAFX LAYOUTS

Aim

To develop a java applications using JavaFX layouts

ALGORITHM

Step 1: Creating a Class

Create a Java class and inherit the Application class of the package javafx.application and
implement the start() method

Step 2: Creating a Scene Object

Create a Scene by instantiating the class named Scene which belongs to the package
javafx.scene.

Step 3: Setting the Title of the Stage

You can set the title to the stage using the setTitle() method of the Stage class. The
primaryStage is a Stage object which is passed to the start method of the scene class, as a
parameter.

Step 4: Adding Scene to the Stage

You can add a Scene object to the stage using the method setScene() of the class named
Stage.

Step 5: Displaying the Contents of the Stage

Display the contents of the scene using the method named show() of the Stage class

Step 6: Launching the Application

Launch the JavaFX application by calling the static method launch() of the Application class
from the main method

90
PROGRAM

import javafx.application.Application;

import javafx.stage.Stage;

import javafx.scene.Scene;

import javafx.scene.layout.FlowPane;

import javafx.scene.control.Label;

import javafx.scene.control.TextField;

import javafx.geometry.Insets;

public class ShowFlowPane extends Application {

@Override

public void start(Stage primaryStage) {

FlowPane pane = new FlowPane();

pane.setPadding(new Insets(11, 12, 13, 14));

pane.setHgap(5);

pane.setVgap(5);

// Place nodes in the pane

pane.getChildren().addAll(new Label("First Name:"),

new TextField(), new Label("MI:"));

TextField tfMi = new TextField();

tfMi.setPrefColumnCount(1);

pane.getChildren().addAll(tfMi, new Label("Last Name:"),

new TextField());

// Create a scene and place it in the stage

Scene scene = new Scene(pane, 210, 150);

primaryStage.setTitle("ShowFlowPane");

primaryStage.setScene(scene); // Place the scene in the stage

primaryStage.show(); // Display the stage

91
public static void main(String[] args) {

launch(args);

OUTPUT

92
RESULT

Thus the GUI using JavaFX layout was developed successfully and the output was verified.

93
Ex.No.10(c)

Date: DEVELOP APPLICATIONS USING JAVAFX MENUS

Aim

To develop a java applications using JavaFX menus

Algorithm

Step 1:Start the program

Step 2: JavaFX provides five classes that implement menus: MenuBar, Menu, MenuItem,
CheckMenuItem, and RadioButtonMenuItem.

Step 3: MenuBar is a top-level menu component used to hold the menus.

Step 4: A menu consists of menu items that the user can select (or toggle on or off).

Step 5: A menu item can be an instance of MenuItem, CheckMenuItem, or


RadioButtonMenuItem.

Step 6: Menu items can be associated with nodes and keyboard accelerators.

94
PROGRAM

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.geometry.Pos;
public class MenuDemo extends Application {
private TextField tfNumber1 = new TextField();
private TextField tfNumber2 = new TextField();
private TextField tfResult = new TextField();
@Override
public void start(Stage primaryStage) {
MenuBar menuBar = new MenuBar();
Menu menuOperation = new Menu("Operation");
Menu menuExit = new Menu("Exit");
menuBar.getMenus().addAll(menuOperation, menuExit);
MenuItem menuItemAdd = new MenuItem("Add");
MenuItem menuItemSubtract = new MenuItem("Subtract");
MenuItem menuItemMultiply = new MenuItem("Multiply");
MenuItem menuItemDivide = new MenuItem("Divide");
menuOperation.getItems().addAll(menuItemAdd, menuItemSubtract,
menuItemMultiply, menuItemDivide);
MenuItem menuItemClose = new MenuItem("Close");
menuExit.getItems().add(menuItemClose);
menuItemAdd.setAccelerator(
KeyCombination.keyCombination("Ctrl+A"));
menuItemSubtract.setAccelerator(
KeyCombination.keyCombination("Ctrl+S"));
menuItemMultiply.setAccelerator(
KeyCombination.keyCombination("Ctrl+M"));
menuItemDivide.setAccelerator(
KeyCombination.keyCombination("Ctrl+D"));
HBox hBox1 = new HBox(5);
tfNumber1.setPrefColumnCount(2);
tfNumber2.setPrefColumnCount(2);
tfResult.setPrefColumnCount(2);
hBox1.getChildren().addAll(new Label("Number 1:"), tfNumber1,
new Label("Number 2:"), tfNumber2, new Label("Result:"),
tfResult);
hBox1.setAlignment(Pos.CENTER);
HBox hBox2 = new HBox(5);
Button btAdd = new Button("Add");
Button btSubtract = new Button("Subtract");

95
Button btMultiply = new Button("Multiply");
Button btDivide = new Button("Divide");
hBox2.getChildren().addAll(btAdd, btSubtract, btMultiply, btDivide);
hBox2.setAlignment(Pos.CENTER);
VBox vBox = new VBox(10);
vBox.getChildren().addAll(menuBar, hBox1, hBox2);
Scene scene = new Scene(vBox, 300, 250);
primaryStage.setTitle("MenuDemo"); // Set the window title
primaryStage.setScene(scene); // Place the scene in the window
primaryStage.show(); // Display the window
// Handle menu actions
menuItemAdd.setOnAction(e -> perform('+'));
menuItemSubtract.setOnAction(e -> perform('-'));
menuItemMultiply.setOnAction(e -> perform('*'));
menuItemDivide.setOnAction(e -> perform('/'));
menuItemClose.setOnAction(e -> System.exit(0));
// Handle button actions
btAdd.setOnAction(e -> perform('+'));
btSubtract.setOnAction(e -> perform('-'));
btMultiply.setOnAction(e -> perform('*'));
btDivide.setOnAction(e -> perform('/'));
}
private void perform(char operator) {
double number1 = Double.parseDouble(tfNumber1.getText());
double number2 = Double.parseDouble(tfNumber2.getText());
double result = 0;
switch (operator) {
case '+': result = number1 + number2; break;
case '-': result = number1 - number2; break;
case '*': result = number1 * number2; break;
case '/': result = number1 / number2; break;
}
tfResult.setText(result + "");
};
public static void main(String[] args) {
launch(args);
}
}

96
OUTPUT

RESULT:

Thus javafx application using menus was developed successfully and the output was verified.

97
Ex.No.11

Date: LARGEST OF THREE NUMBERS

Aim:
Program to find largest of three numbers

Algorithm:
1. Start the process
2. Initialize three variable num1, num2, num3
3. Get the input from the user using Scanner class
4. Use nested if statements with logical operators to check the largest of three input
variables
5. Print the largest of the three variables
6. Stop the process

98
PROGRAM

import java.util.Scanner;
public class ifdemo
{
public static void main(String args[])
{
int num1, num2, num3;
System.out.println("Enter three integers: ");
Scanner in = new Scanner(System.in);
num1=in.nextInt();
num2=in.nextInt();
num3=in.nextInt();
if (num1 > num2 && num1 > num3)
System.out.println("The largest number is: "+num1);
else if (num2 > num1 && num2 > num3)
System.out.println("The largest number is: "+num2);
else if (num3 > num1 && num3 > num2)
System.out.println("The largest number is: "+num3);
else
System.out.println("The numbers are same.");
}
}

99
OUTPUT

RESULT:

Thus the java program to implement the largest of three numbers was implemented
successfully and the output was verified.

100
Ex.No.12

Date: IMPLEMENTING STRING FUNCTIONS

AIM:
To create a JAVA program to implement the string operation.

ALGORITHM:
STEP 1: Start the process.
STEP 2: Create a class StringExample.
STEP 3: Declare the string variables S1, X.
STEP 4: Concentrate the string and integer values and store it in string S2.
STEP 5: Declare S3 string and assign it the substring () function and also declare string S4
and S5. STEP 6: Display the string S1, S2, S3, S4, S5 using system.out.println ().
STEP 7: Declare the integer variable x and y string variables.
STEP 8: Display the string S6, S7 and S8.
STEP 9: Stop the process.

101
PROGRAM

public class StringExample {


public static void main(String[] args){
String s1="Computer Science";
int x=307;
String s2=s1+" "+x;
String s3=s2.substring(10,17);
String s4="is fun";
String s5=s2+s4;
System.out.println("s1:"+s1);
System.out.println("s2:"+s2);
System.out.println("s3:"+s3);
System.out.println("s4:"+s4);
System.out.println("s5:"+s5);
x=3;
int y=5;
String s6=x+y+"total";
String s7="total"+x+y;
String s8=" "+x+y+"total";
System.out.println("s6:"+s6);
System.out.println("s7:"+s7);
System.out.println("s8:"+s8);
}
}

102
OUTPUT

103
RESULT:
Thus a java program to implement string function has been executed and the result is
verified.

104
Ex.No.13

Date: JAVAFX APPLICATION FOR VBOX

AIM
To develop a JavaFX program to demonstrate VBox.
Algorithm:
1. Start the JavaFX application in Netbeans IDE 8.2
2. Initialize the start method having Stage as parameter
3. Declare two buttons Button 1 and Button 2
4. Create an object root for the VBox pane
5. Add the root object to the Scene
6. Add the button 1 and button 2 to the root using getChildren().addAll() methods
7. Add the scene in the stage
8. Display the stage using primaryStage.Show() method
9. Launch the application using launch() method in the main function.
10. Stop the process.

105
PROGRAM
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Vboxdemo extends Application
{
@Override
public void start(Stage primaryStage) throws Exception {
Button btn1 = new Button("Button 1");
Button btn2 = new Button("Button 2");
VBox root = new VBox();
Scene scene = new Scene(root,200,200);
root.getChildren().addAll(btn1,btn2);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}

106
OUTPUT

107
RESULT
Thus the program to create a VBox in JavaFX application was developed successfully
and the output was verified.

108
Ex.No.14

Date: JAVAFX APPLICATION FOR DRAWING A LINE

AIM
To develop a JavaFX program to draw a line.
Algorithm:
1. Start the JavaFX application in Netbeans IDE 8.2
2. Initialize the start method having Stage as parameter
3. Create an object for the line class
4. Set the starting and ending points for X and Y
5. Create an object root for the Group class
6. Add the root object to the Scene
7. Set the title for the JavaFX application
8. Add the scene in the stage
9. Display the stage using stage.Show() method
10. Launch the application using launch() method in the main function.
11. Stop the process.

109
PROGRAM
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class linedemo extends Application
{
@Override
public void start(Stage stage) {
//Creating a line object
Line line = new Line();

//Setting the properties to a line


line.setStartX(100.0);
line.setStartY(150.0);
line.setEndX(500.0);
line.setEndY(150.0);

//Creating a Group
Group root = new Group(line);

//Creating a Scene
Scene scene = new Scene(root, 600, 300);

//Setting title to the scene


stage.setTitle("Sample application");

//Adding the scene to the stage


stage.setScene(scene);

//Displaying the contents of a scene


stage.show();
}

public static void main(String args[])


{
launch(args);
}
}

110
OUTPUT

111
RESULT
Thus the program to draw a line using JavaFX was implemented successfully and the
output was verified.

112
Ex.No.15

Date: JAVAFX APPLICATION FOR RADIO BUTTON

AIM
To develop a JavaFX program to create a Radio Button.
Algorithm:
1. Start the JavaFX application in Netbeans IDE 8.2
2. Initialize the start method having Stage as parameter
3. Create an object for the Toggle Group Class.
4. Create four radio button namely button1, button2, button3, button4 using RadioButton
class.
5. Add the four buttons into the Toggle Group class.
6. Create an object root for the VBox class
7. Add all the four button into the root object using root.getChildren().addAll().
8. Add the scene in the stage
9. Display the stage using stage.Show() method
10. Launch the application using launch() method in the main function.
11. Stop the process.

113
PROGRAM

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class radiobuttondemo extends Application
{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
ToggleGroup group = new ToggleGroup();
RadioButton button1 = new RadioButton("option 1");
RadioButton button2 = new RadioButton("option 2");
RadioButton button3 = new RadioButton("option 3");
RadioButton button4 = new RadioButton("option 4");
button1.setToggleGroup(group);
button2.setToggleGroup(group);
button3.setToggleGroup(group);
button4.setToggleGroup(group);
VBox root=new VBox();
root.setSpacing(10);
root.getChildren().addAll(button1,button2,button3,button4);
Scene scene=new Scene(root,400,300);
primaryStage.setScene(scene);
primaryStage.setTitle("Radio Button Example");
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}

114
OUTPUT

115
RESULT
Thus the program for creating a Radio Button using JavaFX was implemented
successfully and the output was verified.

116
Ex.No.16

Date: JAVAFX PROGRAM TO DEVELOP A CHECKBOX

AIM
To develop a JavaFX program to create a Radio Button.
Algorithm:
1. Start the JavaFX application in Netbeans IDE 8.2
2. Initialize the start method having Stage as parameter
3. Create a Label using Label class.
4. Create four checkbox button namely c1, c2, c3, c4 using Checkbox class.
5. Create an object root for the HBox class
6. Add all the four button into the root object using root.getChildren().addAll().
7. Add the scene in the stage
8. Display the stage using stage.Show() method
9. Launch the application using launch() method in the main function.
10. Stop the process.

117
PROGRAM

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class checkboxdemo extends Application
{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
Label l = new Label("What do you listen: ");
CheckBox c1 = new CheckBox("Radio one");
CheckBox c2 = new CheckBox("Radio Mirchi");
CheckBox c3 = new CheckBox("Red FM");
CheckBox c4 = new CheckBox("FM GOLD");
HBox root = new HBox();
root.getChildren().addAll(l,c1,c2,c3,c4);
root.setSpacing(5);
Scene scene=new Scene(root,800,200);
primaryStage.setScene(scene);
primaryStage.setTitle("CheckBox Example");
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}

118
OUTPUT

119
RESULT

Thus the program to create a checkbox using JavaFX was implemented successfully
and the output was verified.

120
Ex.No.17
JAVA PROGRAM TO IMPLEMENT FUNCTION
Date: OVERLOADING

Aim:
To develop a java program to implement the concept of function overloading.

Algorithm:

1. Start the process


2. Declare a class overloadingdemo in java
3. Declare three integer class variables a,b,c as public
4. Declare a function add() and add the two input variables a and b, then store the result
in c.
5. Declare another function add(int, int) and add the two input variables a and b, then
store the result in c.
6. Declare another function add(int, float) and add the two input variables a and b, then
store the result in c.
7. Declare another function add(float, float) and add the two input variables a and b, then
store the result in c.
8. Create an object for the overloadingdemo class and call all the member functions with
appropriate function signature.
9. Stop the process

121
PROGRAM

import java.io.*;
public class overloadingdemo
{
public int a,b,c;
public void add()
{
a=10;
b=5;
c=a+b;
System.out.println("The Added C value is:"+c);
}
public void add(int a, int b)
{
c=a+b;
System.out.println("The Int Int C value is:"+c);
}
public void add(int a, float b)
{
float c;
c=a+b;
System.out.println("The Int Float C value is:"+c);
}
public void add(float a, float b)
{
float c;
c=a+b;
System.out.println("The Float Float C value is:"+c);
}
public static void main(String[] args)
{
overloadingdemo obj=new overloadingdemo();
obj.add();
obj.add(10, 5);
obj.add(10, 5.5f);
obj.add(5.5f, 6.5f);
}
}

122
OUTPUT

The Added C value is:15


The Int Int C value is:15
The Int Float C value is:15.5
The Float Float C value is:12.0

123
RESULT
Thus the program for function overloading was implemented successfully and the
output was verified.

124
Ex.No.18
JAVA PROGRAM TO IMPLEMENT CONSTRUCTOR
Date: OVERLOADING

Aim:
To develop a java program to implement the concept of function overloading.

Algorithm:

1. Start the process


2. Declare a class hello in java
3. Declare three integer class variables a,b,c as public
4. Declare a constructor hello() and add the two input variables a and b, then store the
result in c.
5. Declare another constructor hello(int, int) and add the two input variables a and b,
then store the result in c.
6. Declare another constructor hello(int, float) and add the two input variables a and b,
then store the result in c.
7. Declare another constructor hello(float, float) and add the two input variables a and b,
then store the result in c.
8. Create an object for the hello class and pass the parameters using appropriate function
signature.
9. Stop the process

125
PROGRAM
import java.io.*;
public class hello
{
public int a,b,c;
public hello()
{
a=10;
b=5;
c=a+b;
System.out.println("The Added C value is:"+c);
}
public hello(int a, int b)
{
c=a+b;
System.out.println("The Int Int C value is:"+c);
}
public hello(int a, float b)
{
float c;
c=a+b;
System.out.println("The Int Float C value is:"+c);
}
public hello(float a, float b)
{
float c;
c=a+b;
System.out.println("The Float Float C value is:"+c);
}
public static void main(String[] args)
{
System.out.println("Constructor Overloading Demo");
hello h=new hello();
hello h1=new hello(10,5);
hello h2=new hello(10, 5.5f);
hello h3=new hello(5.5f, 6.5f);
}
}

126
OUTPUT
Constructor Overloading Demo
The Added C value is:15
The Int Int C value is:15
The Int Float C value is:15.5
The Float Float C value is:12.0

127
RESULT
Thus the program for constructor overloading was implemented in java and the output
was verified.

128
Ex.No.19
JAVA PROGRAM TO IMPLEMENT MULTILEVEL
Date: INHERITANCE

Aim:
To develop a java program to implement the concept of multilevel inheritance.

Algorithm:

1. Start the process


2. Declare a class multidemo in java
3. Declare a class A as public and in it declare three integer variables a,b,c as public
4. Declare a function get() in A class and read the input for variable a and b
5. Declare a class B and inherit the class A using extends keyword
6. Declare a function add() in class B
7. Declare a class C and inherit the class B using extends keyword
8. Declare a function sub in class C
9. Declare a function mul in multidemo class
10. Create an object for multidemo class and invoke all the members present in the
multidemo class
11. Stop the process

129
PROGRAM

import java.io.*;
class A
{
public int a,b,c;
public void get()
{
a=10;
b=5;
}
}
class B extends A
{
public void add()
{
c=a+b;
System.out.println("The Added C Value"+c);
}
}
class C extends B
{
public void sub()
{
c=a-b;
System.out.println("The Subtracted C Value"+c);
}
}
public class multidemo extends C
{
public void mul()
{
c=a*b;
System.out.println("The Multiplied Value"+c);
}
public static void main(String[] args)
{
System.out.println("Multilevel Inheritance Demo");
multidemo s=new multidemo();
s.get();
s.add();
s.sub();
s.mul();
}

130
OUTPUT

Multilevel Inheritance Demo


The Added C Value 15
The Subtracted C Value 5
The Multiplied Value 50

131
RESULT
Thus the program for multilevel inheritance was implemented successfully and the
output was verified.

132
Ex.No.20

Date: FIBONACCI SERIES IN JAVA

Aim:
To develop a java program to generate Fibonacci Series.

Algorithm:

1. Start the process


2. Declare a class fibodemo in java
3. Declare the integer variable n1=0,n2=1,n3,i,count=10 as public
4. Initialize the for loop from 2 to count and increment by one
5. Add n1 and n2 and store in n3
6. Assign the value of n2 to n1
7. Assign the value of n3 to n2
8. Stop the process

133
PROGRAM
class fibodemo{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.println("Fibonacci Series in Java");
System.out.print(n1+" "+n2);//printing 0 and 1

for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed


{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}

}
}

134
OUTPUT
Fibonacci Series in Java
0 1 1 2 3 5 8 13 21 34

135

You might also like