0% found this document useful (0 votes)
15 views32 pages

Oop Prac 1-16

The document outlines a series of practical programming exercises using Java, covering various topics such as basic output, solving equations, conversions, BMI calculation, sorting integers, and generating random numbers. Each practical includes a specific aim, the Java program code, and expected outputs. The exercises progressively build on programming concepts and techniques, suitable for learning Java programming.

Uploaded by

anuj
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)
15 views32 pages

Oop Prac 1-16

The document outlines a series of practical programming exercises using Java, covering various topics such as basic output, solving equations, conversions, BMI calculation, sorting integers, and generating random numbers. Each practical includes a specific aim, the Java program code, and expected outputs. The exercises progressively build on programming concepts and techniques, suitable for learning Java programming.

Uploaded by

anuj
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/ 32

PEN:230840131023

PRACTICAL-1
AIM: Write a Program that displays Welcome to Java, Learning Java Now and
Programming is fun.
TOOL/Language: JDK/JAVA
Program :
class Prac1 {
public static void main(String[] args) {
System.out.println("Welcome to Java, Learning Java Now and Programming is fun.");
}
}

Output:

1
PEN:230840131023

PRACTICAL-2
AIM: Write a program that solves the following equation and displays the value
x and y:
(1) 3.4x+50.2y=44.5
(2) 2.1x+.55y=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 )

TOOL/Language: JDK/JAVA

Program:
class Prac2 {
public static void main(String[] args) {
double a1 = 3.4, b1 = 50.2, c1 = 44.5, a2 = 2.1, b2 = .55, c2 = 5.9;

double d = a1 * b2 - b1 * a2;

double x = (c1 * b2 - b1 * c2) / d;


double y = (a1 * c2 - c1 * a2) / d;

System.out.println(x);
System.out.println(y);
}
}

Output:

2
PEN:230840131023

PRACTICAL-3
AIM: Write a program that reads a number in meters, converts it to feet, and
displays the result.
TOOL/Laguage : JDK/Java
Program:
import java.util.*;

class Prac3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter value in meter: ");
double meter = scanner.nextDouble();
double feet = 3.281 * meter;
System.out.println(feet);
}
}

Output:

3
PEN:230840131023

PRACTICAL-4
AIM: 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.
TOOL/Language : JDK/JAVA
Program:
import java.util.*;

class Prac4 {
static double convertInchToMeter(double inch) {
return inch * 0.0254;
}

static double convertPoundToKg(double pound) {


return pound * 0.4536;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter your weight (pound): ");


double weightInPound = scanner.nextDouble();

System.out.print("Enter your height (inch): ");


double heightInInch = scanner.nextDouble();

double weightInKg = convertPoundToKg(weightInPound);


double heightInMeter = convertInchToMeter(heightInInch);

4
PEN:230840131023

double bmi = weightInKg / (heightInMeter * heightInMeter);

System.out.println("Your BMI is: " + bmi);


}
}
Output:

5
PEN:230840131023

PRACTICAL-5

AIM: Write a program that prompts the user to enter three integers and display
the integers in decreasing order.
TOOL/Language : JDK/JAVA
Program:
import java.util.Arrays;
import java.util.Scanner;

class Prac5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter three integers:");

int[] numbers = inputIntegers(scanner);


int[] sortedNumbers = sortDescending(numbers);

displayDescending(sortedNumbers);
}

public static int[] inputIntegers(Scanner scanner) {


int[] numbers = new int[3];
for (int i = 0; i < 3; i++) {
System.out.print("Enter integer " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}
return numbers;
}

public static int[] sortDescending(int[] numbers) {


for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 0; j < numbers.length - i - 1; j++) {
if (numbers[j] < numbers[j + 1]) {
// Swap numbers[j] and numbers[j+1]
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
return numbers;
}

public static void displayDescending(int[] numbers) {


System.out.println("Integers in decreasing order:");

6
PEN:230840131023

for (int i = numbers.length - 1; i >= 0; i--) {


System.out.println(numbers[i]);
}
}
}

Output:

7
PEN:230840131023

PRACTICAL-6
AIM : Write a program that prompts the user to enter a letter and check whether
a letter is a vowel or consonant.
TOOL/Language: JDK/JAVA
Program:
import java.util.Scanner;

class Prac6 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a letter: ");


char letter = scanner.next().toLowerCase().charAt(0);

if (Character.isLetter(letter)) {
if ("aeiou".indexOf(letter) != -1) {
System.out.println(letter + " is a vowel.");
} else {
System.out.println(letter + " is a consonant.");
}
} else {
System.out.println("Invalid input. Please enter a valid letter.");
}

scanner.close();
}
}

