OOP - I - GTU - Study - Material - Lab Manual - Object Oriented Programming - I (3140705) - 08052020070602AM PDF
OOP - I - GTU - Study - Material - Lab Manual - Object Oriented Programming - I (3140705) - 08052020070602AM PDF
Lab Solution
Practical-1
2.
class PrintDemo{
//Main Method
public static void main(String[] args) {
}
}
Output:
3. WAP to print your address i) using single print ii) using multiple println
class PrintMultipleDemo{
//Main Method
public static void main(String[] args) {
1
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
2
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-2
import java.util.Scanner;
public class AdditionTwoNumber {
Output:
3
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
import java.util.Scanner;
public class AreaCircle {
//Declare Scanner
Scanner s = new Scanner(System.in);
//Scan Variable
System.out.print("Enter radius of circle:");
r = s.nextInt();
area = pi * r * r;
System.out.println("Area of circle:"+area);
}
}
Output:
import java.util.Scanner;
//Declare Scanner
Scanner in = new Scanner(System.in);
4
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.Scanner;
//Declare Scanner
Scanner sc = new Scanner(System.in);
sc = new Scanner(System.in);
5
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
english = sc.nextInt();
chemistry = sc.nextInt();
computers = sc.nextInt();
physics = sc.nextInt();
maths = sc.nextInt();
Output:
5. WAP that reads a number in meters, converts it to feet, and displays the result.
import java.util.Scanner;
public class MeterToFeet {
//Declare Scanner
Scanner input = new Scanner(System.in);
6
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
6. Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking
your weight in kilograms and dividing by the square of your height in meters. Write a
program that prompts the user to enter a weight in pounds and height in inches and
displays the BMI.
Note:- 1 pound=.45359237 Kg and 1 inch=.0254 meters.
import java.util.Scanner;
public class BMI {
//Declare Scanner
Scanner sc = new Scanner(System.in);
7
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
8
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-3
import java.util.Scanner;
//Declare Scanner
Scanner sc = new Scanner(System.in);
//Scan number
System.out.println("Enter a number:");
num = sc.nextInt();
if (num > 0)
{
System.out.println("Given number is a positive integer");
}
else if(num < 0)
{
System.out.println("Given number is a negative integer");
}
}
}
Output:
9
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
2. WAP that prompts the user to enter a letter and check whether a letter is a vowel or
consonants.
import java.util.Scanner;
public class VowelOrConsonant {
public static void main(String args[]){
//Declare Scanner
Scanner sc = new Scanner(System.in);
//Scan letter
System.out.println("Enter a character :");
char ch = sc.next().charAt(0);
Output:
10
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
3. WAP to find out largest number from given three numbers without using Logical Operator.
import java.util.Scanner;
public class Largest {
11
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
4. WAP to read marks of five subjects. Calculate percentage and print class accordingly. Fail
below 35, Pass Class between 35 to 45, Second Class between 45 to 60, First Class between
60 to 70, Distinction if more than 70.
import java.util.Scanner;
public class ClassFromPercentage {
//Declare Scanner
Scanner sc = new Scanner(System.in);
sc = new Scanner(System.in);
12
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
13
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
5. WAP to find out largest number from given 3 numbers using conditional operator.
import java.util.Scanner;
public class LargestConditional {
14
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.Scanner;
public class SimpleCalculator {
//Declare Scanner
Scanner sc = new Scanner(System.in);
15
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
switch(operator)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.printf("Operator is not correct");
return;
}
16
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
7. Three sides of a triangle are entered through the keyboard. WAP to check whether the
triangle is isosceles, equilateral, scalene or right angled triangle.
import java.util.Scanner;
public class TriangleType {
//Declare Scanner
Scanner sc = new Scanner(System.in);
if(a==b&&b==c)
System.out.println("Equilateral Triangle");
17
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
8. WAP that prompts the user to input number of calls and calculate the monthly telephone
bills as per the following rule:
Minimum Rs. 200 for up to 100 calls.
Plus Rs. 0.60 per call for next 50 calls.
Plus Rs. 0.50 per call for next 50 calls.
Plus Rs. 0.40 per call for any call beyond 200 calls.
import java.util.Scanner;
public class TelephoneBill {
public static void main(String args[]){
//Declare Variables
int totalCalls;
double billAmount;
18
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Declare Scanner
Scanner sc = new Scanner(System.in);
//Scan number
System.out.println("Enter the Number of Calls");
totalCalls = sc.nextInt();
if (totalCalls<=100)
billAmount=200;
else if (totalCalls>100 && totalCalls<=150)
billAmount=200+(0.60*(totalCalls-100));
else if (totalCalls>150 && totalCalls<=200)
billAmount=200+(0.60*50)+(0.50*(totalCalls-150));
else
billAmount=200+(0.60*50)+(0.50*50)+(0.40*(totalCalls-
200));
19
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-4
1. WAP to print numbers between two given numbers which is divisible by 2 but not divisible
by 3.
import java.util.Scanner;
public class DivisibleBy2Not3 {
20
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.Scanner;
public class Factorial {
//Declare Scanner
Scanner sc = new Scanner(System.in);
21
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.*;
class PrimeSimple{
public static void main(String[] args) {
int n, prime=0;
Scanner sc = new Scanner(System.in);
//Get details
System.out.print("Enter Number : ");
n = sc.nextInt();
if(prime == 1)
System.out.println("Number is not Prime");
else
System.out.println("Number is Prime");
}
}
22
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.*;
class Series{
public static void main(String[] args) {
//Declare Variables
int n;
double sum=0;
//Declare Scanner
Scanner sc = new Scanner(System.in);
//Scan variable
System.out.print("Enter Number : ");
n = sc.nextInt();
23
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.Scanner;
public class ReverseNumber {
//Declare Scanner
Scanner sc = new Scanner(System.in);
while(number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
24
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
6. WAP program to calculate the sum of all positive even numbers and the sum of all negative
odd numbers from a set of numbers. You can enter 0 (zero) to quit the program and thus it
displays the result.
import java.util.Scanner;
public class SumOddEen {
//Declare Scanner
Scanner sc = new Scanner(System.in);
while(true)
{
//Scan integer variable, enter zero to stop
System.out.println("Enter any Number:(Enter zero to
stop)");
number = sc.nextInt();
25
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
break;
}
System.out.println("Sum of positive even number:"+sumEven);
System.out.println("Sum of negative odd number:"+sumOdd);
}
}
Output:
26
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-5
import java.util.*;
class SimpleInterest{
//Method
static void calculateInterest(double principle, double
rate_of_interest, double number_of_years){
double simple_interest;
//Calculate Interest & Print
simple_interest = principle * rate_of_interest *
number_of_years;
System.out.println("Simple Interest = " + simple_interest);
}
//Main Method
public static void main(String[] args) {
double principle, rate_of_interest, number_of_years;
Scanner sc = new Scanner(System.in);
//Get details
System.out.print("Enter principle : ");
principle = sc.nextDouble();
System.out.print("Enter rate_of_interest of Interest : ");
rate_of_interest = sc.nextDouble();
System.out.print("Enter Number of Years : ");
number_of_years = sc.nextDouble();
//Method call
calculateInterest(principle,rate_of_interest,
number_of_years);
}
}
27
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
2. WAP to find maximum number from given two numbers using method.
import java.util.*;
class Max_2{
//Method
static void maxNumber(int number1, int number2){
int max = 0, equal = 0;
//Find Max
if(number1 > number2)
max = number1;
else if(number2 > number1)
max = number2;
else
equal = 1;
//Print Max
if(equal == 0)
System.out.println("Max number = " + max);
else
System.out.println("Both number are equal");
}
//Main Method
public static void main(String[] args) {
int number1, number2;
Scanner sc = new Scanner(System.in);
//Get details
28
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Method call
maxNumber(number1,number2);
}
}
Output:
import java.util.*;
class Fibonacci{
//Method
static void printFibonacci(int n){
int n1 = 1, n2 = 1, temp;
29
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Main Method
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
//Get details
System.out.print("Enter limit of fibonacci series : ");
n = sc.nextInt();
//Method call
printFibonacci(n);
}
}
Output:
4. WAP to accept a number and check whether the number is prime or not. Use method name
check (int n). The method returns 1, if the number is prime otherwise, it returns 0.
import java.util.*;
class Prime{
//Method
static int check(int n){
for(int i = 2; i < n; i++){
if(n % i == 0)
return 0;
}
30
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
return 1;
}
//Main Method
public static void main(String[] args) {
int n, prime;
Scanner sc = new Scanner(System.in);
//Get details
System.out.print("Enter Number : ");
n = sc.nextInt();
//Method call
prime = check(n);
if(prime == 0)
System.out.println("Number is not Prime");
else
System.out.println("Number is Prime");
}
}
Output:
5. WAP that calculates area of circle, triangle and square using method overloading.
import java.util.*;
class AreaOverloading{
//Method
void area(double radius){
31
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
double aoc;
aoc = 3.14 * radius * radius;
System.out.println("Area of Circle : "+ aoc);
}
void area(double base, double altitude){
double aot;
aot = 0.5 * base * altitude;
System.out.println("Area of Triangle : "+ aot);
}
void area(float side){
double aos;
aos = side * side;
System.out.println("Area of Square : "+ aos);
}
//Main Method
public static void main(String[] args) {
int ch;
double radius, base, altitude;
float side;
Scanner sc = new Scanner(System.in);
//Get details
System.out.print("Operations:-\n1.Area of Circle\n2.Area of
Triangle\n3.Area of Square\nEnter choice : ");
ch = sc.nextInt();
switch(ch){
case 1:
System.out.print("Enter radius : ");
radius = sc.nextDouble();
ao.area(radius);
break;
case 2:
System.out.print("Enter base length : ");
base = sc.nextDouble();
System.out.print("Enter altitude : ");
altitude = sc.nextDouble();
ao.area(base,altitude);
break;
case 3:
System.out.print("Enter side length : ");
side = sc.nextFloat();
ao.area(side);
32
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
break;
default:
System.out.println("Invalid choice!");
}
}
}
Output:
6. Write a method with following method header: public int gcd (int num1, int num2). Write a
program that prompts the user to enter two integers and compute the gcd of two integers.
[Note:The greatest common divisor (GCD) of two numbers is the largest number that
divides them both.]
import java.util.*;
class GCD{
//Method
static void gcd(int num1, int num2){
int ans = 1, flag = 0;
33
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Main Method
public static void main(String[] args) {
int num1, num2;
Scanner sc = new Scanner(System.in);
//Get details
System.out.print("Enter Number1 : ");
num1 = sc.nextInt();
System.out.print("Enter Number2 : ");
num2 = sc.nextInt();
//Method call
gcd(num1, num2);
}
}
Output:
34
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-6
import java.util.*;
class CountOddEven {
public static void main(String[] args) {
int a[], n, odd=0, even=0;
Scanner sc = new Scanner(System.in);
//Get size of array
System.out.print("Enter size of array : ");
n = sc.nextInt();
a = new int[n];
//Get elements of array
for(int i = 0; i < a.length; i++) {
System.out.print("Enter number : ");
a[i] = sc.nextInt();
}
//Count number of odd and even numbers
for(int i = 0; i < a.length; i++) {
if(a[i]%2==0)
even++;
else
odd++;
}
//Displaying result
System.out.println("\nTotal odd: " + odd);
System.out.println("\nTotal even: " + even);
}
}
35
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
2. WAP to accept n numbers in an array. Display the sum of all the numbers which are
divisible by either 3 or 5.
import java.util.*;
class Div_3_5{
public static void main(String[] args) {
int a[], n, sum = 0;
Scanner sc = new Scanner(System.in);
//Get size of array
System.out.print("Enter size of array : ");
n = sc.nextInt();
a = new int[n];
//Get elements of array
for(int i = 0; i < a.length; i++){
System.out.print("Enter number : ");
a[i] = sc.nextInt();
36
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
3. WAP to accept n numbers in an array. Now, enter a number and search whether the
number is present or not in the list of array elements by using linear search.
import java.util.*;
class ArraySearch{
public static void main(String[] args) {
int a[], n, x;
String message = "not found";
Scanner sc = new Scanner(System.in);
//Get size of array
System.out.print("Enter size of array : ");
n = sc.nextInt();
a = new int[n];
//Get elements of array
for(int i = 0; i < a.length; i++){
System.out.print("Enter number : ");
a[i] = sc.nextInt();
}
System.out.print("Enter number to search : ");
x = sc.nextInt();
for(int i = 0; i < a.length; i++){
if(a[i] == x){
message = "found at "+(i+1);
break;
}
}
37
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
System.out.println("Element "+message);
}
}
Output:
4. WAP to accept 10 numbers in an array. Pass this array to a function name bubble_sort
(int m []). Arrange all the numbers in ascending order using bubble sort and display them.
import java.util.*;
class BubbleSort {
public static void main(String[] args) {
int a[], n, temp;
Scanner sc = new Scanner(System.in);
//Get size of array
System.out.print("Enter size of array : ");
n = sc.nextInt();
a = new int[n];
//Get elements of array
for(int i = 0; i < a.length; i++) {
System.out.print("Enter number : ");
a[i] = sc.nextInt();
38
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
}
//Bubble Sort
for(int i = 1; i <= a.length; i++) {
for(int j = 0; j < a.length-i; j++){
if(a[j]>a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
//Displaying Sorted Array
System.out.println("\nSorted array:-");
for(int i = 0; i < a.length; i++){
System.out.println(a[i]);
}
}
}
Output:
39
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
5. WAP to read values in two-dimensional array and print them in matrix form.
//2D array
import java.util.*;
class TwoDArray{
public static void main(String[] args) {
int a[][], row, column;
Scanner sc = new Scanner(System.in);
//Get row and column
System.out.print("Enter number of rows of 2D array : ");
row = sc.nextInt();
System.out.print("Enter number of columns of 2D array : ");
column = sc.nextInt();
a = new int[row][column];
//Getting elements of 2D array
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
System.out.print("Enter element at a["+(i+1)+"]
["+(j+1)+"] : ");
a[i][j] = sc.nextInt();
}
}
//Displaying 2D array
System.out.println("\nArray in Matrix Form :-");
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
}
40
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
6. WAP to read two matrices of size n X n, perform multiplication operation and store result
in third matrix and print it.
//Matrix multiplication
import java.util.*;
class MatrixMultiplication{
public static void main(String[] args) {
int a[][], b[][],c[][], row, column;
Scanner sc = new Scanner(System.in);
//Get row and column
System.out.print("Enter number of rows of 2D array : ");
row = sc.nextInt();
System.out.print("Enter number of columns of 2D array : ");
column = sc.nextInt();
a = new int[row][column];
b = new int[row][column];
c = new int[row][column];
//Getting elements of 1st matrix
41
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Multiplication
for(int k = 0; k < row; k++){
for(int i = 0; i < row; i++){
c[k][i] = 0;
for(int j = 0; j < column; j++){
}
}
}
}
42
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
7. WAP to accept n numbers in an array. Pass this array to a function name selection_sort
(int m []). Arrange all the numbers in ascending order using selection sort and display them.
import java.util.*;
class SelectionSort{
public static void main(String[] args) {
int a[], n, temp;
43
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Selection Sort
for(int i = 0; i < a.length; i++){
for(int j = i+1; j < a.length; j++){
if(a[i]>a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
Output:
44
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
8. WAP to store numbers in 4 X 4 matrix in a two-dimensional array. Find the sum of the
numbers of each row and the sum of numbers of each column of the matrix.
import java.util.*;
class RowColumnSum{
public static void main(String[] args) {
int a[][], row, column, columnSum[], rowSum[];
Scanner sc = new Scanner(System.in);
a = new int[row][column];
rowSum = new int[row];
columnSum = new int[column];
//Adding Sum
for(int i = 0; i < row; i++){
rowSum[i] = columnSum[i] = 0;
for(int j = 0; j < column; j++){
rowSum[i] += a[i][j];
columnSum[i] += a[j][i];
}
}
45
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
else
System.out.print(a[i][j]+"\t");
}
if(i != row)
System.out.println(rowSum[i]);
}
}
}
Output:
46
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-7
import java.util.Scanner;
class Candidate{
//Declare Variables
int CandidateID;
int CandidateAge;
int CandidateWeight;
String CandidateName;
double CandidateHeight;
Scanner sc = new Scanner(System.in);
47
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Main Class
class CandidateDemo{
//Main method
public static void main(String[] args) {
//Object Initialization
Candidate cn = new Candidate();
//Call method
cn.getCandidateDetails();
cn.displayCandidateDetails();
}
}
Output:
import java.util.Scanner;
class BankAccount{
//Declare Variables
String AccountNumber;
48
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
String UserName;
String Email;
String AccountType;
double AccountBalance;
Scanner sc = new Scanner(System.in);
//Search Method
String searchAccount(String message, String AccountNo,
BankAccount bns){
//Compare Account Numbers
if(AccountNo.equals(bns.AccountNumber)){
message = "Found";
}
return message;
}
}
//Main Class
class BankAccountDemo{
//Main method
public static void main(String[] args) {
49
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Call method
bn1.getAccountDetails();
bn1.displayAccountDetails();
bn2.getAccountDetails();
bn2.displayAccountDetails();
bn3.getAccountDetails();
bn3.displayAccountDetails();
bn4.getAccountDetails();
bn4.displayAccountDetails();
bn5.getAccountDetails();
bn5.displayAccountDetails();
50
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.Scanner;
class Employee{
//Declare Variables
int EmployeeID;
int Age;
int Salary;
String EmployeeName, Designation;
Scanner sc = new Scanner(System.in);
51
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
EmployeeName = sc.next();
System.out.print("Enter Designation : ");
Designation = sc.next();
System.out.print("Enter Age : ");
Age = sc.nextInt();
System.out.print("Enter Salary : ");
Salary = sc.nextInt();
}
//Main Class
class EmployeeDemo{
//Main method
public static void main(String[] args) {
//Object Initialization
Employee e = new Employee();
//Call method
e.getEmployeeDetails();
e.displayEmployeeDetails();
}
}
52
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.Scanner;
class Student{
//Declare Variables
int EnrollmentNo;
int Semester;
String Name;
double CPI;
double SPI;
Scanner sc = new Scanner(System.in);
53
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Main Class
class StudentDemo{
//Main method
public static void main(String[] args) {
//Object Initialization
Student st = new Student();
//Call method
st.getStudentDetails();
st.displayStudentDetails();
}
}
54
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
55
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-8
1. WAP to create Circle class with area and perimeter function to find area and perimeter of
circle.
import java.util.Scanner;
// Class Circle
class Circle{
//Declare variables
double radius;
double areaOfCircle;
double perimiterOfCircle;
final double pi = 3.14;
Scanner sc = new Scanner(System.in);
//Display Results
void display(){
System.out.println("Area Of Circle = "+areaOfCircle);
System.out.println("Perimiter Of Circle = " +
perimiterOfCircle);
}
}
//Main Class
class CircleDemo{
//Main Method
public static void main(String[] args) {
56
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Object Intiatlization
Circle c = new Circle();
//Call Method
c.getRadius();
c.areaOfCircle();
c.perimiterOfCircle();
c.display();
}
}
Output:
2. Define Time class with hour and minute as data member. Also define addition method to
add two time objects.
import java.util.Scanner;
// Class Time
class Time{
//Declare variables
int hours;
int minutes;
Scanner sc = new Scanner(System.in);
57
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Display Results
void display(){
System.out.println("Total Time = "+hours+" h and " +
minutes + " m");
}
}
//Main Class
class TimeDemo{
//Main Method
public static void main(String[] args) {
//Object Intiatlization
Time t1 = new Time();
Time t2 = new Time();
Time t3;
//Call Method
t1.getDetails();
t2.getDetails();
t3 = t1.addTime(t2);
t3.display();
}
}
58
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
3. Define class for Complex number with real and imaginary part. Describe its constructor,
overload the constructors and instantiate its object. Also define addition method to add two
Complex objects.
import java.util.Scanner;
// Class ComplexNumbers
class ComplexNumbers{
//Declare variables
int real;
int imaginary;
int totalReal, totalImaginary;
Scanner sc = new Scanner(System.in);
//Constructor
ComplexNumbers(int i){
System.out.println("Enter Complex Numbers "+i);
System.out.print("Enter Real : ");
real = sc.nextInt();
System.out.print("Enter Imaginary : ");
imaginary = sc.nextInt();
}
59
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Display Results
void display(){
System.out.println("Total = "+ totalReal + "+" +
totalImaginary + "i");
}
}
//Main Class
class ComplexNumbersDemo{
//Main Method
public static void main(String[] args) {
//Object Intiatlization
ComplexNumbers cn1 = new ComplexNumbers(1);
ComplexNumbers cn2 = new ComplexNumbers(2);
//Call Method
cn1.addComplexNumbers(cn2);
cn1.display();
}
}
Output:
60
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-9
import java.util.*;
//Class Student
class Student{
//Declare Variables
int enrollmentNo;
String studetName;
String course;
Scanner sc = new Scanner(System.in);
//Method get student details
void getStudentDetails(){
System.out.println("Student Details :-");
System.out.print("Enter Enrollment No : ");
enrollmentNo = sc.nextInt();
System.out.print("Enter Student Name : ");
studetName = sc.next();
System.out.print("Enter Course : ");
course = sc.next();
}
}
//Class Result
class Result{
//Declare Variables
int enrollmentNo;
int sem;
double CPI;
double SPI;
Scanner sc = new Scanner(System.in);
61
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Main Class
class ResultDemo{
//Main Method
public static void main(String[] args) {
//Declare Variables
int n;
int enrollmentNumber;
int i;
boolean found = false;
Scanner sc = new Scanner(System.in);
//Get number of students
System.out.print("Enter number of students : ");
n = sc.nextInt();
//Object Initialization
Student st[] = new Student[n];
Result rs[] = new Result[n];
for(i = 0; i < n; i++){
st[i] = new Student();
rs[i] = new Result();
st[i].getStudentDetails();
rs[i].getResultDetails();
62
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Display Result
if(found == true){
rs[i].displayResultDetails(st, i);
}
else{
System.out.print("Not Found!");
}
}
}
Output:
63
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
2. Create array of object for Student_Detail (Enrollment_no, Name, Sem, CPI) class for 5
students, read their information and print it.
import java.util.Scanner;
class Student_Detail{
//Declare Variables
int EnrollmentNo;
int Semester;
String Name;
double CPI;
Scanner sc = new Scanner(System.in);
//Main Class
class ArrayStudent{
//Main method
public static void main(String[] args) {
//Declare Variables
int i, numberOfStudents;
Scanner sc = new Scanner(System.in);
//Get number of students
System.out.print("Enter number of students : ");
numberOfStudents = sc.nextInt();
64
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Object Initialization
Student_Detail st[] = new Student_Detail[numberOfStudents];
Output:
65
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
3. WAP that counts the number of objects created by using static variable.
import java.util.Scanner;
class CountObject{
//Declare Variables
static int noOfObjects = 0;
//Main Class
class CountObjectDemo{
//Main method
public static void main(String[] args) {
//Object Initialization
CountObject o1 = new CountObject();
66
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
67
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-10
import java.util.Scanner;
//Class Member
class Member{
//Declare variables
String name;
int age;
int phoneNumber;
String address;
double salary;
//printSalary Method
void printSalary(){
System.out.println("salary = "+salary);
}
}
//Class Employee
class Employee extends Member{
//Declare variables
String specialization;
//Parameterized Contructor
Employee(String n, int a, int ph, String add, double s, String
spe){
name=n;
68
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
age=a;
phoneNumber=ph;
address=add;
salary=s;
specialization=spe;
}
//Class Manager
class Manager extends Member{
//Declare variables
String department;
//Parameterized Contructor
Manager(String n, int a, int ph,String add, double s,String
dept){
name=n;
age=a;
phoneNumber=ph;
address=add;
salary=s;
department=dept;
}
69
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Main Class
class MemberDemo{
//Main Method
public static void main(String[] args) {
Employee e1 = new Employee("Mayur", 24,909997,"xyz, Surat",
45000,"Finance");
Manager m1 = new Manager("Manish",28,765434, "abc,Rajkot",
55000,"HR");
e1.displayEmployeeDetails();
m1.displayManagerDetails();
}
}
Output:
70
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
2. Design a class named MyPoint to represent a point with x- and y-coordinates. The class
contains:
The data fields x and y that represent the coordinates with getter methods.
o a no-arg constructor that creates a point (0, 0).
o a constructor that constructs a point with specified coordinates.
o a method named distance that returns the distance from this point to a specified
point of the MyPoint type.
o a method named distance that returns the distance from this point to another point
with specified x- and y-coordinates.
Create a class named ThreeDPoint to model a point in a three-dimensional space. Let
ThreeDPoint be derived from MyPoint with following additional features:
o a data fields named z that represents the z-coordinate.
o a no-arg constructor that creates a point (0, 0, 0).
o a constructor that constructs a point with three specified coordinates.
o a get method that returns the z value.
o Override the distance method to return the distance between two points in the three-
dimensional space.
Write a program that creates two points (0, 0, 0) and (10, 30, 25.5) and display the distance
between the two points.
import java.util.Scanner;
import java.lang.Math;
//Class MyPoint
class MyPoint{
//Declare Variables
double x;
double y;
Scanner sc = new Scanner(System.in);
//Default Contructor
MyPoint(){
x = 0;
y = 0;
}
//Parameterized Contructor
MyPoint(double x, double y){
this.x = x;
this.y = y;
71
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Distance Method
void distance(MyPoint mp2){
double distance = Math.sqrt((x-mp2.x)*(x-mp2.x) + (y-
mp2.y)*(y-mp2.y));
System.out.println("Distance is "+distance);
}
}
//Class ThreeDPoints
class ThreeDPoints extends MyPoint{
//Declare Variables
double z;
//Default Constructor
ThreeDPoints(){
super(0,0);
z = 0;
}
//Parameterized Constructor
ThreeDPoints(double x, double y, double z){
super(x,y);
this.z = z;
}
//Distance Method
void distance(double x, double y, double z){
double distance = Math.pow((Math.pow(this.x - x, 2) +
Math.pow(this.y - y, 2) + Math.pow(this.z - z, 2) * 1.0),
0.5);
System.out.println("Distance is "+distance);
}
72
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//Distance Method
void distance(ThreeDPoints tp2){
double distance = Math.pow((Math.pow(x - tp2.x, 2) +
Math.pow(y - tp2.y, 2) + Math.pow(z - tp2.z, 2) * 1.0),
0.5);
System.out.println("Distance is "+distance);
}
}
//Main Class
class PointDemo{
//Main Method
public static void main(String[] args) {
ThreeDPoints tp1 = new ThreeDPoints();
ThreeDPoints tp2 = new ThreeDPoints(10,30,25.5);
tp1.distance(1,1,1);
tp1.distance(tp2);
}
}
Output:
73
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-11
import java.util.*;
//Main class
class stringLength{
public static void main(String args[]){
//Declare Variables
int i=0;
String str;
Scanner sc = new Scanner(System.in);
//Get String
System.out.println("Enter the string");
str=sc.nextLine();
char ch[]=str.toCharArray();
for(char c : ch){
i++;
}
System.out.println("Length of the string = "+i);
}
}
Output:
74
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
import java.util.Scanner;
//Main class
class StringPalindrome{
public static void main(String[ ] arg){
//Declare Variables
String str, rev = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string:");
str = sc.nextLine();
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}
Output:
75
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
3. WAP to accept a string and display all the vowels present in the word.
import java.util.Scanner;
//Main class
class stringVowels{
public static void main(String[ ] arg){
//Declare Variables
String s;
char ch;
int i=0;
Scanner sc=new Scanner(System.in);
//Get String
System.out.print("Enter a string : ");
s=sc.nextLine();
System.out.println("Vowels in a string are:");
for(int j=0;j<s.length();j++){
ch=s.charAt(j);
switch(ch){
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' :i=1;
System.out.println(ch);
}
}
if(i==0)
System.out.println("There are no vowels in a string");
}
}
76
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
4. WAP that prompts the user to enter a decimal number and displays the number in a
fraction.
Hint: Read the decimal number as a string, extract the integer part and fractional part from
the string.
import java.util.*;
import java.lang.Math;
//CLass StringFraction
class StringFraction{
//Declare Variables
String strnum;
int count;
int number;
int exponent;
int numerator;
int denominator;
Scanner sc = new Scanner(System.in);
void getStringNumber(){
System.out.print("Enter number as string : ");
strnum = sc.next();
}
77
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
void convert(){
for(int i = 0; i < strnum.length() ; i++){
if(strnum.charAt(i) == '.'){
count = strnum.length() - (i+1);
break;
}
}
number = (int)(Double.parseDouble(strnum) *
Math.pow(10,count));
exponent = (int)Math.pow(10,count);
System.out.println("Number : "+number);
//Getting GCD
int gcd = 1, flag = 0;
for(int i = 2; i<=number || i<=exponent; i++){
for(int j = 2; j < i; j++){
if(i % j == 0)
flag = 1;
}
if(flag == 0 && number % i == 0 && exponent % i == 0){
gcd = gcd * i;
}
flag = 0;
}
//Actual Fraction
numerator = number / gcd;
denominator = exponent / gcd;
System.out.println("Fraction : " + numerator + "/" +
denominator);
}
}
//Main Class
class StringFractionDemo{
//Main Method
public static void main(String[] args) {
StringFraction sf = new StringFraction();
sf.getStringNumber();
sf.convert();
}
}
78
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
79
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-12
1. WAP that prompts the user to enter 5 numbers, stores them in an ArrayList, and displays
them in increasing order.
import java.util.Scanner;
import java.util.ArrayList;
class Program1 {
80
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.ArrayList;
class Program2 {
public static void main(String[] args) {
list.add("Delhi");
list.add("Mumbai");
list.add("Bangalore");
list.add("Hyderabad");
list.add("Ahmedabad");
System.out.println(list);
}
}
81
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.ArrayList;
class Program3 {
public static void main(String[] args) {
list.add("Aarav");
list.add("Kabir");
list.add("Vivaan");
list.add("Ayaan");
list.add("Aditya");
System.out.println(list);
82
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
83
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-13
1. WAP to develop a simple command-line calculator which takes operand and operator as a
command-line argument, here program terminates if any operand is nonnumeric. Add
exception handler to achieve the exception handling with nonnumeric operand and display a
message that informs the user of the wrong operand type before exiting.
class Program1 {
public static void main(String args[]) {
int result = 0;
try {
//Scan operator and operand from command line argument
int firstNumber = Integer.parseInt(args[0]);
int secondNumber = Integer.parseInt(args[2]);
char operator = args[1].charAt(0);
// perform operation
switch (operator) {
case ('+'):
result = firstNumber + secondNumber;
System.out.println(args[0] + " " + args[1] + "
" + args[2] + " = " + result);
break;
case ('-'):
result = firstNumber - secondNumber;
System.out.println(args[0] + " " + args[1] + "
" + args[2] + " = " + result);
break;
case ('*'):
result = firstNumber * secondNumber;
System.out.println(args[0] + " " + args[1] + "
" + args[2] + " = " + result);
break;
case ('/'):
result = firstNumber / secondNumber;
System.out.println(args[0] + " " + args[1] + "
" + args[2] + " = " + result);
break;
84
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
default:
System.out.print("Invalid Operator selected ");
}
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (NumberFormatException e) {
System.out.println("operand is nonnumeric");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("please enter operand");
}
}
}
Output:
2. WAP to accept N integer numbers from the command line. Raise and handle exceptions for
following cases :
- when a number is ve
- when a number is evenly divisible by 10
- when a number is greater than 1000 and less than 2000
- when a number is greater than 7000
Skip the number if an exception is raised for it, otherwise add it to find total sum.
class Program2 {
public static void main(String args[]) {
85
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
int sum = 0;
try {
// a. - when a number is –ve
if (number < 0) {
throw new Exception("Number is Negative");
}
// add number
sum = sum + number;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
System.out.println("Sum = " + sum);
}
}
86
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
3. WAP to create Account class, which is representing a bank account where we can deposit
and withdraw money. if we want to withdraw money which exceed our bank balance? We
will not be allowed, create InSufficientFundException to handle above situation and display
proper error message.
// custom InSufficientFundException
class InSufficientFundException extends Exception {
InSufficientFundException(String msg) {
super(msg);
}
}
class Account {
double balance = 0;
Account(int bal) {
this.balance = bal;
}
void checkBalance() {
System.out.println("Current balance" + balance);
}
87
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
System.out.println(e.getMessage());
}
}
}
Output:
88
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-14
1. The abstract Vegetable class has three subclasses named Potato, Brinjal and Tomato. Write
a program that demonstrates how to establish this class hierarchy. Declare one instance
variable of type String that indicates the color of a vegetable. Create and display instances
of these objects. Override the toString() method of object to return a string with the name
of vegetable and its color.
//Class Vegetable
abstract class Vegetable{
String color;
Vegetable(String color){
this.color = color;
}
}
//Class Potato
class Potato extends Vegetable{
Potato(){
super("Cream");
}
public String toString(){
return ("Potato : "+color);
}
}
//Class Brinjal
class Brinjal extends Vegetable {
Brinjal(){
super("Purple");
}
public String toString(){
return ("Brinjal : "+color);
}
}
//Class Tomato
class Tomato extends Vegetable{
Tomato(){
super("Red");
}
public String toString(){
return ("Tomato : "+color);
89
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
}
}
//Main Class
class VegetableDemo{
//Main Method
public static void main(String[] args) {
Potato p = new Potato();
Brinjal b = new Brinjal();
Tomato t = new Tomato();
//Display Vegetables with their color
System.out.println(p.toString());
System.out.println(b.toString());
System.out.println(t.toString());
}
}
Output:
interface EventListener{
//performEvent Method
void performEvent();
}
interface MouseListener extends EventListener{
//mouseClicked Method
void mouseClicked();
90
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
//mousePressed Method
void mousePressed();
//mouseReleased Method
void mouseReleased();
//mouseMoved Method
void mouseMoved();
//mouseDragged Method
void mouseDragged();
}
//Main Class
class EventDemo implements MouseListener, KeyListener{
//performEvent Method
public void performEvent(){
System.out.println("Perform Event Method");
}
//mouseClicked Method
public void mouseClicked(){
System.out.println("Mouse Clicked");
}
//mousePressed Method
public void mousePressed(){
System.out.println("Mouse Pressed");
}
//mouseReleased Method
public void mouseReleased(){
System.out.println("Mouse Released");
}
//mouseMoved Method
public void mouseMoved(){
System.out.println("Mouse Moved");
}
//mouseDragged Method
public void mouseDragged(){
System.out.println("Mouse Dragged");
}
//keyPressed Method
public void keyPressed(){
91
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
System.out.println("Key Pressed");
}
//keyReleased Method
public void keyReleased(){
System.out.println("Key Released");
}
//Main Method
public static void main(String[] args) {
EventDemo e = new EventDemo();
e.performEvent();
e.mouseClicked();
e.mousePressed();
e.mouseReleased();
e.mouseMoved();
e.mouseDragged();
e.keyPressed();
e.keyReleased();
}
}
Output:
92
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
3. The Transport interface declares a deliver () method. The abstract class Animal is the super
class of the Tiger, Camel, Deer and Donkey classes. The Transport interface is implemented
by the Camel and Donkey classes. Write a test program that initialize an array of four
Animal objects. If the object implements the Transport interface, the deliver () method is
invoked.
interface Transport{
void deliver();
}
abstract class Animal{
abstract void display();
}
//Tiger Class
class Tiger extends Animal{
void display(){
System.out.println("Tiger Class");
}
}
//Camel Class
class Camel extends Animal implements Transport{
void display(){
System.out.println("Camel Class");
}
public void deliver(){
System.out.println("Camel deliver");
}
}
//Deer Class
class Deer extends Animal{
void display(){
System.out.println("Deer Class");
}
}
//Donkey Class
class Donkey extends Animal implements Transport{
void display(){
System.out.println("Donkey Class");
}
public void deliver(){
93
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
System.out.println("Donkey deliver");
}
}
//Main Class
class AnimalDemo{
public static void main(String[] args) {
Tiger t = new Tiger();
t.display();
Output:
94
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
4. Declare a class called book having author_name as private data member. Extend book class
to have two sub classes called book_publication & paper_publication. Each of these classes
have private member called title. Write a program to show usage of dynamic method
dispatch (dynamic polymorphism) to display book or paper publications of given author.
Use command line arguments for inputting data.
//class Book
class Book{
private String authorName;
Book(String a){
authorName = a;
}
void display(){
System.out.println("Author : "+authorName);
}
}
//class BookPublication
class BookPublication extends Book{
private String title;
BookPublication(String a,String t){
super(a);
title = t;
}
void display(){
System.out.println("Book Title : "+title);
}
}
//class PaperPublication
class PaperPublication extends Book{
private String title;
PaperPublication(String a,String t){
super(a);
title = t;
}
void display(){
System.out.println("Paper Title : "+title);
}
}
95
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Book bs = b;
bs.display();
bs = bp;
bs.display();
bs = pp;
bs.display();
}
}
Output:
96
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-15
1. Write a program to change the color of the circle from red to blue when mouse is clicked on
the circle.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
97
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
98
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
2. Write a program to detect and display the key pressed on the keyboard.
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
99
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
100
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-16
import javafx.application.Application;
import javafx.event.*;
import static javafx.geometry.HPos.RIGHT;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.*;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Login");
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
101
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
actiontarget.setFill(Color.FIREBRICK);
actiontarget.setText("Sign in button pressed");
}
});
102
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import javafx.application.Application;
import javafx.collections.*;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
103
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
104
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
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);
105
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
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);
106
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
107
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-17
1. WAP that counts number of characters, words, and lines in a file. Use exceptions to check
whether the file that is read exists or not.
import java.io.*;
import java.util.*;
filename = sc.nextLine();
BufferedReader buf = new BufferedReader(new FileReader
(filename));
}
}
System.out.println("Character Count : " + char_count);
System.out.println("Word Count : " + word_count);
System.out.println("Line Count : " + line_count);
buf.close();
}
}
108
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
2.
display the no. of replacement.
import java.io.*;
import java.util.*;
109
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
reader.close();
writer.flush();
writer.close();
}
}
Output:
110
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
import java.util.Scanner;
111
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
return 1;
}
// Recursion: Function calling itself!!
output = fact(n - 1) * n;
return output;
}
}
Output:
import java.util.Scanner;
112
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
5. WAP that reads a file and counts the number of occurrences of digit enter by user. Supply
the file name as a command-line argument.
import java.io.*;
import java.util.Scanner;
113
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
}
}
Output:
6. WAP to check that whether the name given from command line is file or not? If it is a file
then print the size of file and if it is directory then it should display the name of all files in
it.
import java.io.*;
114
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
}
}
115
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
116
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-18
1. Define generic class WildCard with method sum which add two generic values. Create class
NumberDemo to demonstrate WildCard class.
import java.util.Arrays;
import java.util.List;
return sum;
}
}
class Program1 {
public static void main(String args[]) {
WildCard w = new WildCard();
// Upper Bounded Integer List
List<Integer> list1 = Arrays.asList(4, 5, 6, 7);
// Double list
List<Double> list2 = Arrays.asList(4.1, 5.1, 6.1);
117
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.Scanner;
class Program2 {
public static void main(String args[]) {
Integer[] list = new Integer[10];
Scanner sc = new Scanner(System.in);
int search;
for (int i = 0; i < list.length; i++) {
System.out.print("list[" + i + "]=");
list[i] = sc.nextInt();
}
System.out.println("Enter value to find");
search = sc.nextInt();
int foundAt = linearSearch(list, search);
if (foundAt == -1) {
System.out.println(search + " isn't present in
array.");
} else {
System.out.println(search + " is present at location "
+ foundAt + ".");
}
}
118
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
119
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-19
1. Define MYPriorityQueue class that extends Priority Queue to implement the Cloneable
interface and implement the clone() method to clone a priority queue.
import java.util.PriorityQueue;
class Program1 {
public static void main(String args[]) {
// MyPriorityQueue object created.
MyPriorityQueue<String> queue = new MyPriorityQueue<>();
queue.offer("1");
queue.offer("2");
queue.offer("3");
System.out.print(queue1);
}
}
120
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
import java.util.Stack;
class Program2 {
public static void main(String args[]) {
if (args.length > 0) {
String exp = args[0];
System.out.println("postfix evaluation: " +
evaluatePostfix(exp));
} else {
System.out.println("Enter expression");
}
}
121
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
else {
int val1 = stack.pop();
int val2 = stack.pop();
switch (c) {
case '+':
stack.push(val2 + val1);
break;
case '-':
stack.push(val2 - val1);
break;
case '/':
stack.push(val2 / val1);
break;
case '*':
stack.push(val2 * val1);
break;
}
}
}
return stack.pop();
}
}
Output:
122
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-20
import java.util.*;
class Program1 {
public static void main(String args[]) {
//set created
Set hs = new HashSet();
// - remove element
hs.remove("Beijing");
System.out.println(hs);
// - Contains element?
System.out.println(hs.contains("Beijing"));
// - addAll
Set hs1 = new HashSet();
hs1.add("Rajkot");
hs1.add("Delhi");
hs1.add("Goa");
System.out.println("The items in set2 are "+hs1);
123
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
hs.addAll(hs1);
System.out.println(hs);
// - removeAll
hs.removeAll(hs1);
System.out.println(hs);
// - retainAll
hs1.add("New York");
hs.retainAll(hs1);
System.out.println(hs);
System.out.println(hs1);
}
}
Output:
import java.util.*;
class Program2 {
124
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
}
}
Output:
125
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Practical-21
1. WAP to create two threads, one thread will print odd numbers and second thread will print
even numbers between 1 to 1000 numbers.
}
}
public Thread2() {
t = new Thread(this);
t.start();
}
126
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Output:
class CI {
int n;
boolean valueSet = false;
127
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
Producer(CI ci) {
this.ci = ci;
new Thread(this, "Producer").start();
}
Consumer(CI ci) {
this.ci = ci;
new Thread(this, "Consumer").start();
}
128
Department of Computer Engineering
Academic Year 2019-20 | Semester-IV
Lab Solution
}
}
Output:
129