0% found this document useful (0 votes)
18 views24 pages

OOP Practical

The document contains a series of Java programming exercises designed for OOP-1 practicals at GTU. Each program addresses a specific problem, such as displaying messages, solving equations, converting units, calculating BMI, and generating random values. The document includes code snippets and expected outputs for each exercise.

Uploaded by

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

OOP Practical

The document contains a series of Java programming exercises designed for OOP-1 practicals at GTU. Each program addresses a specific problem, such as displaying messages, solving equations, converting units, calculating BMI, and generating random values. The document includes code snippets and expected outputs for each exercise.

Uploaded by

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

OOP-1(3140705) GTU PRACTICALS search

Home

MAR GTU NEW OOP-1 PRACTICALS


5 Program - 01

Write a Program that displays Welcome to Java, Learning Java Now and
Programming is fun.

class Main {

public static void main(String[] args) {

System.out.print("Welcome to Java, ");

System.out.print("Learning Java Now and Programming is fun");

OUTPUT

Program - 02

Write a program that solves the following equation and displays the value x and
y: 1) 3.4 x + 50.2 y = 44.5 2) 2.1 x + .55 y = 5.9(Assume Cramer’ s rule to solve
equation ax + by = e x = ed - bf / ad - bc, cx + dy = f y = af - ec / ad - bc)

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Values from Equestion - 1 :");

System.out.print("Enter value of a : ");

double a = input.nextDouble();

System.out.print("Enter value of b : ");

double b = input.nextDouble();

System.out.print("Enter value of e : ");

double e = input.nextDouble();

System.out.println("Values from Equestion - 2 :");

System.out.print("Enter value of c : ");

double c = input.nextDouble();

System.out.print("Enter value of d : ");


double d = input.nextDouble();

System.out.print("Enter value of f : ");

double f = input.nextDouble();

double x = ((e * d) - (b * f)) / ((a * d) - (b * c));

double y = ((a * f) - (e * c)) / ((a * d) - (b * c));

System.out.print(" X = " + x + " Y = " + y);

OUTPUT

Program - 03

Write a program that reads a number in


meters, converts it to feet, and displays the
result.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter Value in Meters :");

double met = input.nextDouble();

double feet = met * 3.28084;

System.out.print(met + " Meters = " + feet + " Feets");

OUTPUT

Program - 04

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;

class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter Your weight in Pound :");

double pou = input.nextDouble();

System.out.print("Enter Your Height in Inch :");

double inch = input.nextDouble();

double BMI = (pou * 0.45359237) / ((inch * 0.0254) * (inch * 0.0254));

System.out.print(" BMI = " + BMI);

OUTPUT

Program - 05

Write a program that prompts the user to enter three integers and display the
integers in decreasing order.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

int temp;

Scanner input = new Scanner(System.in);

System.out.print("Enter First Integer :");

int a = input.nextInt();

System.out.print("Enter Second Integer :");

int b = input.nextInt();

if (a < b) {

temp = a;

a = b;

b = temp;
}

System.out.print("Enter Third Integer :");

int c = input.nextInt();