OUTPUT:

8
PEN:230840131023

PRACTICAL-7
Aim : Assume a vehicle plate number consists of three uppercase letters
followed by four digits. Write a program to generate a plate number.
TOOL/Language: JDK/JAVA

Program:

import java.util.Random;

class Prac7 {
public static int randomInt() {
Random r = new Random();
return r.nextInt(26);
}

public static int randomChar() {


Random r = new Random();
return (char) (r.nextInt(26) + 'A');
}

public static void main(String[] args) {


String numberPlate = "";

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


numberPlate += randomChar();
}

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


numberPlate += randomInt();
}

System.out.println(numberPlate);
}
}
OUTPUT:

9
PEN:230840131023

PRACTICAL-8

AIM: 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.
TOOL/Language: JDK/JAVA
Program:

import java.util.Scanner;

class Prac8 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
scanner.close();

System.out.print("Smallest factors of " + number + " are: ");


displaySmallestFactors(number);
}

public static void displaySmallestFactors(int number) {


for (int i = 2; i <= number; i++) {
while (number % i == 0) {
System.out.print(i);
number /= i;
if (number > 1) {
System.out.print(",");
}
}
}
}
}
OUTPUT:

10
PEN:230840131023

PRACTICAL-9
AIM: Write a method with 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.
TOOL/Language: JDK/JAVA
Program:
import java.util.Scanner;

class Prac9 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first integer: ");


int num1 = scanner.nextInt();

System.out.print("Enter the second integer: ");


int num2 = scanner.nextInt();

int result = gcd(num1, num2);


System.out.println("The GCD of " + num1 + " and " + num2 + " is: " + result);

scanner.close();
}

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

if (num2 > num1) {


int temp = num1;
num1 = num2;
num2 = temp;
}

while (num2 != 0) {
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}

return num1;
}
}

11
PEN:230840131023

OUTPUT:

12
PEN:230840131023

PRACTICAL-10
AIM: Write a test program that prompts the user to enter ten numbers, invoke a
method to reverse the numbers, display the numbers.

TOOL/Language: JDK/JAVA

Program:

import java.util.Scanner;

class Prac10 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[10];

System.out.println("Enter ten numbers:");

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


System.out.print("Number " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}

reverseNumbers(numbers);

System.out.println("Reversed numbers:");

for (int number : numbers) {


System.out.print(number + " ");
}
}

public static void reverseNumbers(int[] numbers) {


int left = 0;
int right = numbers.length - 1;

while (left < right) {

int temp = numbers[left];


numbers[left] = numbers[right];
numbers[right] = temp;

left++;
right--;
}

13
PEN:230840131023

}
}

OUTPUT:

14
PEN:230840131023

PRACTICAL -11
Aim: 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.
TOOL/Language: JDK/JAVA
Program:
import java.util.Random;

class Prac11 {
public static void main(String[] args) {
int[][] matrix = generateMatrix(6, 6);
displayMatrix(matrix);
boolean isOddRowColumn = checkOddRowsAndColumns(matrix);
System.out.println("Every row and column has an odd number of 1's: " +
isOddRowColumn);
}

public static int[][] generateMatrix(int rows, int cols) {


int[][] matrix = new int[rows][cols];
Random random = new Random();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = random.nextInt(2);
}
}
return matrix;
}

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


System.out.println("Generated Matrix:");
for (int[] row : matrix) {

15
PEN:230840131023

for (int cell : row) {


System.out.print(cell + " ");
}
System.out.println();
}
}

