0% found this document useful (0 votes)
16 views128 pages

Foop

The document contains practical programming exercises focused on Java, covering topics such as calculating areas and perimeters, average acceleration, palindrome checking, point-in-triangle determination, great circle distance, and string manipulation. Each practical includes code examples, expected outputs, and explanations of the tasks. The document is structured into three main practicals, each demonstrating different programming concepts and techniques.

Uploaded by

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

Foop

The document contains practical programming exercises focused on Java, covering topics such as calculating areas and perimeters, average acceleration, palindrome checking, point-in-triangle determination, great circle distance, and string manipulation. Each practical includes code examples, expected outputs, and explanations of the tasks. The document is structured into three main practicals, each demonstrating different programming concepts and techniques.

Uploaded by

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

OOP TERMWORK SUBMISSION [ALL PRACTICALS]

Practical 1

1. Write a program that displays the area and perimeter of a circle that has a radius of 5.5
using the following formula: perimeter = 2 * radius * pi, area = radius * radius * pi

Code :

class prac1_1{

public static void main(String[] args) {

float r = 5.5f;

double area;

area= 3.14*r*r;

double peremeter;

peremeter = 2*3.14*r;

System.out.println(area);

System.out.println(peremeter);

Output :

94.985

34.54
220280152057

2. Average acceleration is defined as the change of velocity divided by the time taken to
make the change, as shown in the following formula: a = v1 - v0/t Write a program that
prompts the user to enter the starting velocity v0 in meters/ second, the ending velocity v1
in meters/second, and the time span t in seconds, and displays the average acceleration.
Here is a sample run: Enter v0, v1, and t: 5.5 50.9 4.5 The average acceleration is 10.0889

Code :

import java.util.Scanner;

import java.util.*;

public class prac1_2 {

public static void main(String[] args){

double v0,v1,t,a;

Scanner sc = new Scanner(System.in);

v0 = sc.nextDouble();

v1 = sc.nextDouble();

t = sc.nextDouble();

a = (v1 - v0)/t;

System.out.println(“a= ”+a);

Output :

40

10

a=3.5
220280152057
3. Write a program that prompts the user to enter a three-digit integer and determines
whether it is a palindrome number. A number is palindrome if it reads the same from right to
left and from left to right. Here is a sample run of this program: Enter a three-digit integer:
121 121 is a palindrome Enter a three-digit integer: 123 123 is not a palindrome

Code :

import java.util.*;

public class prac1_3 {

public static void main(String[] args){

int sum=0,temp,n,r;

Scanner sc = new Scanner(System.in);

n= sc.nextInt();

temp=n;

while(n>0){

r= n%10;

sum = (sum*10) + r;

n=n/10;

if(temp==sum){

System.out.println("Number is plindrome");

else{

System.out.println("Number is not palindrome");

Output :

121

Number is palindrome
220280152057

4. Suppose a right triangle is placed in a plane. The right-angle point is placed at (0, 0), and the
other two points are placed at (200, 0), and (0, 100). Write a program that prompts the user to
enter a point with x- and y-coordinates and determines whether the point is inside the triangle.
Here are the sample runs: Enter a point's x- and y-coordinates: 100.5 25.5 The point is in the
triangle Enter a point's x- and y-coordinates: 100.5 50.5 The point is not in the triangle

Code :

import java.util.*;

class p1_4 {

public static void main(String[] args){

double x,y,z;

Scanner sc= new Scanner(System.in);

System.out.println("Enter X coordinate : ");

x= sc.nextDouble();

System.out.println("Enter Y coordinate : ");

y= sc.nextDouble();

z = x + (2*y) - 200;

if(x>=0 && y>=0 && x<=200 && y<=100 && z<=0){

System.out.println("Point is in Triangle");

else{

System.out.println("Point is not in triangle");

}
Output : Enter X coordinate :

100.5

Enter Y coordinate :

50.5

Point is not in triangle


220280152057

5. The great circle distance is the distance between two points on the surface of a sphere. Let
(x1, y1) and (x2, y2) be the geographical latitude and longitude of two points. The great circle
distance between the two points can be computed using the following formula: d = radius *
arccos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2)) Write a program that prompts the
user to enter the latitude and longitude of two points on the earth in degrees and displays its
great circle distance. The average earth radius is 6,371.01 km. Note that you need to convert
the degrees into radians using the Math.toRadians method since the Java trigonometric
methods use radians. The latitude and longitude degrees in the formula are for north and west.
Use negative to indicate south and east degrees. Here is a sample run: Enter point 1 (latitude
and longitude) in degrees: 39.55, -116.25 Enter point 2 (latitude and longitude) in degrees:
41.5, 87.37 The distance between the two points is 10691.79183231593 km

Code :

import java.util.*;

class p1_5{

public static void main (String[] args){

double x1,y1,x2,y2,d,r;

Scanner sc = new Scanner(System.in);

System.out.println("Enter first point latitude :");

x1 = Math.toRadians(sc.nextDouble());

System.out.println("Enter first point longitude :");

y1 = Math.toRadians(sc.nextDouble());

System.out.println("Enter second point latitude :"); x2

= Math.toRadians(sc.nextDouble());

System.out.println("Enter second point longitude :");

y2 = Math.toRadians(sc.nextDouble());

r=6371.01;

d = r* Math.acos(Math.sin(x1)* Math.sin(x2) + Math.cos(x1)*Math.cos(x2)*Math.cos(y1-y2));

System.out.println("Distance between two points is " +d+ " km" );

}}
220280152057

Enter first point latitude :

100

Enter first point longitude :

20.5

Enter second point latitude :

-25.3

Enter second point longitude :

45.3

Distance between two points is 13820.420161880218 km


220280152057

Practical Number-2
To learn Arrays and Strings in Java
1. Aim: Assume letters A, E, I, O, and U as the vowels. Write a
program that prompts the user to enter a string and displays
the number of vowels and consonants in the string.

Code :
import java.util.*;
public class prac2_1 {
public static void main(String[] args) { int
vcount = 0, ccount = 0;
System.out.println("Enter the string:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for (int i=0;i<str.length(); i++) {
if (str.charAt(i) == 'A' || str.charAt(i) == 'E' || str.charAt(i)
== 'I' || str.charAt(i) == 'O' || str.charAt(i) == 'U'||
str.charAt(i)=='a' || str.charAt(i)=='e' || str.charAt(i)=='i'||
str.charAt(i)=='o'|| str.charAt(i)=='u') {
vcount++;
}
else if ((str.charAt(i) >= 'A' && str.charAt(i) <=
'Z') || (str.charAt(i)>='a' && str.charAt(i)<='z')) {
ccount++;
}
}
System.out.println("The number of vowels in string
are " + vcount);
System.out.println("The number of consonants in
string are " + ccount);

1|Page
}
}

Output:
Enter the string:
HELLO
The number of vowels in string are 2
The number of consonants in string are 3

2|Page
220280152057

2. Aim: Write a program that prompts the user to


enter two strings and displays the largest
common prefix of the two strings.

Code :
import java.util.*;
public class prac2_2 {
public static void main(String[]
args) { int i;
System.out.println("Enter the 1st string:");
Scanner sc = new Scanner(System.in); String
s1 = sc.nextLine(); System.out.println("Enter
the 2nd string:"); String s2 = sc.nextLine();
System.out.println("The largest common prefix
is"); for(i=0;i<s1.length();i++){

if(s1.charAt(0)!=s2.charAt(0))
{ System.out.println("No largest common
prefix "); System.exit(0);
}
else if(s1.charAt(i)==s2.charAt(i))
{ System.out.print(s1.charAt(i));
}
}
}
}

3|Page
220280152057

Output:
Enter the 1st string:
hello
Enter the 2nd string:
welcome
No largest common prefix

Enter the 1st string:


welcometoc++
Enter the 2nd string:
welcometoc
The largest common prefix is
welcometoc

4|Page
220280152057

3. Aim: Some websites impose certain rules for passwords.


Write a method that checks whether a string is a valid
password. Suppose the password rules are as follows: A
password must have at least eight characters. A password
consists of only letters and digits. A password must
contain at least two digits. Write a program that prompts
the user to enter a password and displays Valid Password
if the rules are followed or Invalid Password otherwise.

Code :
import java.util.*;
public class prac2_3 {
public static void main(String[] args)
{ int dcount=0;
System.out.println("Enter the
string:"); Scanner sc = new
Scanner(System.in); String str =
sc.nextLine(); if(str.length()<8){
System.out.println("Password must have at
least 8 characters");
System.exit(0);
}
for(int i=0; i<str.length(); i++){
if (str.charAt(i)>='0' &&
str.charAt(i)<='9'){ dcount++;
}
else if((str.charAt(i)>=33 && str.charAt(i)<=64)||
(str.charAt(i)>=91 && str.charAt(i)<=96)||
(str.charAt(i)>=123 && str.charAt(i)<=127))
{ System.out.println("Password should not
contain
special characters");

5|Page
}
}
if(dcount<2){
System.out.println("Password must have at least 2
digits");
}
}
}

6|Page
220280152057

4. Aim: Write a method that returns a new array by eliminating


the duplicate values in the array using the following method
header: public static int[] eliminateDuplicates(int[] list) Write
a test program that reads in ten integers, invokes the
method, and displays the result.

Code :
import java.util.*;
public class prac2_4 {
public static int[] removeduplicates(int[]
a) { int[] temp = new int[a.length];
int k=0;
for (int i = 0; i <= a.length - 1; i++)
{ boolean isDuplicate = false;
for (int j = i + 1; j <= a.length-1;
j++) { if (a[i] == a[j]) {
isDuplicate =
true; break;
}
}
if (!isDuplicate)
{ temp[k] =
a[i]; k++;
}
}
System.out.println("The array after removing
duplicates is:");
for (int l = 0; l < k ; l++)
{ System.out.println(temp[l])
;
}
return Arrays.copyOf(temp,k);
}
7|Page
220280152057

public static void main(String[]


args) { int[] a = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the elements of
array:"); for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
removeduplicates(a);
}
}

Output:
Enter the elements of array:
1
2
3
1
5
4
2
23
1
2
The array after removing duplicates is:
3
5
4
23
1
2

8|Page
220280152057

5. Aim: Write a method that returns the index of the


smallest element in an array of integers. If the
number of such elements is greater than 1, return
the smallest index. Use the following header: public
static int indexOfSmallestElement(double[] array).

Code :
import java.util.*;
public class prac2_5 {
public static int indexofsmallestelement(int[]
array){ int sindex=0;
int selement=array[0];
Scanner sc= new Scanner(System.in);
for(int i=0; i<array.length; i++){
if(array[i]<selement){
selement=array[i];
sindex=i;
}
}
System.out.println("The index of smallest element
is:"); System.out.println(sindex);
return sindex;
}
public static void main(String[] args) { int[] a =
new int[3]; System.out.println("Enter the
elements of array:"); Scanner sc= new
Scanner(System.in);
for(int i=0; i<a.length; i+
+){ a[i]=sc.nextInt();
}

9|Page
220280152057

indexofsmallestelement(a);
}
}

Output:
Enter the elements of array:
6
4
5
The index of smallest element is:
1

10 | P a g e
220280152057

Practical Number-3
1. Aim: Design a class named Rectangle to represent a rectangle.
The class contains: Two double data fields named width and
height that specify the width and height of the rectangle.
The default values are 1 for both width and height.
A no-arg constructor that creates a default rectangle.
A constructor that creates a rectangle with the specified
width and height.
A method named getArea() that returns the area of
this rectangle.
A method named getPerimeter() that returns the perimeter.
Write a test program that creates two Rectangle objects—one
with width 4 and height 40 and the other with width 3.5 and
height 35.9. Display the width, height, area, and perimeter of
each rectangle in this order.

Java Program:

public class
Rectangle { double
height=1; double
width=1;
Rectangle(){
double height;
double width;
}
Rectangle(double height, double
width){ double h=height;
double w=width;
}

public static double getArea(double height, double


width){ double area;
area=height*width;
220280152057

return area;
}

public static double getPerimeter(double height,


double width){
double perimeter;
perimeter=2*(height + width);
return perimeter;
}

public static void main(String[] args)


{ Rectangle obj1=new Rectangle(40,4);
Rectangle obj2=new Rectangle(35.9,3.5);
double area1 = Rectangle.getArea(40,4);
double perimeter1 = Rectangle.getPerimeter(40,4);
double area2 = Rectangle.getArea(35.9,3.5); double
perimeter2 = Rectangle.getPerimeter(35.9,3.5);
System.out.println(obj1.width);
System.out.println(obj1.height);
System.out.println(area1);
System.out.println(perimeter1);
System.out.println(obj2.width);
System.out.println(obj2.height);
System.out.println(area2);
System.out.println(perimeter2);
}
}
220280152057

Output:
1.0
1.0
160.0
88.0
1.0
1.0
125.64999999999999
78.8
220280152057

2. Aim: Design a class named Account that contains:


A private int data field named id for the account (default 0). A
private double data field named balance for the account (default
0). A private double data field named annualInterestRate that
stores the current interest rate (default 0). Assume all accounts
have the same interest rate. A private Date data field named
dateCreated that stores the date when the account was created. A
no-arg constructor that creates a default account.
A constructor that creates an account with the specified id
and initial balance.
The accessor and mutator methods for id, balance,
and annualInterestRate.
The accessor method for dateCreated.
A method named getMonthlyInterestRate() that returns the
monthly interest rate.
A method named getMonthlyInterest() that returns the monthly
interest.
A method named withdraw that withdraws a specified
amount from the account.
A method named deposit that deposits a specified amount to
the account.
Write a test program that creates an Account object with an
account ID of 1122 a balance of Re. 20,000 and an annual
interest rate of 4.5%. Use the withdraw method to withdraw
Re. 2,500 use the deposit method to deposit Re. 3,000 and print
the balance, the monthly interest, and the date when this
account was created.
220280152057

Java Program:

public class Account {


private int id;
private double balance;
private double annualInterestRate; // stores current
interest rate
private double dateCreated; // stores the date
when the account was created

Account() {
System.out.println("Constructor called");
id = 0;
balance = 0.0;
annualInterestRate = 0.0; // stores current interest rate
}

public Account(int id, double


balance) { this.id = id;
this.balance = balance;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public double getBalance() {


return balance;
}
220280152057

public void setBalance(double


balance) { this.balance = balance;
}

public double getAnnualInterestRate()


{ return annualInterestRate;
}

public void setAnnualInterestRate(double


annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}

public double getMonthlyInterestRate()


{ annualInterestRate /= 12.0;

return annualInterestRate;
}

public double getMonthlyInterest() {


double interest = balance *
getMonthlyInterestRate() / 100.0;

return interest;
}

public void withdraw(double


amount) { balance -= amount;
}
220280152057

public void deposit(double


amount) { balance += amount;
}
public static void main(String[] args) {
Account ac = new Account(1122, 20000.0);
ac.setAnnualInterestRate(4.5);
ac.withdraw(2500.0);
ac.deposit(3000.0);
System.out.println("Balance: " + ac.getBalance());
System.out.println("Monthly Interest: " +
ac.getMonthlyInterest());
}
}

Output:
Balance: 20500.0
Monthly Interest: 76.875
220280152057

3. Aim: Design a class named Stock that contains:


A string data field named symbol for the stock’s symbol.
A string data field named name for the stock’s name.
A double data field named previousClosingPrice that stores
the stock price for the previous day.
A double data field named currentPrice that stores the stock
price for the current time.
A constructor that creates a stock with the specified symbol
and name.
A method named getChangePercent() that returns the
percentage changed from previousClosingPrice to currentPrice.
Write a test program that creates a Stock object with the stock
symbol ORCL, the name Oracle Corporation, and the previous
closing price of 34.5. Set a new current price to 34.35 and
display the price-change percentage.

Java Program:

public class Stock


{ String symbol;
String name;
double previousClosingPrice;
double currentPrice;

public Stock(String symbol, String


name) { this.symbol = symbol;
this.name = name;
}
220280152057

public double getChangePercent(double


previousClosingPrice, double currentPrice) {
return (Math.abs(currentPrice -
previousClosingPrice) / previousClosingPrice )* 100;
}

public static void main(String[] args) {


Stock stock = new Stock("ORCL", "Oracle Corporation");
System.out.println(stock.getChangePercent(34.5, 34.35));
}
}

Output:
The percentage change in stock price is:
0.434782608695648
220280152057

Practical Number-4
1. Aim: (The Person, Student, Employee, Faculty, and Staff
classes) Design a class named Person and its two subclasses
named Student and Employee. Make Faculty and Staff
subclasses of Employee. A person has a name, address, phone
number, and email address. A student has a class status
(freshman, sophomore, junior, or senior). Define the status as a
constant. An employee has an office, salary, and date hired. A
faculty member has office hours and a rank. A staff member
has a title. Override the toString method in each class to display
the class name and the person’s name.
Write a test program that creates a Person, Student, Employee,
Faculty, and Staff, and invokes their toString() methods.

Java Program:

import java.util.*;
public class Person {
private String name;
private String address;
private String MobileNo;
private String email;

public String toString()


{ System.out.println("Person
Method"); return
getClass().getName() + "@" +
Integer.toHexString(hashCode());
}

public static void main(String[]


args) { Person p = new Person();

p.name = "Meet";
220280152057

p.address = "Ahmedabad";
p.MobileNo = "9428041999";
p.email = "[email protected]";
System.out.println("Person name is " + p.name);
System.out.println("Person address is " + p.address);
System.out.println("Person mobile number is " +
p.MobileNo);
System.out.println("Person email id is " +
p.email); System.out.println(p);

Student s = new Student();


p.name = "Dev";
p.address = "Navsari";
p.MobileNo = "7516423592";
p.email = "[email protected]";
System.out.println("Student name is " + p.name);
System.out.println("Student address is " + p.address);
System.out.println("Student mobile number is " +
p.MobileNo);
System.out.println("Student email id is " +
p.email); System.out.println(s);

Employee e = new Employee();


p.name = "Divy";
p.address = "Mehsana";
p.MobileNo = "4568754236";
p.email = "[email protected]";
System.out.println("Employee name is " + p.name);
System.out.println("Employee address is " + p.address);
System.out.println("Employee mobile number is " +
p.MobileNo);

System.out.println("Employee email id is " + p.email);


220280152057

System.out.println(e);

Faculty f = new Faculty(); p.name = "Archana


Mam"; p.address = "Ahmedabad"; p.MobileNo
= "7894561230"; p.email = "[email protected]";
System.out.println("Faculty name is " +
p.name); System.out.println("Faculty address is
" + p.address); System.out.println("Faculty
mobile number is " +

p.MobileNo);
System.out.println("Faculty email id is " +
p.email); System.out.println(f);

Staff S = new Staff();


p.name = "Suresh Bhai";
p.address = "Ahmedabad";
p.MobileNo = "9876543210";
p.email = "[email protected]";
System.out.println("Staff name is " + p.name);
System.out.println("Staff address is " + p.address);
System.out.println("Staff mobile number is " +
p.MobileNo);
System.out.println("Staff email id is " +
p.email); System.out.println(S);
}
}

class Student extends Person {


class Status {
String freshman;

String sophomore;
220280152057

String junior;
String senior;

public String toString()


{ System.out.println("Student
Method"); return
getClass().getName() + "@" +
Integer.toHexString(hashCode());
}
}
}

class Employee extends Person {


String office;
double salary;
Date hiredDate;

public String toString()


{ System.out.println("Employee
Method"); return getClass().getName() +
"@" +
Integer.toHexString(hashCode());
}
}

class Faculty extends Employee {


int officehours;
int rank;

public String toString()


{ System.out.println("Faculty
Method"); return
getClass().getName() + "@" +
Integer.toHexString(hashCode());
}
220280152057

class Staff extends Employee {


String title;

public String toString()


{ System.out.println("Staff Method");
return getClass().getName() + "@" +
Integer.toHexString(hashCode());
}
}

Output:
Person name is Meet
Person address is Ahmedabad
Person mobile number is 9428041999
Person email id is [email protected]
Person Method
Person@5acf9800
Student name is Dev
Student address is Navsari
Student mobile number is 7516423592
Student email id is [email protected]
Person Method
Student@36baf30c
Employee name is Divy
Employee address is Mehsana
Employee mobile number is 4568754236
Employee email id is [email protected]
Employee Method
Employee@5ca881b5

Faculty name is Archana Mam


220280152057

Faculty address is Ahmedabad


Faculty mobile number is 7894561230
Faculty email id is [email protected]
Faculty Method
Faculty@4517d9a3
Staff name is Suresh Bhai
Staff address is Ahmedabad
Staff mobile number is 9876543210
Staff email id is [email protected]
Staff Method
Staff@2f92e0f4
220280152057

2. Aim: (The Account class) Design a class named Account


that contains:
■ A private int data field named id for the account (default 0).
■ A private double data field named balance for the account
(default 0).
■ A private double data field named annualInterestRate that
stores the current interest rate (default 0). Assume all
accounts have the same interest rate.
■ A private Date data field named dateCreated that stores
the date when the account was created.
■ A no-arg constructor that creates a default account.
■ A constructor that creates an account with the specified id
and initial balance.
■ The accessor and mutator methods for id, balance,
and annualInterestRate.
■ The accessor method for dateCreated.
■ A method named getMonthlyInterestRate() that returns
the monthly interest rate.
■ A method named getMonthlyInterest() that returns
the monthly interest.
■ A method named withdraw that withdraws a specified
amount from the account.
■ A method named deposit that deposits a specified amount
to the account.
(Subclasses of Account)Create two subclasses for checking
and saving accounts. A checking account has an overdraft
limit, but a savings account cannot be overdrawn.
Write a test program that creates objects of Account,
SavingsAccount, and CheckingAccount and invokes their
toString() methods.
220280152057

Java Program:

public class Accounts {


private int id;
private double balance;
private double annualInterestRate;

Accounts(){
id=0;
balance=0.0;
annualInterestRate=0.0;
}

public Accounts(int id, double balance){


this.id=id;
this.balance=balance;
}

public int getId(){


return id;
}

public void setId(int id){


this.id=id;
}

public double getBalance(){


return balance;
}

public void setBalance(double


balance){ this.balance=balance;
}
220280152057

public double getAnnualInterestRate()


{ return annualInterestRate;
}

public void setAnnualInterestRate(double


annualInterestRate){
this.annualInterestRate=annualInterestRate;
}

public double getMonthlyInterestRate()


{ return annualInterestRate/12.0;
}

public double getMonthlyInterest(){


return balance * getMonthlyInterestRate()/100.0;
}

public void withdraw(double amount){


balance = balance - amount;
}

public void deposit(double amount){


balance = balance + amount;
}

public String toString(){


return "id,amount,balance,deposit,withdraw";
}

public static void main(String[] args)


{ Accounts a = new
Accounts(101,500000); Checking c = new
Checking();
220280152057

Savings s = new Savings();


a.getId();
a.setId(101);
a.getBalance();
a.setBalance(500000);
a.getAnnualInterestRate();
a.setAnnualInterestRate(2.0);
a.getMonthlyInterestRate();
a.getMonthlyInterest();
System.out.println("Id = "+a.id);
System.out.println("Balance = "+a.balance);
System.out.println("AnnualInterestRate =
"+a.annualInterestRate+" %");
System.out.println("Monthly Interest Rate =
"+a.getMonthlyInterestRate());
System.out.println("Monthly Interest =
"+a.getMonthlyInterest());
a.withdraw(5000.0);
System.out.println("Balance after withdrawal =
"+a.balance);
a.deposit(4000.0);
System.out.println("Balance after Deposit =
"+a.balance); System.out.println(a.toString());
System.out.println(c.toString());
System.out.println(s.toString());
}
}

class Checking extends Accounts{


double overDraftLimit;

public String toString(){


220280152057

return "OverDraft Limit";


}
}

class Savings extends Accounts{


public String toString(){
return "This account cannot be overdrawn";
}
}

Output:
Id = 101
Balance = 500000.0
AnnualInterestRate = 2.0 %
Monthly Interest Rate =
0.16666666666666666 Monthly Interest =
833.3333333333333 Balance after withdrawal
= 495000.0 Balance after Deposit = 499000.0
id,amount,balance,deposit,withdraw OverDraft
Limit
This account cannot be overdrawn
220280152057

3. Aim: Suppose that we are required to model students and


teachers in our application. We can define a super class called
Person to store common properties such as name and address,
and subclasses Student and Teacher for their specific
properties. For students, we need to maintain the courses taken
and their respective grades; add a course with grade, print all
courses taken and the average grade. Assume that a student
takes no more than 30 courses for the entire program. For
teachers, we need to maintain the courses taught currently, and
able to add or remove a course taught. Assume that a teacher
teaches not more than 5 courses concurrently.

Java Program:

import java.util.*;

import javax.xml.transform.Source;
public class Persons {

private String name;


private String address;
public Persons(String name, String address){
this.name=name;
this.address=address;
}

public String getName(){


return this.name;
}

public void setName(String name){


this.name=name;
}
220280152057

public String getAddress(){


return this.address;
}

public void setAddress(String


address){ this.address=address;
}

public String toString(){


return "The name is "+this.name+" and the
address is "+this.address;
}

public static void main(String[] args) {


Persons p = new Persons("Meet","Ahmedabad");
System.out.println(p.toString()); Student s =
new Student("Dev","Navsari");
System.out.println(s.getName());
System.out.println(s.getAddress());
System.out.println(s.toString("Dev",
"Navsari")); System.out.println(s.toString());
s.addCourseGrade("Artificial Intelligence",
9); s.addCourseGrade("Mathematics", 9);
s.addCourseGrade("Machine Learning", 9);
s.addCourseGrade("Java", 9);
s.printGrades();
System.out.println("The average grade of student
" + s.getName() + " is " + s.getAverageGrade());
Teacher t = new Teacher("Nikunj Sir", "Ahmedabad");
System.out.println(t.toString());
System.out.println(t.getName() + ": " + t.getAddress());
System.out.println(t.addCourse("OS"));
220280152057

System.out.println(t.addCourse("COA"));
System.out.println(t.addCourse("DS"));
System.out.println(t.removeCourse("DS"));
System.out.println(t.toString("Nikunj Sir", "Ahmedabad"));
}
}

class Student extends Persons{


int numCourses;
//String[] Courses
ArrayList<String> courses = new ArrayList<String>(1);
//int[] Grades
ArrayList<Integer> grades = new ArrayList<Integer>(1);
public Student(String name, String address){
super(name,address);
}

public String toString(){


return "This is Student SubClass";
}

public void addCourseGrade(String course, int


grade){ this.courses.add(course);
this.grades.add(grade);
}

public void printGrades(){


for(int i=0; i<this.grades.size(); i++)
{ System.out.println(this.grades.get(i))
;
}
}

public double getAverageGrade(){


220280152057

double totalGrade=0.0;
double avgGrade=0.0;
for(int i=0; i<this.grades.size();i++){
totalGrade += this.grades.get(i);
}
avgGrade = (double)
totalGrade/this.grades.size(); return avgGrade;
}

public String toString(String name, String address)


{ return "Student: "+name+ " ( " + address + " )";
}
}

class Teacher extends Persons {


int numCourses = 0;
// String[] courses;
ArrayList<String> courses = new ArrayList<String>(1);

public Teacher(String name, String


address) { super(name, address);
}

public String toString() {


return "This is Teacher SubClass.";
}

public boolean addCourse(String


course) { boolean add = true;
for (int i = 0; i < this.courses.size(); i++)
{ if (course == this.courses.get(i)) {
add = false;
} else {
220280152057

add = true;
}
}
return add;
}

public boolean removeCourse(String


course) { boolean remove = true;
for (int i = 0; i < this.courses.size(); i++)
{ if (course == this.courses.get(i)) {
remove = true;
} else {
remove = false;
}
}
return remove;
}

public String toString(String name, String address)


{ return "Teacher: " + name + " ( " + address + " )";
}
}

Output:
The name is Meet and the address is Ahmedabad
Dev
Navsari
Student: Dev ( Navsari )
This is Student SubClass
9
9
9
9
220280152057

The average grade of student Dev


is 9.0 This is Teacher SubClass.
Nikunj Sir: Ahmedabad
true
true
true
true
Teacher: Nikunj Sir ( Ahmedabad )
220280152057

Practical Number-5
1. Aim: Write a superclass called Shape (as shown in the
class diagram), which contains:
• Two instance variables color (String) and filled (boolean).
• Two constructors: a no-arg (no-argument) constructor
that initializes the color to "green" and filled to t rue, and a
constructor that initializes the color and filled to the given
values.
• Getter and setter for all the instance variables. By
convention, the getter for a boolean variable xxx is called
isXXX() (instead of getXxx() for all the other types).
• A toString() method that returns "A Shape with color of
xxx and filled/Not filled".
Write a test program to test all the methods defined in Shape.
220280152057

Write two subclasses of Shape called Circle and Rectangle, as


shown in the class diagram.
The Circle class contains:
• An instance variable radius (double).
• Three constructors as shown. The no-arg constructor initializes
the radius to 1.0.
• Getter and setter for the instance variable radius. • Methods
getArea() and getPerimeter().
• Override the toString() method inherited, to return "A Circle
with radius=xxx, which is a subclass of yyy", where yyy is the
output of the toString() method from the superclass.

The Rectangle class contains:


• Two instance variables width (double) and length (double).
• Three constructors as shown. The no-arg constructor initializes
the width and length to 1.0.
• Getter and setter for all the instance variables.
• Methods getArea() and getPerimeter().
• Override the toString() method inherited, to return "A Rectangle
with width=xxx and length=zzz, which is a subclass of yyy", where
yyy is the output of the toString() method from the superclass.
Write a class called Square, as a subclass of Rectangle. Convince
yourself that Square can be modeled as a subclass of Rectangle.
Square has no instance variable, but inherits the instance
variables width and length from its superclass Rectangle.
220280152057

• Provide the appropriate constructors (as shown in the class


diagram).
Hint:

• Override the toString() method to return "A Square with side=xxx,


which is a subclass of yyy", where yyy is the output of the
toString() method from the superclass.
• Do you need to override the getArea() and getPerimeter()? Try
them out.
• Override the setLength() and setWidth() to change both the
width and length, so as to maintain the square geometry.

Java Program:
class Shape{
protected String color;
protected boolean filled;
Shape(){
this.color = "green";
this.filled = true;
}
Shape(String color,boolean filled){
this.color = color;
220280152057

this.filled = filled;
}
public String color(String color){
return color;
}
public String toString(){
return "A shape with color "+color+" has filled value "+filled;
}
}
class Circle1 extends Shape{
private double rad;
public double getRad() {
return rad;
}

public void setRad(double rad) {


this.rad = rad;
}
Circle1(){
this.rad = 1;
}
Circle1(double rad){
220280152057

this.rad = rad;
}
Circle1(double rad,String color,boolean
filled){ this.rad = rad;
this.filled = filled;
this.color = color;
}
public double getperimeter1(){
if(rad<0){
System.out.println("invalid
radius"); return -1;
}
else{
double p = 2*Math.PI*rad;
return p;
}
}
public double getArea1(){
if(rad<0){
System.out.println("invalid
radius"); return -1;
}
else{
220280152057

double p = Math.PI*rad*rad;
return p;
}
}
@Override
public String toString() {
return "a circle with radius "+rad+" subclass
of "+ super.toString();
}
}
class Rectangle1 extends Shape {
protected double length;
protected double width;
Rectangle1() {
this.length = 1;
this.width = 1;
}
public void setLength(double
length) { this.length = length;
}
public void setWidth(double
width) { this.width = width;
}
220280152057

public double getLength() {


return length;
}
public double getWidth() {
return width;
}
Rectangle1(double length, double
width) { this.length = length;
this.width = width;
}
Rectangle1(double length, double width, String color,
boolean filled) {
this.length = length;
this.width = width;
this.color = color;
this.filled = filled;
}
public double Area1() {
if (length < 0 && width < 0)
{ System.out.println("invalid length and
width"); return -1;
} else {
220280152057

double area = length * width;


return area;
}
}
public double perimeter() {
if (length < 0 && width < 0)
{ System.out.println("invalid length and
width"); return -1;
} else {
double p = 2 * (length + width);
return p;
}
}
@Override
public String toString() {
return "rectangle length "+length+" and width
"+width+" subclass of "+super.toString();
}
}
class Square1 extends Rectangle1{
Square1(){
super();
}
Square1(double length){
220280152057

super(length,length);
}
Square1(double length,String color,boolean
filled){ super(length,length,color,filled);
}
@Override
public void setLength(double
length) { super.setLength(length);
}
@Override
public double getLength() {
return super.getLength();
}
public double area1(){
if(length < 0){
System.out.println("invalid length. ..... ");
return -1;
}
else{
double area = length*length;
return area;
}
}
220280152057

public double perimeter(){


if(length<0){
System.out.println("invalid length. .... ");
return -1;
}
else{
double perimeter = 4*length;
return perimeter;
}
}
public String toString() {
return "square length "+length+" and width "+width+"
subclass of "+super.toString();
}
}
public class prac5_1 {
public static void main(String[] args)

{ Shape s = new Shape();

System.out.println(s.toString());

Shape s1 = new Shape("pink",false);

System.out.println(s1.toString());

Circle1 c1 = new Circle1();

System.out.println(c1.toString());
220280152057

System.out.println("area of circle with radius


"+c1.getRad()+" is\n "+c1.getArea1());
System.out.println("perimeter of circle with
radius "+c1.getRad()+" is\n "+c1.getperimeter1());
Circle1 c2 = new Circle1(2);
System.out.println(c2.toString());
System.out.println("area of circle with radius
"+c2.getRad()+" is\n "+c2.getArea1());
System.out.println("perimeter of circle with
radius "+c2.getRad()+" is\n "+c2.getperimeter1());
Circle1 c3 = new Circle1(3,"blue",true);

System.out.println(c3.toString());

System.out.println("area of circle with radius


"+c3.getRad()+" is\n "+c3.getArea1());
System.out.println("perimeter of circle with
radius "+c3.getRad()+" is\n "+c3.getperimeter1());
Rectangle1 r = new Rectangle1();
System.out.println(r.toString());
System.out.println("area of rectangle is\n "+r.Area1());
System.out.println("perimeter of rectangle is\n "+r.perimeter());
Rectangle1 r1 = new Rectangle1(3,2);
System.out.println(r1.toString());
System.out.println("area of rectangle is\n "+r1.Area1());
System.out.println("perimeter of rectangle
is\n "+r1.perimeter());
Rectangle1 r2 = new Rectangle1(4,2,"silver",true);
220280152057

System.out.println(r2.toString());
System.out.println("area of rectangle is\n "+r2.Area1());
System.out.println("perimeter of rectangle
is\n "+r2.perimeter());
Square1 a = new Square1();
System.out.println(a.toString());
System.out.println("area of square with length
"+a.getLength()+" is\n "+a.area1());
System.out.println("perimeter of square with
length "+a.getLength()+" is\n "+a.perimeter());
Square1 a1 = new Square1(2);
System.out.println(a1.toString());
System.out.println("area of square with
length "+a1.getLength()+" is\n "+a1.area1());
System.out.println("perimeter of square with
length "+a1.getLength()+" is\n "+a1.perimeter());
Square1 a2 = new Square1(3,"golden",false);

System.out.println(a2.toString());

System.out.println("area of square with


length "+a2.getLength()+" is\n "+a2.area1());
System.out.println("perimeter of square with
length "+a2.getLength()+" is\n "+a2.perimeter());
}
}
220280152057

Output:
A shape with color green has filled value true
A shape with color pink has filled value false
a circle with radius 1.0 subclass of A shape with color green
has filled value true
area of circle with radius 1.0 is
3.141592653589793
perimeter of circle with radius 1.0 is
6.283185307179586
a circle with radius 2.0 subclass of A shape with color green
has filled value true
area of circle with radius 2.0 is
12.566370614359172 perimeter
of circle with radius 2.0 is
12.566370614359172
a circle with radius 3.0 subclass of A shape with color blue
has filled value true
area of circle with radius 3.0 is
28.274333882308138 perimeter
of circle with radius 3.0 is
18.84955592153876
rectangle length 1.0 and width 1.0 subclass of A shape
with color green has filled value true
area of rectangle is
220280152057

1.0
perimeter of rectangle is
4.0
rectangle length 3.0 and width 2.0 subclass of A shape
with color green has filled value true
area of rectangle is
6.0
perimeter of rectangle is
10.0
rectangle length 4.0 and width 2.0 subclass of A shape
with color silver has filled value true
area of rectangle is
8.0
perimeter of rectangle is
12.0
square length 1.0 and width 1.0 subclass of ractangle length 1.0 and
width 1.0 subclass of A shape with color green has filled value true
area of square with length 1.0 is
1.0
perimeter of square with length 1.0 is
4.0
square length 2.0 and width 2.0 subclass of rectangle length 2.0 and
width 2.0 subclass of A shape with color green has filled value true
area of square with length 2.0 is
4.0
220280152057

perimeter of square with length


2.0 is 8.0
square length 3.0 and width 3.0 subclass of rectangle length 3.0 and
width 3.0 subclass of A shape with color golden has filled value false
area of square with length 3.0 is
9.0
perimeter of square with length 3.0 is
12.0
220280152057

2. Aim: Define an abstract class Shape. Define two classes


Rectangle and Triangle from extending the Shape class as
shown blow. Test the call of getArea() methods by the
instances of all the classes.
220280152057

Java Program:

abstract class Shape3{ protected


String color = "red"; public
abstract double getArea();
public String toString(){
return "color of the shape is "+color+" and
area is "+getArea();
}
}
class Rect4 extends Shape3{
protected int length;
protected int width;
Rect4(int length,int width){
this.length = length;
this.width = width;
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
@Override
public String toString() {
return super.toString();
}
@Override
public double getArea() {
if(length < 0 && width < 0){
System.out.println("invalid length and
width. ... "); return -1;
}
220280152057

else{
double area = (double)
(length*width); return area;
}
}
}
class Triangle4 extends Shape3{
protected int base;
protected int height;
Triangle4(int base,int height){
this.base = base;
this.height = height;
}
public int getBase() {
return base;
}
public int getHeight() {
return height;
}
@Override
public double getArea() {
if(height < 0 && base < 0){
System.out.println("invalid base and
height ... "); return -1;
}
else{
double area = (double)
(0.5*height*base); return area;
}
}
}
public class prac5_2 {
public static void main(String[] args) {
220280152057

Rect4 r = new Rect4(2,3);


System.out.println("length of the rectangle is
"+r.getLength()+" and width is "+r.getWidth());
r.getArea();
System.out.println(r.toString());
Triangle4 t = new Triangle4(2,4);
System.out.println("base of the triangle is "+t.getBase()+"
and height is "+t.getHeight());
t.getArea();
System.out.println(t.toString());
}
}

Output:
length of the rectangle is 2 and width is 3
color of the shape is red and area is 6.0
base of the triangle is 2 and height is 4
color of the shape is red and area is 4.0
220280152057

3. Aim: (The ComparableCircle class) Define a class named


ComparableCircle that extends Circle and implements
Comparable. Implement the compareTo method to compare the
circles on the basis of area. Write a test class to find the larger
of two instances of ComparableCircle objects.

Java Program:

interface Comparable{
public void toComparable(ComparableCircle o);
}
/ Circle 1 class is consider from practical (i) of
5 class ComparableCircle extends Circle1
implements Comparable{
ComparableCircle(double
rad){ super(rad);
}
public void toComparable(ComparableCircle
o){ if(getArea1() < 0 || o.getArea1() < 0)
{ System.out.println("error: invalid. ... ");
}
else
{ if(getArea1()>o.getArea1()
){
System.out.println("1st circle has greater
area"); } else if (getArea1() == o.getArea1()) {
System.out.println("both circle has same area");
}
else{
System.out.println("2nd circle has greater area");
}
}
}
}
220280152057

public class prac5_3 {

public static void main(String[] args)


{ ComparableCircle c = new
ComparableCircle(2); ComparableCircle d =
new ComparableCircle(13); c.toComparable(d);
}
}

Output:
2nd circle has greater area
220280152057

Practical Number-6
1. Aim: Write a program that meets the following requirements: ■
Creates an array with 100 randomly chosen integers.
■ Prompts the user to enter the index of the array, then displays
the corresponding element value. If the specified index is out of
bounds, display the message Out of Bounds.
(ArrayIndexOutOfBoundsException)

Java Program:

import java.util.*;
public class prac6_1 {
public static void main(String[] args)
{ Scanner sc = new
Scanner(System.in); int a[] = new
int[100];
Random r = new Random();
for(int i=0; i<100; i++){
a[i]=r.nextInt();
}
System.out.println("Enter the index:");
int i = sc.nextInt();
try{
System.out.println("The element of that index is "+ a[i]);
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("Program Executed
Successfully"); sc.close();
}
}
220280152057

Output:
Enter the index:
5
The element of that index is 2004793661
Program Executed Successfully

Enter the index:


101
java.lang.ArrayIndexOutOfBoundsException: Index
101 out of bounds for length 100
at prac6_1.main(prac6_1.java:13)
Program Executed Successfully
220280152057

2. Aim: Write a program that prompts the user to read two


integers and displays their sum. Your program should prompt
the user to read the number again if the input is incorrect.
(InputMismatchException)

Java Program:

import java.util.*;
public class prac6_2 {
public static void main(String[] args)
{ Scanner sc = new
Scanner(System.in); int a, b;
try{
System.out.println("Enter two
numbers:"); a = sc.nextInt();
b = sc.nextInt();
System.out.println("The addition is "+ (a + b));
}
catch(InputMismatchException
e){ e.printStackTrace();
}
System.out.println("Program Executed
Successfully"); sc.close();
}
}
220280152057

Output:
Enter two numbers:
5
6
The addition is 11
Program Executed Successfully

Enter two numbers:


3
4.5
java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at prac6_2.main(prac6_2.java:10)
Program Executed Successfully
220280152057

3. Aim: Define the Triangle class with three sides. In a triangle,


the sum of any two sides is greater than the other side. The
Triangle class must adhere to this rule.
Create the IllegalTriangleException class, and modify the
constructor of the Triangle class to throw an
IllegalTriangleException object if a triangle is created with
sides that violate the rule, as follows:
/** Construct a triangle with the specified sides */
public Triangle(double side1, double side2, double side3)
throws IllegalTriangleException {
// Implement it
}

Java Program:

class IllegalTriangleException extends


Exception {
IllegalTriangleException()
{
super();
}

public String getMessage()


{
return "one side is grater than other two side";
}
}
class Triangle
{
double side1,side2,side3;
public Triangle(double side1, double side2, double
side3) throws IllegalTriangleException {
double a= side1;
220280152057

if(a<side2){
a = side2;
if(a<side3){
a = side3;
}
}
if(a == side1)
if(a >= side2+side3) throw new
IllegalTriangleException(); if(a == side2)
if(a >= side1+side3) throw new
IllegalTriangleException(); if(a == side3)
if(a >= side2+side1) throw new IllegalTriangleException();

this.side1 =side1;
this.side2 =side2;
this.side3 =side3;
}
}
public class prac6_3 {
public static void main(String[]
args) { try{
Triangle a = new Triangle(1,2,11); System.out.println("It
is a triangle as it follows the rule");
}
catch(Exception e){
System.out.println("Not a Triangle as it does not
follow the rule");
e.printStackTrace();
}
System.out.println("Program Executed Successfully");
}
}
220280152057

Output:
Not a Triangle as it does not follow the rule
IllegalTriangleException: one side is grater than other two side
at Triangle.<init>(prac6_3.java:30)
at prac6_3.main(prac6_3.java:40)
Program Executed Successfully
220280152057

Practical Number-7
1. Aim: (Extend Thread) Write a program to create a
thread extending Thread class and demonstrate the use
of slip() method.

Java Program:

public class prac7_1 extends


Thread{ public prac7_1()
{
this.start();;
}
public static void main( String args[])
{ System.out.println(Thread.currentThread().getName() + " is
start");
prac7_1 [] a = new prac7_1
[10]; for(int i = 0;i<10;i++)
{
a[i] = new prac7_1();
}
System.out.println(Thread.currentThread().getName()
+ " is end");
}
public void run(){
System.out.println("A new thread is formed "
+ Thread.currentThread().getName());
System.out.println("putting" +
Thread.currentThread().getName() + " in sleep");
try{
Thread.sleep(20000)
; }catch(Exception e)
{
220280152057

System.out.println(Thread.currentThread().getName() +
" is awake");
}
}

Output:
main is start
main is end
A new thread is formed Thread-1
A new thread is formed Thread-0
A new thread is formed Thread-3
A new thread is formed Thread-6
A new thread is formed Thread-7
A new thread is formed Thread-5
A new thread is formed Thread-4
puttingThread-3 in sleep
puttingThread-4 in sleep
A new thread is formed Thread-
9 puttingThread-9 in sleep
A new thread is formed Thread-2
A new thread is formed Thread-8
puttingThread-6 in sleep
puttingThread-1 in sleep
puttingThread-0 in sleep
puttingThread-5 in sleep
puttingThread-7 in sleep
puttingThread-2 in sleep
puttingThread-8 in sleep
Thread-9 is awake
Thread-6 is awake
Thread-1 is awake
220280152057

Thread-0 is awake

Thread-5 is awake
Thread-7 is awake
Thread-2 is awake
Thread-8 is awake
Thread-3 is awake
Thread-4 is awake
220280152057

2. Aim: (Implement Runnable) Write a program to create a


thread implementing Runnable interface and demonstrate the
use of join() method.

Java Program:

public class prac7_2 implements


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

public static void main( String args[])


{ System.out.println(Thread.currentThread().getName()
+ " is start");
prac7_2 [] a = new prac7_2
[10]; for(int i = 0;i<6;i++)
{
a[i] = new
prac7_2(); try{
(a[i].t).join(); System.out.println("");
System.out.println(a[i].t.getName() + " is joined with
"
+ Thread.currentThread().getName());
System.out.println("");
}
catch (Exception e) {}
}

System.out.println(Thread.currentThread().getName()
+ " is end");
220280152057

}
public void run()

{
System.out.println("A new thread is formed "
+ Thread.currentThread().getName());
System.out.println("putting" +
Thread.currentThread().getName() + " in sleep");
try{
Thread.sleep(2000);
}catch(Exception e)
{}
System.out.println(Thread.currentThread().getName() +
" is awake");
}
}

Output:
main is start
A new thread is formed Thread-0
puttingThread-0 in sleep
Thread-0 is awake

Thread-0 is joined with main

A new thread is formed Thread-1


puttingThread-1 in sleep
Thread-1 is awake

Thread-1 is joined with main

A new thread is formed Thread-2


puttingThread-2 in sleep
220280152057

Thread-2 is awake

Thread-2 is joined with main

A new thread is formed Thread-3


puttingThread-3 in sleep
Thread-3 is awake

Thread-3 is joined with main

A new thread is formed Thread-4


puttingThread-4 in sleep
Thread-4 is awake

Thread-4 is joined with main

A new thread is formed Thread-5


puttingThread-5 in sleep
Thread-5 is awake

Thread-5 is joined with main

main is end
220280152057

3. Aim: (Synchronize threads) Write a program that launches 10


threads. Each thread adds 1 to a variable sum that initially is 0.
Define an Integer wrapper object to hold sum. Run the
program with and without synchronization to see its effect.

Java Program:

import java.lang.*;

public class prac7_3 extends Thread


{ static Integer sum =
0; prac7_3()
{
this.start();
}
public static void main( String args[])
{ System.out.println("value of sum is " +
sum.intValue()); System.out.println("");
prac7_3[] a = new prac7_3[10];
for(int i =0 ; i<10; i++)
{
a[i] = new prac7_3();
}
}

public void run()


{
b1.add();
}
static class b1{
public static void add()
220280152057

{
System.out.println("adding 1 in sum by the "
+ Thread.currentThread().getName());

prac7_3.sum++;
System.out.println("now value of sum is :");
System.out.println(sum.intValue());
System.out.println("");
}
}
}

Output:
value of sum is 0

adding 1 in sum by the Thread-7


adding 1 in sum by the Thread-1
now value of sum is :
2
adding 1 in sum by the Thread-5
adding 1 in sum by the Thread-9
now value of sum is :
4

adding 1 in sum by the Thread-2


now value of sum is :
5
adding 1 in sum by the Thread-3
now value of sum is :
now value of sum is :
6

adding 1 in sum by the Thread-4


220280152057

now value of sum is :


7

adding 1 in sum by the Thread-0


adding 1 in sum by the Thread-6
now value of sum is :
9

adding 1 in sum by the Thread-8


now value of sum is :
10

now value of sum is :


10

now value of sum is :


10
220280152057

Practical Number-8
1. Aim: (Remove text) Write a program that removes all the
occurrences of a specified string from a text file. For
example, invoking java Practical7_1 John filename removes
the string John from the specified file. Your program should
get the arguments from the command line.

Java Program:

import java.io.*;
import java.util.*;

public class prac8_1 {


/** Main method */
public static void main(String[] args) throws Throwable{
/ Check command line parameter
usage if (args.length != 2) {
System.out.println("Usage: java RemoveText
filename"); System.exit(1);
}
/ Check if file exists
File file = new File(args[1]);
if (!file.exists()) {
System.out.println("File " + args[1] + " does not
exist"); System.exit(2);
}
/ Create an ArrayList
ArrayList<String> s2 = new
ArrayList<>(); try (
/ Create input file
Scanner input = new Scanner(file);)
{ while (input.hasNext()) {
220280152057

String s1 = input.nextLine();
s2.add(removeString(args[0], s1));
}
}
try (
// Create output file
PrintWriter output = new PrintWriter(file);)
{ for (int i = 0; i < s2.size(); i++) {
output.println(s2.get(i));
}
}
}

public static String removeString(String string, String line){


StringBuilder stringBuilder = new StringBuilder(line); int
start = stringBuilder.indexOf(string); // Start index int
end = string.length(); // End index
while (start >= 0) {
end = start + end;
stringBuilder = stringBuilder.delete(start, end);
start = stringBuilder.indexOf(string, start);
}
return stringBuilder.toString();
}
}

Output:
Usage: java RemoveText filename
220280152057

2. Aim: (Count characters, words, and lines in a file) Write a


program that will count the number of characters, words, and
lines in a file. Words are separated by whitespace characters.
The file name should be passed as a command-line argument.

Java Program:

import java.io.*;
import java.util.*;

public class prac8_2 {


/** Main method */
public static void main(String[] args) throws Throwable {
/ Check command line parameter
usage if (args.length != 1) {
System.out.println("Usage: java
filename"); System.exit(1);
}
/ Check if file exists
File file = new File(args[0]);
if (!file.exists()) {
System.out.println("File " + args[0] + " does not
exist"); System.exit(2);
}
int characters = 0; // Number of
character int words = 0; // Number of
words int lines = 0; // Number of lines
try (
// Create input file
Scanner input = new Scanner(file);)
{ while (input.hasNext()) {
lines++;
String line = input.nextLine();
220280152057

characters += line.length();

}
}
try (
// Create input file
Scanner input = new Scanner(file);)
{ while (input.hasNext()) {
String line = input.next();
words++;
}
}
// Display results
System.out.println("File " + file.getName() + "
has"); System.out.println(characters + "
characters"); System.out.println(words + "
words"); System.out.println(lines + " lines");
}
}

Output:
Usage: java filename
220280152057

3. Aim: (Write/read data) Write a program to create a file


named Practical7.txt if it does not exist. Write 100 integers
created randomly into the file using text I/O. Integers are
separated by spaces in the file. Read the data back from the
file and display the data in increasing order.

Java Program:

import java.util.*;
import java.io.*;

public class prac8_3


{ /** Main method */
public static void main(String[] args) throws Throwable
{ // Check if file exists
File file = new File("Exercise12_15.txt");
if (file.exists()) {
System.out.println("File already
exists"); System.exit(0);
}
try (
// Create output file
PrintWriter output = new PrintWriter(file);) {
/ Write 100 integers created radomly to
file for (int i = 0; i < 100; i++) {
output.print(((int) (Math.random() * 500) +
1)); output.print(" ");
}
}
// Crate and ArrayList
ArrayList<Integer> list = new
ArrayList<>(); try (
220280152057

// Create input file


Scanner input = new Scanner(file);) {

/ Read the data back from the


file while (input.hasNext()) {
list.add(input.nextInt());
}
}
/ Sort array list
Collections.sort(list);
/ Display data in increasing order
System.out.print(list.toString());
System.out.println();
}
}

Output:
[4, 6, 11, 17, 24, 27, 29, 57, 66, 67, 70, 71, 72, 72, 74, 84,
93,
110, 114, 115, 119, 120, 129, 135, 136, 152, 162, 164, 169, 172,
172, 176, 180, 187, 203, 203, 207, 209, 212, 222, 223, 227, 238,
239, 241, 243, 243, 244, 251, 261, 267, 270, 274, 276, 281, 282,
284, 286, 290, 294, 295, 295, 296, 301, 311, 312, 313, 314, 321,
327, 329, 329, 342, 343, 349, 349, 350, 365, 369, 378, 389, 397,
404, 406, 409, 416, 418, 425, 440, 443, 445, 450, 461, 464, 466,
476, 483, 491, 494, 497]
220280152057

Practical Number-9
1. Aim: (Decimal to binary) Write a recursive method that
converts a decimal number into a binary number as a string. The
method header is: public static String dec2Bin(int value). Write
a test program that prompts the user to enter a decimal number
and displays its binary equivalent.

Java Program:

public class prac9_1 {


public static String dec2Bin(int value)
{
if(value == 1 || value == 0)
return String.valueOf(value);

return dec2Bin(value/2)+ String.valueOf(value%2);

}
public static void main(String[] args) { System.out.println("The
equivalent binary of given number
is "+dec2Bin(15));
}
}

Output:
The equivalent binary of given number is 1111
220280152057

2. Aim: (Distinct elements in ArrayList) Write the following


method that returns a new ArrayList. The new list contains
the non-duplicate elements from the original list.
public static ArrayList removeDuplicates(ArrayList list).

Java Program:

import java.util.*;
class E implements Comparable<E>
{
int i;
E(int a)
{
this.i = a;
}
public int compareTo(E e)
{
if(e.i == this.i) return
0; if(e.i < this.i) return
1; else return -1;
}

}
public class prac9_2 {
public static ArrayList<E> removeDuplicates(ArrayList<E>
list) { ArrayList <E> newa = new ArrayList<E>();

for(int i = 0 ; i < list.size()-1;i++)


{
if(list.get(i).i == list.get(i+1).i)
continue;
else
newa.add(list.get(i));
220280152057

}
newa.add(list.get(list.size()-1));
return newa;
}
public static void main(String[] args) {
Random r = new Random();
ArrayList <E> arrx = new
ArrayList<E>(); E[] a = new E[10];
for(int i = 0 ; i < 5 ; i = i+2)
{ int b = r.nextInt();
a[i] = new E(b);
a[i+1] = new E(b);
arrx.add(a[i]);
arrx.add(a[i+1]);
}

System.out.println("Initial the element of arraylist are");


for (E e : arrx)
{
System.out.print(e.i + " ");
}
Collections.sort(arrx);
System.out.println("");
ArrayList <E> b = removeDuplicates(arrx);
System.out.println("");
System.out.println("After removing duplicates");
for (E e :b)
{
System.out.print(e.i + " ");
}
}
}
220280152057

Output:
Initial the element of arraylist are
-1740604387 -1740604387 -2005072672 -2005072672
750077308 750077308

After removing duplicates


-2005072672 -1740604387 750077308
220280152057

3. Aim: (Generic binary search) Implement the following


method using binary search.
public static <E extends Comparable
<E>> int binarySearch(E[] list, E key)

Java Program:

public class prac9_3 {


public static void main(String[] args)
{ Integer[] list = new Integer[10];
for (int i = 0; i < list.length; i++) {
list[i] = i;
}
System.out.println("The element 9 is present at
index: " + binarySearch(list, 9));
System.out.println("The element 5 is present at
index: " + binarySearch(list, 5));

public static <E extends Comparable<E>> int


binarySearch(E[] list, E value) {

int low = 0;
int high = list.length - 1;

while (high >= low) {


int mid = (high - low) / 2 + low;
if (list[mid].compareTo(value) == 0) return mid;

if (list[mid].compareTo(value) < 0)
low = mid + 1;
else
220280152057

high = mid - 1;

}
return -1;
}
}

Output:
The element 9 is present at index: 9
The element 5 is present at index: 5
220280152057

Practical Number-10
1. Aim: (Store numbers in a linked list) Write a program that
lets the user enter numbers from a graphical user interface
and displays them in a text area, as shown in Figure. Use a
linked list to store the numbers. Do not store duplicate
numbers. Add the buttons Sort, Shuffle, and Reverse to sort,
shuffle, and reverse the list.

JavaFX Program:

package com.example;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos; import
javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage; import
java.util.LinkedList;

public class prac10_1 extends Application {


220280152057

private LinkedList<Integer> numbers;

private TextArea displayArea;

public static void main(String[]


args) { launch(args);
}

@Override
public void start(Stage primaryStage) {
numbers = new LinkedList<>();

// Create input area


TextField inputField = new TextField();
Button addButton = new Button("Add");
addButton.setOnAction(e ->
addNumber(inputField.getText()));
HBox inputBox = new HBox(inputField,
addButton); inputBox.setSpacing(10);

// Create control buttons


Button sortButton = new Button("Sort");
sortButton.setOnAction(e -> sortList());

Button shuffleButton = new Button("Shuffle");


shuffleButton.setOnAction(e -> shuffleList());

Button reverseButton = new Button("Reverse");


reverseButton.setOnAction(e -> reverseList());

HBox buttonBox = new HBox(sortButton,


shuffleButton, reverseButton);
buttonBox.setSpacing(10);
220280152057

/ Create display area displayArea = new


TextArea();
displayArea.setEditable(false);
displayArea.setWrapText(true);
ScrollPane scrollPane = new
ScrollPane();
scrollPane.setContent(displayArea);
scrollPane.setFitToWidth(true);
scrollPane.setPrefWidth(100);
scrollPane.setPrefHeight(100);

/ Create main layout


VBox mainLayout = new
VBox(inputBox, scrollPane, buttonBox);
mainLayout.setSpacing(10);
mainLayout.setPadding(new Insets(10));
mainLayout.setAlignment(Pos.TOP_CENTER);

// Create scene and stage


Scene scene = new Scene(mainLayout, 300,
400); primaryStage.setTitle("Practical_10.1");
primaryStage.setScene(scene);
primaryStage.show();
}
private void addNumber(String input) {

int number = Integer.parseInt(input);

numbers.add(number);
displayNumbers();

}
220280152057

private void displayNumbers() {

StringBuilder sb = new StringBuilder();


for (int number : numbers) {
sb.append(number).append(" ");
}
displayArea.setText(sb.toString());
}
private void sortList() {
numbers.sort(null);
displayNumbers();
}
private void shuffleList()
{ java.util.Collections.shuffle(numbers)
; displayNumbers();
}
private void reverseList()
{ java.util.Collections.reverse(numbers)
; displayNumbers();
}
}

Output:
Before Sorting:
220280152057

After Sorting:

Before Shuffling:

After Shuffling:
220280152057

Before Reversing:

After Reversing:
220280152057

2. Aim: (Perform set operations on priority queues) Create two


priority queues, {"George", "Jim", "John", "Blake", "Kevin",
"Michael"} and {"George", "Katie", "Kevin", "Michelle",
"Ryan"}, and find their union, difference, and intersection.

Java Program:

import java.util.*;

public class prac10_2 {


public static void main(String[] args) {
String[] s = { "George", "Jim", "John", "Blake",
"Kevin", "Michael" };
PriorityQueue<String> q1 = new
PriorityQueue<String>(); q1.addAll(Arrays.asList(s));
String[] s1 = { "George", "Katie", "Kevin", "Michelle", "Ryan"
};
PriorityQueue<String> q2 = new
PriorityQueue<String>(); q2.addAll(Arrays.asList(s1));

PriorityQueue<String> union = new


PriorityQueue<>(q1); union.addAll(q2);
Set<String> a = new HashSet<>();
for (String element : union) {
a.add(element);
}
PriorityQueue<String> union1 = new PriorityQueue<>(a);
System.out.println("The union of two priority queue is" +
union1);
System.out.println(" ");

PriorityQueue<String> difference =
new PriorityQueue<>(q1);
220280152057

difference.removeAll(q2);

System.out.println("The difference of two priority queue is"


+ difference);
System.out.println("
");

PriorityQueue<String> intersection =
new PriorityQueue<>();
for (String element : q1) {
if (q2.contains(element)) {
intersection.add(element);
}
}
System.out.println("The intersection of two priority
queue is" + intersection);
}
}

Output:
The union of two priority queue is[Blake, George,
Michael, Jim, Katie, Ryan, Michelle, John, Kevin]
The difference of two priority queue is[Blake,
John, Jim, Michael]
The intersection of two priority queue is [George, Kevin]
220280152057

3. Aim: (Guess the capitals using maps) Store pairs of 10 states


and its capital in a map. Your program should prompt the user
to enter a state and should display the capital for the state.

Java Program:

import java.util.*;

public class prac10_3 {


public static void main(String[] args)
{ Map<String, String> m = new
HashMap<>(); m.put("Andhra_Pradesh",
"Amaravati"); m.put("Assam", "Dispur");
m.put("Bihar", "Patna"); m.put("Gujarat",
"Gandhinagar"); m.put("Goa", "Panaji");
m.put("Haryana", "Chandigarh");
m.put("Kerala", "Thiruvananthapuram");
m.put("Jharkhand", "Ranchi");

m.put(" Karnataka", "Bengaluru");


m.put("Maharashtra", "Mumbai");

Scanner sc = new Scanner(System.in);


System.out.println("Enter the State");
String s = sc.nextLine(); if
(m.containsKey(s)) {
System.out.println("The capital is " + m.get(s));
} else {
System.out.println("Not present in data");
}
}
}
220280152057

Output:
Enter the State
Gujarat
The capital is Gandhinagar

Enter the State


Arunachal Pradesh
Not present in data
220280152057

Practical Number-11
1. Aim: (Color and font) Write a program that displays five texts
vertically, as shown in Figure. Set a random color and opacity
for each text and set the font of each text to Times Roman,
bold, italic, and 22 pixels.

JavaFX Program:

package com.example;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene; import
javafx.scene.layout.HBox; import
javafx.scene.layout.VBox; import
javafx.scene.paint.Color; import
javafx.scene.text.Font; import
javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text; import
javafx.stage.Stage;

import java.util.Random;

public class prac11_1 extends Application {

public static void main(String[]


args) { launch(args);
220280152057

@Override
public void start(Stage primaryStage)
{ HBox hbox = new HBox();
hbox.setSpacing(10);
hbox.setPadding(new Insets(10));
hbox.setAlignment(Pos.CENTER_LEFT);

Random random = new Random();

for (int i = 1; i <= 5; i++) {


Text text = new Text("Java " + i);
text.setRotate(90);
text.setFont(Font.font("Times New Roman",
FontWeight.BOLD, FontPosture.ITALIC, 22));
text.setFill(generateRandomColor(random));
text.setOpacity(random.nextDouble());
hbox.getChildren().add(text);
}

Scene scene = new Scene(hbox,400,300);


primaryStage.setTitle("Text Display");
primaryStage.setScene(scene);
primaryStage.show();
}

private Color generateRandomColor(Random


random) { return Color.rgb(random.nextInt(256),
random.nextInt(256), random.nextInt(256));
}
}
220280152057

Output:
220280152057

2. Aim: (Display a bar chart) Write a program that uses a bar chart
to display the percentages of the overall grade represented by
projects, quizzes, midterm exams, and the final exam, as shown
in Figure 14.46b. Suppose that projects take 20 percent and are
displayed in red, quizzes take 10 percent and are displayed in
blue, midterm exams take 30 percent and are displayed in
green, and the final exam takes 40 percent and is displayed in
orange. Use the Rectangle class to display the bars.
Interested readers may explore the JavaFX BarChart class
for further study.

JavaFX Program:

package com.example;
import javafx.application.Application;
import javafx.stage.Stage; import
javafx.scene.Scene; import
javafx.scene.shape.Rectangle; import
javafx.scene.layout.HBox; import
javafx.scene.layout.VBox; import
javafx.scene.layout.StackPane;
import javafx.geometry.Pos; import
javafx.scene.text.Text; import
javafx.scene.paint.Color; import
javafx.geometry.Insets;
220280152057

public class prac11_2 extends Application


{ public static void main(String[] args) {
launch(args);
}
@Override // Override the start method in the
Application class
public void start(Stage primaryStage)
{ // Create a HBox
HBox hBox = new HBox(15);
hBox.setAlignment(Pos.BOTTOM_CENTER);

String[] type = {"Project", "Quiz", "Midterm",


"Final"}; double[] grade = {20, 10, 30, 40};

double max = getMax(grade);

double height = 200;


double width = 150;

StackPane pane = new StackPane();


pane.setPadding(new Insets(20, 15, 5, 15));

// Create 4 rectangles
Rectangle r1 = new Rectangle(0, 0, width, height *
grade[0] / max);
r1.setFill(Color.RED);
Rectangle r2 = new Rectangle(0, 0, width, height *
grade[1] / max);
r2.setFill(Color.BLUE);
Rectangle r3 = new Rectangle(0, 0, width, height *
grade[2] / max);
r3.setFill(Color.GREEN);
220280152057

Rectangle r4 = new Rectangle(0, 0, width, height *


grade[3] / max);
r4.setFill(Color.ORANGE);

// Create 4 Text objects


Text t1 = new Text(0, 0, type[0] + " -- " + grade[0] + "%");
Text t2 = new Text(0, 0, type[1] + " -- " + grade[1] + "%");
Text t3 = new Text(0, 0, type[2] + " -- " + grade[2] + "%");
Text t4 = new Text(0, 0, type[3] + " -- " + grade[3] + "%");

hBox.getChildren().addAll(getVBox(t1, r1),
getVBox(t2, r2),getVBox(t3, r3), getVBox(t4, r4));
pane.getChildren().add(hBox);

/ Create a scene and place it in the stage Scene scene =


new Scene(pane);
primaryStage.setTitle("Exercise_14_12"); // Set the stage
title
primaryStage.setScene(scene); // Place the scene in
the stage
primaryStage.show(); // Display the stage
}

public double getMax(double[] l) {


double max = l[0];
for (int i = 0; i < l.length; i++) {
if (l[i] > max)
max = l[i];
}
return max;
}
220280152057

public VBox getVBox(Text t, Rectangle r)


{ VBox vBox = new VBox(5);
vBox.setAlignment(Pos.BOTTOM_LEFT);
vBox.getChildren().addAll(t, r); return
vBox;
}
}

Output:
220280152057

3. Aim: (Display a rectanguloid) Write a program that displays a


rectanguloid, as shown in Figure 14.47a. The cube should
grow and shrink as the window grows or shrinks.

JavaFX Program:

package com.example;
import javafx.application.Application;
import javafx.scene.Scene; import
javafx.scene.layout.Pane; import
javafx.scene.paint.Color; import
javafx.scene.shape.Line; import
javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;

import java.util.ArrayList;

public class prac11_3 extends Application


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

@Override
public void start(Stage primaryStage) {
220280152057

Pane pane = new Pane();

ArrayList<Shape> shapes = new ArrayList<>();

Rectangle rec1 = new Rectangle(0,0, Color.TRANSPARENT);


rec1.setStroke(Color.BLACK);
rec1.xProperty().bind(pane.widthProperty().divide(4).subtr
act(25));
rec1.yProperty().bind(pane.heightProperty().divide(4).add(
25));
rec1.widthProperty().bind(pane.widthProperty().divide(2));
rec1.heightProperty().bind(pane.widthProperty().divide(2))
;
shapes.add(rec1);

Rectangle rec2 = new Rectangle(0,0, Color.TRANSPARENT);


rec2.setStroke(Color.BLACK);
rec2.xProperty().bind(pane.widthProperty().divide(4).add(2
5));
rec2.yProperty().bind(pane.heightProperty().divide(4).subtr
act(25));
rec2.widthProperty().bind(pane.widthProperty().divide(2));
rec2.heightProperty().bind(pane.widthProperty().divide(2))
;
shapes.add(rec2);

Line line1 = new Line();


line1.startXProperty().bind(rec1.xProperty());
line1.startYProperty().bind(rec1.yProperty());
line1.endXProperty().bind(rec2.xProperty());

line1.endYProperty().bind(rec2.yProperty());
220280152057

shapes.add(line1);

Line line2 = new Line();


line2.startXProperty().bind(rec1.xProperty());
line2.startYProperty().bind(rec1.yProperty().add(rec1.heigh
tProperty()));
line2.endXProperty().bind(rec2.xProperty());
line2.endYProperty().bind(rec2.yProperty().add(rec1.height
Property()));
shapes.add(line2);

Line line3 = new Line();


line3.startXProperty().bind(rec1.xProperty().add(rec1.width
Property()));
line3.startYProperty().bind(rec1.yProperty().add(rec1.heigh
tProperty()));
line3.endXProperty().bind(rec2.xProperty().add(rec1.width
Property()));
line3.endYProperty().bind(rec2.yProperty().add(rec1.height
Property()));
shapes.add(line3);

Line line4 = new Line();


line4.startXProperty().bind(rec1.xProperty().add(rec1.width
Property()));
line4.startYProperty().bind(rec1.yProperty());
line4.endXProperty().bind(rec2.xProperty().add(rec1.width
Property()));
line4.endYProperty().bind(rec2.yProperty());
shapes.add(line4);

pane.getChildren().addAll(shapes);
220280152057

Scene scene = new Scene(pane, 400, 400);


scene.xProperty().add(scene.yProperty());
primaryStage.setTitle("Welcome to Java");
primaryStage.setScene(scene);
primaryStage.show();
}
}

Output:
220280152057
220280152057

Practical Number-12
1. Aim: (Select a font) Write a program that can dynamically
change the font of a text in a label displayed on a stack pane.
The text can be displayed in bold and italic at the same time.
You can select the font name or font size from combo boxes,
as shown in Figure. The available font names can be obtained
using Font.getFamilies(). The combo box for the font size is
initialized with numbers from 1 to 100.

JavaFX Program:

package com.example;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label; import
javafx.scene.layout.BorderPane; import
javafx.scene.layout.HBox; import
javafx.scene.layout.StackPane; import
javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text; import
javafx.stage.Stage;
220280152057

public class prac12_1 extends Application {

Text text = new Text("Programming is fun");


ComboBox<String> cbFontFamilies = new ComboBox<>();

CheckBox chkBold = new CheckBox("Bold");


ComboBox<Integer> cbFontSize = new ComboBox<>();

CheckBox chkItalic = new


CheckBox("Italic"); @Override
public void start(Stage primaryStage) throws Exception {

// Center Text

Integer[] sizes = new Integer[100];

for (int i = 0; i < 100; i++)


sizes[i] = i + 1;
// Top pane nodes
cbFontFamilies.getItems().addAll(Font.getFamilies());
cbFontFamilies.setValue(text.getFont().getFamily());
cbFontFamilies.setOnAction(e-> update()); Label
lblFontFamilies = new Label("Font Name",
cbFontFamilies);
lblFontFamilies.setContentDisplay(ContentDisplay.RIGHT);

cbFontSize.getItems().addAll(getSizes());
cbFontSize.setValue((int)text.getFont().getSize());
cbFontSize.setOnAction(e -> {
update();
primaryStage.sizeToScene();
});
220280152057

Label lblFontSizes = new Label("Font Size",cbFontSize);


lblFontSizes.setContentDisplay(ContentDisplay.RIGHT);

// Top pane
HBox topPane = new HBox(lblFontFamilies, lblFontSizes);
topPane.setSpacing(5);
topPane.setPadding(new Insets(5));

/ Bottom pane nodes


chkBold.setOnAction(e-> update());
chkItalic.setOnAction(e-> update());

/ Bottom pane
HBox bottomPane = new HBox(chkBold, chkItalic);
bottomPane.setAlignment(Pos.CENTER);

StackPane centerPane = new StackPane(text);


BorderPane borderPane = new
BorderPane(centerPane); borderPane.setTop(topPane);
borderPane.setBottom(bottomPane);
primaryStage.setTitle("Prac_12_1");
primaryStage.setScene(new Scene(borderPane));
primaryStage.show();

}
private void update(){
FontWeight fontWeight = (chkBold.isSelected()) ?
FontWeight.BOLD : FontWeight.NORMAL;
FontPosture fontPosture =
(chkItalic.isSelected()) ? FontPosture.ITALIC :
FontPosture.REGULAR;
String fontFamily = cbFontFamilies.getValue();
double size = cbFontSize.getValue();
220280152057

text.setFont(Font.font(fontFamily, fontWeight,
fontPosture, size));
}

private Integer[] getSizes() { Integer[]


sizes = new Integer[100];

for (int i = 0; i < 100; i++)


sizes[i] = i + 1;

return sizes;
}

public static void main(String[]


args) { Application.launch(args);
}
}

Output:
220280152057

2. Aim: (Control a moving text) Write a program that displays


a moving text, as shown in Figure. The text moves from left
to right circularly. When it disappears in the right, it
reappears from the left. The text freezes when the mouse is
pressed and moves again when the button is released.

JavaFX Program:

package com.example;
import javafx.application.Application;
import javafx.animation.PathTransition;
import javafx.animation.Timeline; import
javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.scene.shape.Line;
import javafx.stage.Stage; import
javafx.util.Duration;

public class prac12_2 extends Application


{ public static void main(String[] args) {
launch(args);
}
@Override // Override the start method in the
Application class
public void start(Stage primaryStage)
{ Pane pane = new Pane();

Text text = new Text("Programing is


fun"); pane.getChildren().add(text);
220280152057

PathTransition pt = new
PathTransition(Duration.millis(10000),
new Line(-50, 50, 250, 50), text);
pt.setCycleCount(Timeline.INDEFINITE);
pt.play(); // Start animation

/ Create and register the handle


pane.setOnMousePressed(e -> {
pt.pause();
});

pane.setOnMouseReleased(e -> {
pt.play();
});

/ Create a scene and place it in the stage Scene scene =


new Scene(pane, 200, 100);
primaryStage.setTitle("Exercise_15_27"); // Set the stage
title
primaryStage.setScene(scene); // Place the scene in
the stage
primaryStage.show(); // Display the stage
}
}
220280152057

Output:
220280152057

3. Aim: (Create an image animator with audio) Create animation


in Figure to meet the following requirements:
■ Allow the user to specify the animation speed in a text field. ■
Get the number of iamges and image’s file-name prefix from the
user. For example, if the user enters n for the number of images
and L for the image prefix, then the files are L1.gif, L2.gif, and so
on, to Ln.gif. Assume that the images are stored in the image
directory, a subdirectory of the program’s class directory. The
animation displays the images one after the other.
■ Allow the user to specify an audio file URL. The audio
is played while the animation runs.

JavaFX Program:

package com.example;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.Label;
220280152057

import javafx.animation.Timeline; import


javafx.animation.KeyFrame; import
javafx.scene.media.Media; import
javafx.scene.media.MediaPlayer; import
javafx.scene.image.Image; import
javafx.scene.image.ImageView; import
javafx.geometry.Pos; import
javafx.geometry.HPos; import
javafx.util.Duration;

public class prac12_3 extends Application


{ public static void main(String[] args) {
launch(args);
}
protected TextField tfSpeed = new TextField();
protected TextField tfPrefix = new TextField();
protected TextField tfNumberOfImages = new TextField();
protected TextField tfURL = new TextField();
protected StackPane paneForImage = new StackPane();
protected Timeline animation;
protected int n = 1;

@Override // Override the start method in the


Application class
public void start(Stage primaryStage) { final int
COLUMN_COUNT = 27;
tfSpeed.setPrefColumnCount(COLUMN_COUNT);
tfPrefix.setPrefColumnCount(COLUMN_COUNT);
tfNumberOfImages.setPrefColumnCount(COLUMN_COUNT
);
tfURL.setPrefColumnCount(COLUMN_COUNT); /
/ Create a button
220280152057

Button btStart = new Button("Start Animation");


/ Create a grid pane for labels and text fields
GridPane paneForInfo = new GridPane();
paneForInfo.setAlignment(Pos.CENTER);
paneForInfo.add(new Label("Enter information for
animation"), 0, 0);
paneForInfo.add(new Label("Animation
speed in milliseconds"), 0, 1);
paneForInfo.add(tfSpeed, 1, 1);
paneForInfo.add(new Label("Image file prefix"), 0, 2);
paneForInfo.add(tfPrefix, 1, 2);
paneForInfo.add(new Label("Number of images"), 0, 3);
paneForInfo.add(tfNumberOfImages, 1, 3);
paneForInfo.add(new Label("Audio file URL"), 0, 4);
paneForInfo.add(tfURL, 1, 4);
/ Create a border pane BorderPane pane =
new BorderPane();
pane.setBottom(paneForInfo);
pane.setCenter(paneForImage);
pane.setTop(btStart);
pane.setAlignment(btStart, Pos.TOP_RIGHT);
/ Create animation
animation = new Timeline(
new KeyFrame(Duration.millis(1000),
e -> nextImage()));
animation.setCycleCount(Timeline.INDEFINITE);
/ Create and register the handler
btStart.setOnAction(e -> {
if (tfURL.getText().length() > 0) { MediaPlayer
mediaPlayer = new MediaPlayer(
new Media(tfURL.getText()));
mediaPlayer.play();
220280152057

}
if (tfSpeed.getText().length() > 0)
animation.setRate(Integer.parseInt(tfSpeed.getText()))
;
animation.play();
});
/ Create a scene and place it in the stage Scene scene =
new Scene(pane, 550, 680);
primaryStage.setTitle("Exercise_16_23"); // Set the stage
title
primaryStage.setScene(scene); // Place the scene in
the stage
primaryStage.show(); // Display the stage
}

/** Place imageView in pane */


private void getImage() {
paneForImage.getChildren().clear();
paneForImage.getChildren().add(new ImageView(new
Image(
"http://cs.armstrong.edu/liang/common/image/"
+ tfPrefix.getText() + n + ".gif")));
}

/** Load next image */


private void nextImage() {
n = n < Integer.parseInt( tfNumberOfImages.getText()) ?
n += 1 : 1;
getImage();
}
}

Output:
220280152057

You might also like