if (c > b) {

if (c > a) {

temp = c;

c = b;

b = a;

a = temp;

} else {

temp = c;

c = b;

b = temp;

System.out.print("Decreasing Order :" + a + " " + b + " " + c);

OUTPUT

Program - 06

Write a program that prompts the user to enter a letter and check whether a
letter is a vowel or constant.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

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

char ch = input.next().charAt(0);

switch (Character.toLowerCase(ch)) {

case 'a':

case 'e':

case 'i':
case 'o':

case 'u':

System.out.print(ch + " is vowel");

break;

default:

System.out.print(ch + " is constant");

}
OUTPUT

Program - 07

Assume a vehicle plate number consists of three uppercase letters followed by


four digits.Write a program to generate a plate number.

class Main {

public static void main(String[] args) {

int alpha1 = 'A' + (int)(Math.random() * ('Z' - 'A'));

int alpha2 = 'A' + (int)(Math.random() * ('Z' - 'A'));

int alpha3 = 'A' + (int)(Math.random() * ('Z' - 'A'));

int digit1 = (int)(Math.random() * 10);

int digit2 = (int)(Math.random() * 10);

int digit3 = (int)(Math.random() * 10);

int digit4 = (int)(Math.random() * 10);

System.out.println("" + (char)(alpha1) + ((char)(alpha2)) +

((char)(alpha3)) + digit1 + digit2 + digit3 + digit4);

OUTPUT

Program - 08

Write a program that reads an integer and displays all its smallest factors in
increasing order.For example if input number is 120, the output should be
as follows: 2, 2, 2, 3, 5.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

int div = 2;

Scanner input = new Scanner(System.in);

System.out.print("Enter Integer Value : ");

int number = input.nextInt();

while (number > 1) {

if (number % div == 0) {

System.out.print(div + ",");

number = number / div;

} else {

div++;

OUTPUT

Program - 09

Write a method with the following method header.Public static int gcd(int
num1, int num2) Write a program that prompts the user to enter two integers
and compute the gcd of two integers.

import java.util.Scanner;

class Main {

public static int gcd(int num1, int num2) {

while (num1 != num2) {

if (num1 > num2) {

num1 = num1 - num2;

} else {

num2 = num2 - num1;

}
}

return num1;

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter First Number : ");

int number1 = input.nextInt();

System.out.print("Enter Second Number : ");

int number2 = input.nextInt();

System.out.print("GCD of " + number1 + " and " + number2 + " = " + gcd(number1, number2));

OUTPUT

Program - 10

Write a test program that prompts the user to enter ten numbers, invoke a
method to reverse the numbers, display the numbers.

import java.util.Scanner;

class Main {

public static void reverse(int numbers[]) {

int j = 0, temp;

while (j <= numbers.length / 2) {

temp = numbers[j];

numbers[j] = numbers[numbers.length - 1 - j];

numbers[numbers.length - 1 - j] = temp;

j++;

public static void main(String[] args) {

int i = 0;

int num_array[] = new int[10];

Scanner input = new Scanner(System.in);

for (i = 0; i < 10; i++) {


System.out.print("Enter at Position " + (i + 1) + " : ");

num_array[i] = input.nextInt();

reverse(num_array);

System.out.println("After reversing numbers in an Array :");

for (i = 0; i < 10; i++) {

System.out.println("Value at Position " + (i + 1) + " : " + num_array[i]);

OUTPUT

Program - 11

Write a program that generate 6 * 6 two - dimensional matrix, filled with


0’ s and 1’ s, display the matrix, check every raw and column have an odd
number’ s of 1’ s.

import java.util.Scanner;

class Main {

public static int[][] create_fill_matrix() {

int[][] matrix = new int[6][6];

for (int i = 0; i < 6; i++) {

for (int j = 0; j < 6; j++) {

matrix[i][j] = (int)((Math.random() * 5) % 2);

return matrix;
}

public static void displayMatrix(int[][] matrix) {

System.out.print("\nMatrix Values \n");

for (int i = 0; i < 6; i++) {

for (int j = 0; j < 6; j++) {

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

System.out.println();

public static void main(String[] args) {

int my_matrix[][];

int i, j, cnt;

my_matrix = create_fill_matrix();

displayMatrix(my_matrix);

System.out.println("\nRows Having ODD no of 1s");

for (i = 0; i < 6; i++) {

cnt = 0;

for (j = 0; j < 6; j++) {

if (my_matrix[i][j] == 1) {

cnt++;

if (cnt % 2 != 0) {

System.out.println("Row - " + (i + 1) + " have ODD no of 1s");

System.out.println("\nColumns Having ODD no of 1s");

for (i = 0; i < 6; i++) {

cnt = 0;

for (j = 0; j < 6; j++) {

if (my_matrix[j][i] == 1) {

cnt++;

if (cnt % 2 != 0) {

System.out.println("Column - " + (i + 1) + " have ODD no of 1s");

}
}

OUTPUT

Program - 12

Write a program that creates a Random object with seed 1000 and displays
the first 100 random integers between 1 and 49 using the NextInt(49)
method

import java.util.Random;

class Main {

public static void main(String[] args) {

Random rand = new Random(1000);

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

System.out.format("%3d", rand.nextInt(49));

if ((i + 1) % 20 == 0) {

System.out.println();

OUTPUT
Program - 13

Write a program for calculator to accept an expression as a string in which


the operands and operator are separated by zero or more spaces.For
ex: 3 + 4 and 3 + 4 are

acceptable expressions.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

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

String str = input.nextLine();

String a = str.replaceAll(" ", "");

if (a.length() < 3) {

System.out.println(

"Minimum 2 Opearator and 1 Opearand Required");

System.exit(0);

int result = 0;

int i = 0;

while (a.charAt(i) != '+' && a.charAt(i) != '-' && a.charAt(i) != '*' && a.charAt(i) != '/') {

i++;

switch (a.charAt(i)) {

case '+':

result = Integer.parseInt(a.substring(0, i)) + Integer.parseInt(a.substring(i + 1, a.length()));

break;

case '-':

result = Integer.parseInt(a.substring(0, i)) - Integer.parseInt(a.substring(i + 1, a.length()));


break;

case '*':

result = Integer.parseInt(a.substring(0, i)) * Integer.parseInt(a.substring(i + 1, a.length()));

break;

case '/':

result = Integer.parseInt(a.substring(0, i)) / Integer.parseInt(a.substring(i + 1, a.length()));

break;

System.out.println(a.substring(0, i) + ' ' + a.charAt(i) + ' ' + a.substring(i + 1, a.length()) +

" = " + result);

OUTPUT

Program - 14

Write a program that creates an Array List and adds a Loan object, a Date
object, a string, and a Circle object to the list, and use a loop to display all
elements in the list by invoking the object’ s toString() method.

import java.util.ArrayList;

import java.util.Date;

class Main {

public static void main(String[] args) {

ArrayList < Object > arr_list = new ArrayList < Object > ();

arr_list.add(new Loan(5000.50));

arr_list.add(new Date());

arr_list.add(new String("String class"));

arr_list.add(new Circle(3.45));
for (int i = 0; i < arr_list.size(); i++) {

System.out.println((arr_list.get(i)).toString());

class Circle {

double radius;

Circle(double r) {

this.radius = r;

public String toString() {

return "Circle with Radius " + this.radius;

class Loan {

double amount;

Loan(double amt) {

this.amount = amt;

public String toString() {

return "Loan with Amount " + this.amount;

OUTPUT

Program - 15

Write the bin2Dec(string binary String) method to convert a binary string


into a decimal number.Implement the bin2Dec method to throw a
NumberFormatException if the string is not a binary string.

import java.util.Scanner;

class Main {

public static int bin2Dec(String binaryString) throws NumberFormatException {

int decimal = 0;
int strLength = binaryString.length();

for (int i = 0; i < strLength; i++) {

if (binaryString.charAt(i) < '0' || binaryString.charAt(i) > '1') {

throw new NumberFormatException("The Input String is not Binary");

decimal += (binaryString.charAt(i) - '0') * Math.pow(2, strLength - 1 - i);

return decimal;

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter Binary Value : ");

String str = input.nextLine();

try {

System.out.println("Value = " + bin2Dec(str));

} catch (NumberFormatException e) {

System.out.println(e);

OUTPUT

Program - 16

Write a program 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.Scanner;

import java.math.BigInteger;

class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

Double d;

System.out.print("Enter a decimal number: ");

String[] decimal = input.nextLine().split("[.]");


BigInteger b1 = new BigInteger(decimal[0]);

BigInteger b2 = new BigInteger((decimal[1]));

if (decimal[0].charAt(0) == '-') {

d = b1.doubleValue() - (b2.intValue() / Math.pow(10, decimal[1].length()));

} else {

d = b1.doubleValue() + (b2.intValue() / Math.pow(10, decimal[1].length()));

System.out.println("The fraction number is " + d);

Program - 17

Write a program that displays a tic - tac - toe board.A cell may be X, O, or
empty.What to display at each cell is randomly decided.The X and O are
images in the files X.gif and O.gif.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class HelloWorld extends Application {


public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
GridPane pane = new GridPane();

for (int i = 0; i < 3; i++) {


for (int j = 0; j < 3; j++) {
int n = (int)(Math.random() * 3);
if (n == 0)
pane.add(new ImageView(new Image("x.gif")), j, i);
else if (n == 1)
pane.add(new ImageView(new Image("o.gif")), j, i);
else
continue;
}
}
stage.setTitle("tic-tac-toe");
stage.setScene(new Scene(pane, 300, 400));
stage.show();
}
}

Program - 18

Write a program that moves a circle up, down, left or right using arrow keys.

import javafx.application.Application;
import javafx.scene.Scene;

import javafx.scene.shape.Circle;

import javafx.scene.layout.Pane;

import javafx.geometry.Insets;

import javafx.stage.Stage;

class Main {

@Override

public void start(Stage primaryStage) {

Pane pane = new Pane();

pane.setPadding(new Insets(30, 30, 30, 30));

Circle circle = new Circle(30, 30, 30);

pane.getChildren().add(circle);

pane.setOnKeyPressed(e - > {

switch (e.getCode()) {

case UP:

circle.setCenterY(circle.getCenterY() >

circle.getRadius() ? circle.getCenterY() - 15 :

circle.getCenterY());

break;

case DOWN:

circle.setCenterY(circle.getCenterY() <

pane.getHeight() - circle.getRadius() ?

circle.getCenterY() + 15 : circle.getCenterY());

break;

case LEFT:

circle.setCenterX(circle.getCenterX() >

circle.getRadius() ? circle.getCenterX() - 15 :

circle.getCenterX());

break;

case RIGHT:

circle.setCenterX(circle.getCenterX() <

pane.getWidth() - circle.getRadius() ?

circle.getCenterX() + 15 : circle.getCenterX());

});

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

primaryStage.setTitle("arrow keys ");


primaryStage.setScene(scene);

primaryStage.show();

pane.requestFocus();

Program - 19

Write a program that displays the color of a circle as red when the mouse
button is pressed and as blue when the mouse button is released.

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.layout.StackPane;

import javafx.scene.paint.Color;

import javafx.scene.shape.Circle;

import javafx.stage.Stage;

class Main {

@Override

public void start(Stage primaryStage) {

double width = 450;

double height = 450;

Circle c = new Circle(width / 2, height / 2, Math.min


(width, height) / 10, Color.BLUE);

c.setStroke(Color.WHITE);

StackPane pane = new StackPane(c);

primaryStage.setScene(new Scene(pane, width, height));

pane.setOnMousePressed(e - > c.setFill(Color.RED));

pane.setOnMouseReleased(e - > c.setFill(Color.BLUE));

primaryStage.setTitle("Click circle..");

primaryStage.show();

public static void main(String[] args) {

Application.launch(args);

Program - 20

Write a GUI program that use button to move the message to the left and
right and use the radio button to change the color
for the message displayed.

import javafx.application.Application;

import javafx.stage.Stage;

import javafx.scene.Scene;

import javafx.geometry.Pos;

import javafx.scene.control.Button;

import javafx.scene.layout.HBox;

import javafx.scene.layout.Pane;

import javafx.scene.layout.BorderPane;

import javafx.scene.text.Text;

import javafx.scene.control.RadioButton;

import javafx.scene.control.ToggleGroup;

import javafx.scene.paint.Color;

class Main {

protected Text text = new Text(50, 50, "CodingKick");

@Override

public void start(Stage primaryStage) {

HBox paneForButtons = new HBox(20);

Button btLeft = new Button("<=");

Button btRight = new Button("=>");

paneForButtons.getChildren().addAll(btLeft, btRight);

paneForButtons.setAlignment(Pos.CENTER);

BorderPane pane = new BorderPane();

pane.setBottom(paneForButtons);

HBox paneForRadioButtons = new HBox(20);

RadioButton rbRed = new RadioButton("Red");

RadioButton rbYellow = new RadioButton("Yellow");

RadioButton rbBlack = new RadioButton("Black");

RadioButton rbOrange = new RadioButton("Orange");

RadioButton rbGreen = new RadioButton("Green");

paneForRadioButtons.getChildren().addAll(rbRed, rbYellow,

rbBlack, rbOrange, rbGreen);

ToggleGroup group = new ToggleGroup();

rbRed.setToggleGroup(group);

rbYellow.setToggleGroup(group);

rbBlack.setToggleGroup(group);
rbOrange.setToggleGroup(group);

rbGreen.setToggleGroup(group);

Pane paneForText = new Pane();

paneForText.setStyle("-fx-border-color: black");

paneForText.getChildren().add(text);

pane.setCenter(paneForText);

pane.setTop(paneForRadioButtons);

btLeft.setOnAction(e - > text.setX(text.getX() - 10));

btRight.setOnAction(e - > text.setX(text.getX() + 10));

rbRed.setOnAction(e - > {

if (rbRed.isSelected()) {

text.setFill(Color.RED);

});

rbYellow.setOnAction(e - > {

if (rbYellow.isSelected()) {

text.setFill(Color.YELLOW);

});

rbBlack.setOnAction(e - > {

if (rbBlack.isSelected()) {

text.setFill(Color.BLACK);

});

rbOrange.setOnAction(e - > {

if (rbOrange.isSelected()) {

text.setFill(Color.ORANGE);

});

rbGreen.setOnAction(e - > {

if (rbGreen.isSelected()) {

text.setFill(Color.GREEN);

});
Scene scene = new Scene(pane, 450, 150);

primaryStage.setTitle("GUI program");

primaryStage.setScene(scene);

primaryStage.show();

Program - 21

Write a program to create a file name 123. txt, if it does not exist.Append a
new data to it if it already exists.Write 150 integers created randomly into
the file using Text I / O.Integers are separated by space.

import java.io.*;

import java.util.Scanner;

class Main {

public static void main(String[] args) {

try (

PrintWriter pw = new PrintWriter(new FileOutputStream(new File("123.txt"), true));

){

for (int i = 0; i < 150; i++) {

pw.print((int)(Math.random() * 150) + " ");

} catch (FileNotFoundException fnfe) {

System.out.println("Cannot create the file.");

fnfe.printStackTrace();

Program - 22

Write a recursive method that returns the smallest integer in an array.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter five integers: ");

int[] list = new int[5];

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

list[i] = input.nextInt();
}

System.out.println("The smallest element is " + min(list));

public static int min(int[] list) {

int min = list[list.length - 1];

int index = list.length - 1;

return min(list, index, min);

private static int min(int[] list, int index, int min) {

if (index < 0) {

return min;

} else if (list[index] < min) {

return min(list, index - 1, list[index]);

} else {

return min(list, index - 1, min);

Write a test program that prompts the user to enter an integer and display
its product.

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int product = 1;

System.out.print("Enter five integers: ");

int[] list = new int[5];

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

list[i] = input.nextInt();

product *= list[i];

System.out.println("The Product of elements is " + product);

OUTPUT
Program - 23

Write a generic method that returns the minimum elements in a two dimensional
array.

public class Main {

public static void main(String[] args) {

Integer[][] list = new Integer[10][10];

int value = 0;

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

for (int j = 0; j < list[i].length; j++) {


list[i][j] = value++;
}
}

System.out.println("Max = " + max(list));


}

public static <E extends Comparable<E>> E max(E[][] list) {


E max = list[0][0];

for (E[] elements : list) {

for (E element : elements) {

if (element.compareTo(max) > 0) {
max = element;
}
}
}
return max;
}
}

Program - 24

Define MYPriorityQueue class that extends Priority Queue to implement the


Cloneable interface and implement the clone() method to clone a priority
queue.

class Mainpublic static void main(String[] args) throws CloneNotSupportedException {

// Create a string MyPriorityQueue and 4 state names

MyPriorityQueue < String > queue1 = new MyPriorityQueue < > ();

queue1.offer("Oklahoma");

queue1.offer("Indiana");
queue1.offer("Georgia");

queue1.offer("Texas");

// Clone queue1 to queue2

MyPriorityQueue < String > queue2 = queue1.clone();

// Add 2 more state names to queue 1

queue1.offer("New York");

queue1.offer("New Jersey");

// Remove 1 state from queue 2

queue2.remove();

// Display queues

System.out.print("Queue1: ");

while (queue1.size() > 0) {

System.out.print(queue1.remove() + " ");

System.out.println();

System.out.print("Queue2: ");

while (queue2.size() > 0) {

System.out.print(queue2.remove() + " ");

System.out.println();

Program - 25

Write a program that reads words from a text file and displays all the
nonduplicate words in descending order.The text file is passed as a
command -
line argument.import com.sun.javaws.exceptions.InvalidArgumentException;

import java.io.*;

import java.security.InvalidParameterException;

import java.util.Arrays;

import java.util.HashSet;

import java.util.TreeSet;

class Mainpublic static void main(String[] args) throws FileNotFoundException {

if (args.length != 1)

throw new InvalidParameterException("Usage: fullFilePathName");

File file = new File(args[0]);

if (!file.isFile())

throw new FileNotFoundException(file + " is not a file.");

try (BufferedReader in = new BufferedReader(new InputStreamReader


(new FileInputStream(file)), 10000)) {
String inputS;

StringBuilder sb = new StringBuilder(10000);

while ((inputS = in .readLine()) != null)

sb.append(inputS);

String[] words = sb.toString().split("\\s+");

TreeSet < String > ndWords = new TreeSet < > (Arrays.asList(words));

for (String s: ndWords)

System.out.println(s);

} catch (IOException e) {

e.printStackTrace();

System.exit(0);

}
}

G-MAIL: [email protected]

GTU NEW OS PRACTICALS: https://gtunewospracticals.blogspot.com/2020/06/gtu-new-os-practicals.html

Posted 5th March 2020 by GTU NEW STUDY MATERIAL

0 Add a comment

You might also like