public static boolean checkOddRowsAndColumns(int[][] matrix) {


int rows = matrix.length;
int cols = matrix[0].length;

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


int rowOnesCount = 0;
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 1) {
rowOnesCount++;
}
}
if (rowOnesCount % 2 == 0) {
return false;
}
}

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


int colOnesCount = 0;
for (int i = 0; i < rows; i++) {
if (matrix[i][j] == 1) {
colOnesCount++;
}
}

16
PEN:230840131023

if (colOnesCount % 2 == 0) {
return false;
}
}

return true;
}
}

OUTPUT:

17
PEN:230840131023

PRACTICAL-12
Aim : 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.
TOOL/Language: JDK/JAVA
Program:
import java.util.Random;

class Prac12 {
public static void main(String[] args) {
Random random = new Random(1000);

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


int randomNumber = random.nextInt(49) + 1;
System.out.println(randomNumber);
}
}
}

Output:

18
PEN:230840131023

19
PEN:230840131023

PRACTICAL-13
Aim: 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.
TOOL/Language: JDK/JAVA
Program:
import java.util.*;

// Token class representing the tokens produced by the lexer


class Token {
enum Type { NUMBER, OPERATOR, LPAREN, RPAREN, EOF }
Type type;
String value;

Token(Type type, String value) {


this.type = type;
this.value = value;
}
}

// Lexer class to tokenize the input string


class Lexer {
private String input;
private int position;

Lexer(String input) {
this.input = input;
this.position = 0;
}

20
PEN:230840131023

Token getNextToken() {
if (position >= input.length()) {
return new Token(Token.Type.EOF, "");
}

char currentChar = input.charAt(position);

if (Character.isDigit(currentChar)) {
StringBuilder number = new StringBuilder();
while (position < input.length() && Character.isDigit(input.charAt(position))) {
number.append(input.charAt(position));
position++;
}
return new Token(Token.Type.NUMBER, number.toString());
}

if (currentChar == '+' || currentChar == '-' || currentChar == '*' || currentChar == '/') {


position++;
return new Token(Token.Type.OPERATOR, String.valueOf(currentChar));
}

if (currentChar == '(') {
position++;
return new Token(Token.Type.LPAREN, "(");
}

if (currentChar == ')') {
position++;
return new Token(Token.Type.RPAREN, ")");
}

21
PEN:230840131023

if (currentChar == ' ') {


position++;
return getNextToken();
}

throw new IllegalArgumentException("Invalid character: " + currentChar);


}
}

// Node class representing a node in the Abstract Syntax Tree


abstract class Node {
abstract double evaluate();
}

// Operand node representing a number in the AST


class OperandNode extends Node {
double value;

OperandNode(double value) {
this.value = value;
}

@Override
double evaluate() {
return value;
}
}

// Operator node representing an operator in the AST

22
PEN:230840131023

class OperatorNode extends Node {


char operator;
Node left;
Node right;

OperatorNode(char operator, Node left, Node right) {


this.operator = operator;
this.left = left;
this.right = right;
}

@Override
double evaluate() {
double leftValue = left.evaluate();
double rightValue = right.evaluate();
switch (operator) {
case '+':
return leftValue + rightValue;
case '-':
return leftValue - rightValue;
case '*':
return leftValue * rightValue;
case '/':
if (rightValue == 0) {
throw new ArithmeticException("Division by zero");
}
return leftValue / rightValue;
default:
throw new IllegalArgumentException("Invalid operator: " + operator);
}

23
PEN:230840131023

}
}

// Parser class to generate the Abstract Syntax Tree (AST)


class Parser {
private Lexer lexer;
private Token currentToken;

Parser(Lexer lexer) {
this.lexer = lexer;
this.currentToken = lexer.getNextToken();
}

private void consume(Token.Type expectedType) {


if (currentToken.type == expectedType) {
currentToken = lexer.getNextToken();
} else {
throw new IllegalArgumentException("Unexpected token type: " +
currentToken.type);
}
}

Node factor() {
if (currentToken.type == Token.Type.NUMBER) {
double value = Double.parseDouble(currentToken.value);
consume(Token.Type.NUMBER);
return new OperandNode(value);
} else if (currentToken.type == Token.Type.LPAREN) {
consume(Token.Type.LPAREN);
Node node = expr();
consume(Token.Type.RPAREN);

24
PEN:230840131023

return node;
} else {
throw new IllegalArgumentException("Unexpected token: " + currentToken.value);
}
}

Node term() {
Node node = factor();
while (currentToken.type == Token.Type.OPERATOR &&
(currentToken.value.equals("*") || currentToken.value.equals("/"))) {
Token operatorToken = currentToken;
consume(Token.Type.OPERATOR);
node = new OperatorNode(operatorToken.value.charAt(0), node, factor());
}
return node;
}

Node expr() {
Node node = term();
while (currentToken.type == Token.Type.OPERATOR &&
(currentToken.value.equals("+") || currentToken.value.equals("-"))) {
Token operatorToken = currentToken;
consume(Token.Type.OPERATOR);
node = new OperatorNode(operatorToken.value.charAt(0), node, term());
}
return node;
}

Node parse() {
return expr();
}

25
PEN:230840131023

class Prac13 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an expression: ");
String input = scanner.nextLine();

Lexer lexer = new Lexer(input);


Parser parser = new Parser(lexer);
Node ast = parser.parse();

double result = ast.evaluate();


System.out.println("Result: " + result);
}
}

Output:

26
PEN:230840131023

PRACTICAL-14
Aim: 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 to String() method.
TOOL/Language: JDK/JAVA
Program :
import java.util.ArrayList;
import java.util.Date;

class Loan {
private double amount;

public Loan(double amount) {


this.amount = amount;
}

@Override
public String toString() {
return "Loan amount: " + amount;
}
}

class Circle {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override

27
PEN:230840131023

public String toString() {


return "Circle radius: " + radius;
}
}

class Prac14 {
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<>();

list.add(new Loan(1000.0));
list.add(new Date());
list.add("Hello, World!");
list.add(new Circle(5.0));

for (Object obj : list) {


System.out.println(obj.toString());
}
}
}

Output:

28
PEN:230840131023

PRACTICAL-15
Aim: 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.
TOOL/Language: JDK/JAVA
Program :
import java.util.Scanner;

class BinaryConverter {
public static int bin2Dec(String binaryString) {
if (!binaryString.matches("[01]+")) {
throw new NumberFormatException("Input is not a binary string");
}

int decimal = 0;
int power = 0;
for (int i = binaryString.length() - 1; i >= 0; i--) {
if (binaryString.charAt(i) == '1') {
decimal += Math.pow(2, power);
}
power++;
}
return decimal;
}
}

class Prac15 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

29
PEN:230840131023

System.out.print("Enter binary number: ");


String binaryString = scanner.next();

try {
int decimalNumber = BinaryConverter.bin2Dec(binaryString);
System.out.println("Binary: " + binaryString + " Decimal: " + decimalNumber);
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
}
}

Output:

30
PEN:230840131023

PRACTICAL-16
Aim: 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.
TOOL/Language: JDK/JAVA
Program :
import java.util.Scanner;

class Prac16 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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


String decimalStr = scanner.nextLine();

DecimalFractionConverter converter = new DecimalFractionConverter();

String fraction = converter.convertToFraction(decimalStr);

System.out.println("Fractional representation: " + fraction);


}
}

class DecimalFractionConverter {
public String convertToFraction(String decimalStr) {

String[] parts = decimalStr.split("\\.");


String fractionalPart = parts.length > 1 ? parts[1] : "0";

31
PEN:230840131023

int fractionalLength = fractionalPart.length();


int denominator = (int) Math.pow(10, fractionalLength);

int numerator = Integer.parseInt(parts[0]) * denominator +


Integer.parseInt(fractionalPart);

int gcd = gcd(numerator, denominator);

numerator /= gcd;
denominator /= gcd;

return numerator + "/" + denominator;


}

private int gcd(int a, int b) {


while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}

Output:

32

You might also like