We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 353
MASTERING
JAVA
10Q+
solved and commented
exercises
to accelerate your learning
RUHAN CONCEICAOMASTERING JAVA:
100+ Solved and
Commented Exercises
to Accelerate your
Learning
Ruhan Avila da ConceicdoPreface
Welcome to this book where solved and com-
mented Java exercises are presented. In this book,
you will find a collection of over 100 exercises de-
signed to help you improve your programming skills
in this powerful language.
Learning to program involves not only under-
standing theoretical concepts but also applying
those concepts in real-life situations. That's exactly
what you will find in this book: a wide variety of
problems ranging from basic fundamentals to more
complex challenges.
Each exercise is accompanied by a complete
and detailed solution, which not only presents the
source code but also explains the reasoning behind
the approach taken. These comments discuss impor-
tant concepts, provide valuable tips, and help under-
stand how programming logic can be efficiently ap-
plied in problem-solving.As you progress through the exercises, you will be
challenged with tasks involving mathematical for-
mula manipulation, strings, conditionals, loops, vec-
tor manipulation, matrices, and much more.
The main goal of this book is to provide a prac-
tical and comprehensive resource for programmers
seeking improvement. Whether you are a beginner
in Java looking to solidify your knowledge or an
experienced programmer wishing to deepen your
expertise, these exercises will serve as an excellent
study guide and reference. This book is also suitable
for teachers who would like to have a rich collection
of solved Programming Logic exercises to create ex-
ercises and questions for their students.
In several exercises, multiple solutions are pre-
sented for the same proposed problem, involving
different strategies and techniques.
Enjoy this learning journey and dive into the
solved and commented Java exercises. Prepare your-
self for stimulating challenges, creative solutions,
and a unique opportunity to enhance your program-
ming skills.This book was written using artificial intelligence
tools in content creation, but all materials have been
reviewed and edited by the author to deliver a final
high-quality product.
Happy reading, happy studying, and have fun ex-
ploring the fascinating world of Java programming
Ruhan Avila da Conceicao.Summary
Brief Introduction to Java
Introduction to Exercises
Mathematical Formulas
Conditionals
Repeat Loops
Arrays
Strings
Matrices
Recursive Functions
Extra Exercises
Complete List of Exercises
Additional Content
About the AuthorBrief Introduction
to Java
Java is a widely-used programming language ex-
pressly designed for use in the distributed environ-
ment of the internet. It was designed to have the
"look and feel" of the C++ language, but it is simpler
to use than C++ and enforces an object-oriented pro-
gramming model.
Here are some key characteristics of Java:
Object-Oriented: In Java, everything is an Object.
Java can be easily extended since it is based on the
Object model.
Platform Independent: Unlike many other pro-
gramming languages including C and C++, when
Java is compiled, it is not compiled into platform-
specific machine code, but into platform-indepen-
dent byte code. This byte code is distributed over theweb and interpreted by the Virtual Machine (JVM)
on whichever platform it is being run on.
Simple: Java is designed to be easy to learn. If you
understand the basic concept of OOP, Java would be
easy to master.
Secure: With Java's secure feature, it enables to
develop virus-free, tamper-free systems. Authenti-
cation techniques are based on public-key encryp-
tion.
Architectural-Neutral: Java compiler generates
an architecture-neutral object file format, which
makes the compiled code executable on many pro-
cessors, with the presence of a Java runtime system.
Portable: Being architectural-neutral and having
no implementation dependent aspects of the specifi-
cation makes Java portable.
Robust: Java makes an effort to eliminate error-
prone situations by emphasizing mainly on com-
pile-time error checking and runtime checking.
Multithreaded: With Java's multithreaded fea-
ture, it is possible to write programs that can per-
form many tasks simultaneously.Java was developed by James Gosling, a develop-
ment leader in sun microsystem. Sun Microsystems
in 1995. It was later acquired by Oracle Corporation.
Java is used in a wide variety of computing plat-
forms from embedded devices and mobile phones to
enterprise servers and supercomputers.
A basic structure of a Java program is shown
below:
public class Main {
public static void main(String|] args) {
System.out.println("Hello, World!");
}
}
This is a simple program that prints "Hello,
World!" to the console. In the above example, public
class Main is the declaration of the class. Java pro-
grams are made up of classes. The main method is
the entry point of the program and System. out.print-
In("Hello, World!"); is the line which prints the text
"Hello, World!" to the console.Variables
In Java, a variable is a name given to a memory
location. It's called a variable because the informa-
tion stored in the memory location may change dur-
ing the execution of the program. Each variable in
Java has a specific data type, which determines the
size and layout of the variable's memory, the range
of values that can be stored within that memory,
and the set of operations that can be applied to the
variable.
There are three types of variables in Java:
Local Variables: A variable defined within a
method is called a local variable. The variable will be
destroyed once the method has completed.
Instance Variables (Non-static Fields): Instance
variables are non-static and are declared in a class
outside any method, constructor or block. They are
created when an object is created with the use of
the keyword ‘new' and destroyed when the object is
destroyed.
Class Variables (Static Fields): A variable that is
declared as static is called a static variable. It cannotbe local. There would only be one copy of each class
variable per class, regardless of how many objects
are created from it.
Java variable types are further divided into two
groups:
Primitive Data Types: The primitive data types
include boolean, char, byte, short, int, long, float and
double.
Non-primitive Data Types (Reference/Object
Data Types): Reference variables are created using
defined constructors of the classes. They are used to
access objects. These variables are declared to be of
a specific type that cannot be changed. Class objects
and various type of array variables come under ref-
erence data type.
Here is an example of how to declare variables in
Java:
public class Main {
public static void main(String[] args) {
String name = "John"; // String variable
int age = 20; // integer variable
float mark = 85.5f; // float variablechar grade='A'; // character variable
boolean passed = true; // boolean variable
System.out.println(name);
System.out.println(age);
System.out.println(mark);
System.out.println(grade);
System.out.println(passed);
In this program, name, age, mark, grade and passed are
variables. String is a non-primitive data type whereas int,
float, char and boolean are primitive data types.
Primitive Data Types
byte: The byte data type is an 8-bit signed two's
complement integer. It has a minimum value of -128
and a maximum value of 127 (inclusive). The byte
data type can be useful for saving memory in large
arrays.
short: The short data type is a 16-bit signed two's
complement integer. It has a minimum value of
-32,768 and a maximum value of 32,767 (inclusive).int: By default, the int data type is a 32-bit signed
two's complement integer, which has a minimum
value of -(231) and a maximum value of 231-1.
long: The long data type is a 64-bit two's comple-
ment integer. The signed long has a minimum value
of -(263) and a maximum value of 263-1.
float: The float data type is a single-precision 32-
bit IEEE 754 floating point. Use a float (instead of
double) if you need to save memory in large arrays of
floating point numbers.
double: The double data type is a double-precision
64-bit IEEE 754 floating point. For decimal values,
this data type is generally the default choice.
boolean: The boolean data type has only two pos-
sible values: true and false. Use this data type for
simple flags that track true/false conditions.
char: The char data type is a single 16-bit Unicode
character. It has a minimum value of '\u0000' (or 0)
and a maximum value of '\uffff' (or 65,535 inclu-
sive).Non-Primitive Data Types
Non-primitive data types are created by the pro-
grammer and are not defined by Java (except for
String). Non-primitive types can be used to call
methods to perform certain operations, while primi-
tive types cannot. A non-primitive data type can also
be null, while a primitive type cannot.
Examples of non-primitive types include Strings,
Arrays, Classes, Interfaces, and so on. For example,
String in Java is a non-primitive data type.
Printing data
Printing data to the console in Java is straight-
forward. You use System.out.print() or System.out-
-printin(.
Here's a brief explanation of the two methods:
- System.out.print(): This method prints the text
you pass to it, and the cursor remains at the end
of the text in the console.
- System.out.printIn(): This method prints the
text you pass to it, and moves the cursor to thenext line in the console. The ‘Im' in printin stands
for line."
Here are examples of using both methods:
public class Main {
public static void main(String|] args) {
System.out.print('Hello, ");
System.out.print(""World!");
System.out.println("Hello, ");
System.out.println("World!");
}
t
In this program, the System.out.print statements
will output Hello, World! on the same line, while the
System.out.printin statements will output Hello, and
World! on separate lines.
You can print all primitive data types, Strings, and
even objects (which will be printed in a format de-
fined by the class's toString method, unless you over-
ride it).
public class Main {
public static void main(String|] args) {inta= 10;
double b = 20.5;
boolean c = true;
String d = "Hello, World!";
System.out.printIn("The value of a:" + a);
System.out.printIn("The value of b: " + b);
System.out.println("The value of c:" + c);
System.out.printIn("The value of d:" + d);
}
}
In this program, we're declaring variables of
different types, then printing them. The + operator
is used to concatenate the string literal with the
value of the variable.
Reading data
Java provides several ways to read user input. The
Scanner class is one of the most commonly used
ways to get user input from the standard input,
which is typically the keyboard. The Scanner class is
a part of the java.util package, so you'll need to im-
port this package or the class itself before using it.Here is an example of how you can use the Scan-
ner class to read different types of input:
import java-util.Scanner; // import the Scanner class
public class Main {
public static void main(String|] args) {
Scanner scanner = new Scanner(System.in); // create a
Scanner object
System.out.printIn("Enter your name:");
String name = scanner.nextLine(); // read a whole line
of input
System.out.printIn("Enter your age:");
int age = scanner.nextInt(); // read an integer input
System.out.printIn("Enter your GPA:");
double gpa = scanner.nextDouble(); // read a double
input
System.out.printIn("Your name is “ + name);
System.out.printIn("Your age is " + age);
System.out.printIn("Your GPA is " + gpa);
scanner.close(); // it's a good practice to close the
scanner when you're doneIn this program, we first import the Scanner class,
then we create a Scanner object named scanner. We
then use the nextLine(), nextInt(), and nextDouble()
methods to read a String, an integer, and a dou-
ble, respectively. Finally, we close the Scanner object
using scanner.close() to prevent a resource leak.
It's worth noting that when using scanner.nex-
tInt() or similar methods, it does not consume
the last newline character from your input, and
thus this newline is consumed in the next call to
nextLine(). This might not be the desired behavior
for your program, and it's generally a good idea to
add an extra nextLine() call to consume the rest of
the line when reading numeric or boolean data.
import java.util.Scanner;
public class Main {
public static void main(String|] args) {
Scanner scanner = new Scanner(System.in);
System.out.printIn("Enter your age:");int age = scanner.nextInt();
scanner.nextLine(); // consume the leftover newline
System.out.printIn("Enter your name:");
String name = scanner.nextLine();
System.out.printIn("Your name is " + name);
System.out.printIn("Your age is " + age);
scanner.close();
In this program, we use scanner.nextLine() after
scanner.nextInt() to consume the leftover newline.Introduction to
Exercises
If you have acquired this book, you want to start
programming and be logically challenged as soon as
possible, without wanting to read a sermon on the
mount. But it is important to highlight a few things
before we begin.
Even though many exercises may be considered
easy, if you are new to this programming journey, it
is important for you to first try to solve the problem
on your own before looking at the solution. There is
more than one possible solution to the same prob-
lem, and you need to think and develop your own so-
lution. Then, you can compare it with the proposed
one in the book, identify the strengths of each, and
try to learn a little more.
If the exercise is too difficult and you can't solve it,
move on to the next one and try again the next day.Don't immediately jump to the answer, even if you
can't solve it, and definitely don't look at the answer
without even attempting to solve it.
Learning programming logic is not about getting
the answer; it's about the journey you take to arrive
at the answer.
With that being said, the remaining chapters of
this book are divided according to the programming
topics covered in the proposed exercises
e@ Mathematical Formulas (15 exercises)
@ Conditionals (20 exercises)
Loop Structures (25 exercises)
Arrays (10 exercises)
Strings (10 exercises)
Matrices (10 exercises)
Recursive Functions (10 exercises)
+ Extra Exercises at the End
eoeeee#e
You can check out the complete list of exercises at
the end of the book.
From now on, it's all up to you!Mathematical
Formulas
In Java, you can perform a variety of mathemati-
cal operations using operators and the built-in Math
class.
Operators
The basic mathematical operators are:
+ for addition
- for subtraction
* for multiplication
/ for division
% for modulo (remainder of division)
Here is an example:
public class Main {
public static void main(String|] args) {
int x = 10;
int y = 20;int sum = x + y; // addition
int diff = x - y; // subtraction
int product = x* y; // multiplication
int quotient = y / x; // division
int remainder = y % x; // modulo
System.out.printIn("Sum: " + sum);
System.out.println("Difference: " + diff);
System.out.printIn("Product: " + product);
System.out.printIn("Quotient: " + quotient);
System.out.printIn("Remainder: " + remainder);
Math class
Java provides the Math class in the java.util pack-
age which has several methods that can be used for
mathematical operations. These include:
Math.abs(number): returns the absolute value of
the number.
Math.max(number1, number2): returns the maxi-
mum of two numbers.Math.min(number1, number2): returns the mini-
mum of two numbers.
Math.sqrt(number): returns the square root of the
number.
Math.cbrt(number): returns the cube root of the
number.
Math.pow(number, power): returns the value of
the first parameter raised to the second parameter.
Math.round(number): returns the number
rounded to the nearest whole number.
Math.ceil(number): rounds a number UP to the
nearest integer, if necessary, and returns the result.
Math.floor(number): rounds a number DOWN to
the nearest integer, if necessary, and returns the re-
sult.
Here's an example of how to use the Math class:
public class Main {
public static void main(String|] args) {
double x = 10.6;
double y = 20.5;System.out.printIn("Max: " + Math.max(x, y));
System.out.printIn("Min: " + Math.min(x, y));
System.out.printIn("Square root of y: "+ Math.sqrt(y));
System.out.printIn('y to the power of x: + Math-
-pow(y, x);
System.out.printIn("Round of y: " + Math.round(y));
System.out.printIn(Ceiling of x:" + Math.ceil(x));
System.out.printIn("Floor of x: " + Math.floor(x));
}
}
1. Write a program that prompts the
user for two numbers and displays the
addition, subtraction, multiplication,
and division between them.
public class ArithmeticCalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user for the first number
System.out.print("Enter the first number: ");double num1 = scanner.nextDouble();
// Prompt the user for the second number
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
// Perform arithmetic operations
double addition = num1 + num2;
double subtraction = num1 - num2;
double multiplication = num1 * num2;
double division = num1 / num2;
// Display the results
System.out.println("Addition: " + addition);
System.out.println("Subtraction: "+ subtraction);
System.out.println(Multiplication: " + multiplica-
tion);
System.out.println('Division: " + division);
// Close the Scanner
scanner.close();
We begin by importing the java.util.Scanner class,
which allows us to read user input from the console.We define the ArithmeticCalculator class, which
will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user.
We use System.out.print and scanner.nextDou-
ble() to prompt the user to enter the first num-
ber. The entered value is then stored in the variable
num1.
Similarly, we prompt the user to enter the
second number using System.out.print and scan-
ner.nextDouble(), and store the entered value in the
variable num2.
Next, we perform the four arithmetic operations
using the entered numbers: addition (num1 + num2),
subtraction (num1 - num2), multiplication (num1 *
num2), and division (num1 / num2). The results of
these operations are stored in separate variables: ad-
dition, subtraction, multiplication, and division.
Finally, we use System.out.printin to display the
results of the arithmetic operations to the user.
We close the Scanner object to free up system re-
sources using the scanner.close() method.2. Write a program that calculates the
arithmetic mean of two numbers.
import java.util.Scanner;
public class ArithmeticMeanCalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user for the first number
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
// Prompt the user for the second number
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
// Calculate the arithmetic mean
double arithmeticMean = (num1 + num2) / 2;
// Display the arithmetic mean
System.out.printIn(‘Arithmetic Mean: " + arith-
meticMean);
// Close the Scannerscanner.close();
We import the java.util.Scanner class to read user
input.
We define the ArithmeticMeanCalculator class,
which will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user.
We use System.out.print and scanner.nextDou-
ble() to prompt the user to enter the first num-
ber. The entered value is then stored in the variable
num.
Similarly, we prompt the user to enter the
second number using System.out.print and scan-
ner.nextDouble(), and store the entered value in the
variable numz2.
Next, we calculate the arithmetic mean of the two
numbers using the formula: (num1 + num2) / 2, and
store the result in the variable arithmeticMean.
Finally, we use System.out.printin to display the
arithmetic mean to the user.We close the Scanner object to free up system re-
sources using the scanner.close() method.
3. Create a program that calculates
and displays the arithmetic mean of
three grades entered by the user.
import java.util.Scanner;
public class GradeAverageCalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user for the three grades
System.out.print("Enter the first grade: ");
double grade1 = scanner.nextDouble();
System.out.print("Enter the second grade: ");
double grade? = scanner.nextDouble();
System.out.print("Enter the third grade: ");
double grade3 = scanner.nextDouble();
// Calculate the arithmetic mean
double arithmeticMean = (grade1 + grade2 +grade3) / 3;
// Display the arithmetic mean
System.out.printIn(‘Arithmetic Mean of the three
grades: + arithmeticMean);
// Close the Scanner
scanner.close();
We begin by importing the java.util.Scanner class,
which allows us to read user input from the console.
This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the GradeAverageCalculator class,
which will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's grades.
We prompt the user to enter the first grade using
System.out.print and scanner.nextDouble(). The en-
tered value is then stored in the variable gradel.Similarly, we prompt the user to enter the second
grade and store the entered value in the variable
grade2. We then prompt the user to enter the third
grade and store the entered value in the variable
grade3.
Next, we calculate the arithmetic mean of the
three grades using the formula: (gradel + grade2 +
grade3) / 3. We add up the three grades and divide
the sum by 3 to get the average.
Finally, we use System.out.printIn to display the
calculated arithmetic mean to the user.
We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.
4. Write a program that calculates
the geometric mean of three
numbers entered by the user
import java.util.Scanner;
public class GeometricMeanCalculator {public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the three numbers
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter the third number: ");
double num3 = scanner.nextDouble();
// Calculate the geometric mean
double geometricMean = Math.pow(num1 * num2 *
num3, 1.0 / 3.0);
// Display the geometric mean
System.out.println(""Geometric Mean:" + geomet-
ricMean);
// Close the Scanner
scanner.close();We begin by importing the java.util.Scanner class,
which allows us to read user input from the console.
This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the GeometricMeanCalculator
class, which will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the three numbers.
We prompt the user to enter the first number
using System.out.print and scanner.nextDouble().
The entered value is then stored in the variable
num.
Similarly, we prompt the user to enter the second
number and store the entered value in the variable
num2.
We then prompt the user to enter the third num-
ber and store the entered value in the variable num3.
Next, we calculate the geometric mean of the
three numbers using the formula: geometricMean =
cubeRoot(num1 * num2 *num3). We can find the geo-
metric mean by multiplying the three numbers to-gether and then taking the cube root of the product.
We use the Math.pow method to calculate the cube
root, as it's equivalent to raising to the power of 1.0/
3.0.
Finally, we use System.out.printIn to display the
calculated geometric mean to the user.
We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.
5. Write a program that calculates
the BMI of an individual, using the
formula BMI = weight / height?
import java.util.Scanner;
public class BMICalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter weight in kilograms
System.out.print("Enter your weight in kilograms: ");double weight = scanner.nextDouble();
// Prompt the user to enter height in meters
System.out.print("Enter your height in meters: ");
double height = scanner.nextDouble();
// Calculate BMI
double bmi = weight / (height * height),
// Display the BMI
System.out.println(Your BMI is: " + bmi);
// Close the Scanner
scanner.close();
We start by importing the java.util.Scanner class,
which allows us to read user input from the console.
This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the BMICalculator class, which
will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user.We use this object to obtain the user's weight and
height.
We prompt the user to enter their weight in kilo-
grams using System.out.print and scanner.nextDou-
ble(). The entered value is then stored in the variable
weight.
Similarly, we prompt the user to enter their
height in meters and store the entered value in the
variable height.
Next, we calculate the BMI using the formula: BMI
= weight / (height * height). We divide the weight by
the square of the height (height * height) to get the
BMI.
Finally, we use System.out.printIn to display the
calculated BMI to the user.
We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.
When you run this Java program, it will prompt
you to enter your weight and height in kilogramsand meters, respectively. After you provide the
input, it will calculate and display your BMI.
6. Create a program that calculates
and displays the perimeter of a circle,
prompting the user for the radius.
import java.util.Scanner;
public class CirclePerimeterCalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from
the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the radius of the
circle
System.out.print("Enter the radius of the circle:
"5
double radius = scanner.nextDouble();
// Calculate the perimeter of the circle
double perimeter = 2 * Math.PI * radius;
// Display the perimeter of the circleSystem.out.println("Perimeter of the circle: " +
perimeter);
// Close the Scanner
scanner.close();
We start by importing the java.util.Scanner class,
which allows us to read user input from the console.
This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the CirclePerimeterCalculator
class, which will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's input (radius of
the circle).
We prompt the user to enter the radius of the cir-
cle using System.out.print and scanner.nextDouble().
The entered value is then stored in the variable ra-
dius.Next, we calculate the perimeter of the circle
using the formula: perimeter = 2 * a * radius.
We use Math.PI to get the value of mw (approxi-
mately 3.14159) from the Java standard library. The
formula calculates the distance around the circle,
which is the perimeter.
Finally, we use System.out.printIn to display the
calculated perimeter of the circle to the user.
We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.
7. Write a program that calculates
the area of a circle from the radius,
using the formula A = tr?
import java.util.Scanner;
public class CircleAreaCalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from
the userScanner scanner = new Scanner(System.in);
// Prompt the user to enter the radius of the
circle
System.out.print("Enter the radius of the circle:
"5
double radius = scanner.nextDouble();
// Calculate the area of the circle
double area = Math.PI* Math.pow(radius, 2);
// Display the area of the circle
System.out.println("Area of the circle: " + area);
// Close the Scanner
scanner.close();
}
}
We start by importing the java.util.Scanner class,
which allows us to read user input from the console.
This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the CircleAreaCalculator class,
which will contain our main method.Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's input (radius of
the circle).
We prompt the user to enter the radius of the cir-
cle using System.out.print and scanner.nextDouble().
The entered value is then stored in the variable ra-
dius.
Next, we calculate the area of the circle using the
formula: area = m * radius?. We use Math.PI to get
the value of m (approximately 3.14159) from the
Java standard library, and Math.pow to calculate the
square of the radius.
Finally, we use System.out.printIn to display the
calculated area of the circle to the user.
We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.8. Write a program that calculates the delta
of a quadratic equation (A = b? - 4ac).
import java.util.Scanner;
public class QuadraticDeltaCalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from
the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the coefficients a,
b,andc
System.out.print("Enter the coefficient a: ");
double a = scanner.nextDouble();
System.out.print("Enter the coefficient b: ");
double b = scanner.nextDouble();
System.out.print("Enter the coefficient c: ");
double c = scanner.nextDouble();
// Calculate the delta (A) of the quadratic
equationdouble delta = Math.pow(b, 2) -4*a*c;
// Display the delta of the quadratic equation
System.out.println("Delta (A) of the quadratic
equation: " + delta);
// Close the Scanner
scanner.close();
We start by importing the java.util.Scanner class,
which allows us to read user input from the console.
This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the QuadraticDeltaCalculator
class, which will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's input (coefficients
a,b, and c of the quadratic equation).
We prompt the user to enter the coefficients a,
b, and c of the quadratic equation using System.out--print and scanner.nextDouble(). The entered values
are then stored in variables a, b, and c, respectively.
Next, we calculate the delta (A) of the quadratic
equation using the formula: A = b? - 4ac. We use
Math.pow to calculate the square of b, and standard
arithmetic operations to perform the rest of the cal-
culations.
Finally, we use System.out.printin to display the
calculated delta (A) of the quadratic equation to the
user.
We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.
9. Write a program that calculates the
perimeter and area of a rectangle, using
the formulas P = 2(w + 1) and A = wl, where
w is the width and 1 is the length
import java.util.Scanner;
public class RectangleCalculator {public static void main(String|] args) {
// Create a Scanner object to read input from
the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the width of the
rectangle
System.out.print("Enter the width of the rec-
tangle: ");
double width = scanner.nextDouble();
// Prompt the user to enter the length of the
rectangle
System.out.print("Enter the length of the rec-
tangle: ");
double length = scanner.nextDouble();
// Calculate the perimeter of the rectangle
double perimeter = 2 * (width + length);
// Calculate the area of the rectangle
double area = width * length;
// Display the perimeter and area of the
rectangleSystem.out.println("Perimeter of the rectangle:
"+ perimeter);
System.out.println("Area of the rectangle: " +
area);
// Close the Scanner
scanner.close();
We start by importing the java.util.Scanner class,
which allows us to read user input from the console.
This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the RectangleCalculator class,
which will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's input (width and
length of the rectangle).
We prompt the user to enter the width of the rec-
tangle using System.out.print and scanner.nextDou-ble(). The entered value is then stored in the variable
width.
Similarly, we prompt the user to enter the length
of the rectangle and store the entered value in the
variable length.
Next, we calculate the perimeter of the rectangle
using the formula: perimeter = 2 * (width + length).
We add the width and length together, and then
multiply the sum by 2 to get the perimeter.
Similarly, we calculate the area of the rectangle
using the formula: area = width * length. We simply
multiply the width and length together to get the
area.
Finally, we use System.out.printIn to display the
calculated perimeter and area of the rectangle to the
user.
We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.10. Write a program that calculates the
perimeter and area of a triangle, using the
formulas P = a+b+candA=(b*h)/2,
where a, band c are the sides of the triangle
and h is the height relative to the side B.
import java.util.Scanner;
public class TriangleCalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the sides of the trian-
gle
System.out.print("Enter the side a of the triangle: ");
double a = scanner.nextDouble();
System.out.print("Enter the side b of the triangle:
double b = scanner.nextDouble();
System.out.print("Enter the side c of the triangle:double c = scanner.nextDouble();
// Prompt the user to enter the height relative to
side B
System.out.print("Enter the height relative to side B:
%
double h = scanner.nextDouble();
// Calculate the perimeter of the triangle
double perimeter = a +b +c;
// Calculate the area of the triangle
double area = (b* h) / 2;
// Display the perimeter and area of the triangle
System.out.printIn('Perimeter of the triangle: " +
perimeter);
System.out.printIn("Area of the triangle:" + area);
// Close the Scanner
scanner.close();
We start by importing the java.util.Scanner class,
which allows us to read user input from the console.This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the TriangleCalculator class,
which will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's input (sides a, b,c,
and height h of the triangle).
We prompt the user to enter the sides a, b, and
c of the triangle using System.out.print and scan-
ner.nextDouble(). The entered values are then stored
in variables a, b, and.
Next, we prompt the user to enter the height h
relative to side B using System.out.print and scan-
ner.nextDouble(). The entered value is then stored in
the variable h.
Now, we calculate the perimeter of the triangle
using the formula: perimeter = a + b + c. We add the
three sides together to get the perimeter.
Similarly, we calculate the area of the triangle
using the formula: area = (b*h)/ 2. We multiply sideB (b) by the height (h) and then divide the product by
2 to get the area.
Finally, we use System.out.printin to display the
calculated perimeter and area of the triangle to the
user.
We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.
11. Write a program that calculates
the average velocity of an object,
using the formula v = As/At, where v
is the average velocity, As is the space
variation, and At is the time variation
import java.util. Scanner;
public class AverageVelocityCalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);// Prompt the user to enter the space variation
(As)
System.out.print("Enter the space variation (As) in
meters: ");
double spaceVariation = scanner.nextDouble();
// Prompt the user to enter the time variation (At)
System.out.print("Enter the time variation (At) in
seconds: ");
double timeVariation = scanner.nextDouble();
// Calculate the average velocity (v)
double averageVelocity = spaceVariation / timeVari-
ation;
// Display the average velocity
System.out.printIn("Average velocity: " + averageVel-
ocity + " meters per second");
// Close the Scanner
scanner.close();
We start by importing the java.util.Scanner class,
which allows us to read user input from the console.This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the AverageVelocityCalculator
class, which will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's input for the space
variation (As) and the time variation (At).
We prompt the user to enter the space variation
(As) in meters using System.out.print and scan-
ner.nextDouble(). The entered value is then stored
in the variable spaceVariation. Similarly, we prompt
the user to enter the time variation (At) in sec-
onds using System.out.print and scanner.nextDou-
ble(). The entered value is then stored in the variable
timeVariation.
Next, we calculate the average velocity of the ob-
ject using the formula: averageVelocity = As / At. We
divide the space variation (spaceVariation) by the
time variation (timeVariation) to get the average ve-
locity.Finally, we use System.out.printin to display the
calculated average velocity of the object to the user
in meters per second.
We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.
12. Write a program that calculates
the kinetic energy of a moving object,
using the formula E = (mv7’) / 2, where
E is the kinetic energy, m is the mass
of the object, and v is the velocity.
import java.util.Scanner;
public class KineticEnergyCalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the mass of the object
System.out.print("Enter the mass of the object (in
kilograms): ");double mass = scanner.nextDouble();
// Prompt the user to enter the velocity of the
object
System.out.print("Enter the velocity of the object (in
meters per second): ");
double velocity = scanner.nextDouble();
// Calculate the kinetic energy (E) of the object
double kineticEnergy = (mass * Math.pow(velocity,
2))/ 2;
// Display the kinetic energy of the object
System.out.println("Kinetic energy of the object: " +
kKineticEnergy + " joules");
// Close the Scanner
scanner.close();
In this program, we prompt the user to enter the
mass of the object (in kilograms) and the velocity
of the object (in meters per second). The entered
values are then stored in variables mass and veloc-
ity, respectively. We calculate the kinetic energy (E -kineticEnergy) of the object using the formula: kinet-
icEnergy = (mass * velocity\2) / 2. We use Math.pow
to calculate the square of the velocity. The kinetic en-
ergy is a measure of the energy an object possesses
due to its motion.
Finally, we display the calculated kinetic energy
of the object to the user in joules.
13. Write a program that calculates the
work done by a force acting on an object,
using the formula W = F*d, where W is
the work, F is the applied force, and dis
the distance traveled by the object.
import java.util.Scanner;
public class WorkCalculator {
public static void main(String] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the applied force (F) in
newtons
System.out.print("Enter the applied force (F) in new-tons: ");
double force = scanner.nextDouble();
// Prompt the user to enter the distance traveled
(d) by the object in meters
System.out.print("Enter the distance traveled (d) by
the object in meters: ");
double distance = scanner.nextDouble();
// Calculate the work done (T) by the force on the
object
double work = force * distance;
// Display the work done by the force on the object
System.out.printIn("Work done by the force on the
object: "+ work + "joules');
// Close the Scanner
scanner.close();
In this program, we prompt the user to enter
the applied force (F) in newtons and the distance
traveled (d) by the object in meters. The entered val-
ues are then stored in variables force and distance,respectively. We then calculate the work done using
the provided formula W=F*d = work = force * dis-
tance. Finally, we display the calculated work done
by the force on the object to the user in joules.
14. Write a program that reads the x and y
position of two points in the Cartesian plane,
and calculates the distance between them.
import java.util.Scanner;
public class DistanceCalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the x and y coordi-
nates of the first point
System.out.print("Enter the x-coordinate of the first
point: ");
double x1 = scanner.nextDouble();
System.out.print("Enter the y-coordinate of the first
point: ");
double y1 = scanner.nextDouble();// Prompt the user to enter the x and y coordi-
nates of the second point
System.out.print("Enter the x-coordinate of the sec-
ond point: ");
double x2 = scanner.nextDouble();
System.out.print("Enter the y-coordinate of the sec-
ond point: ");
double y2 = scanner.nextDouble();
// Calculate the distance between the two points
using the distance formula
double distance = Math.sqrt(Math.pow(x2 - x1, 2) +
Math.pow(y2 - y1, 2));
// Display the distance between the two points
System.out.println(Distance between the two
points: "+ distance);
// Close the Scanner
scanner.close();
}
}
We start by importing the java.util.Scanner class,
which allows us to read user input from the console.This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the DistanceCalculator class,
which will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's input for the x and
y coordinates of both points.
We prompt the user to enter the x and y coor-
dinates of the first point using System.out.print and
scanner.nextDouble(). The entered values are then
stored in variables x1 and y1.
Similarly, we prompt the user to enter the x and
y coordinates of the second point using System.out-
.print and scanner.nextDouble(). The entered values
are then stored in variables x2 and y2.
Next, we calculate the distance between
the two points using the distance formula:
We use Math.sqrt to calculate the square root of
the sum of the squares of the differences in the x andy coordinates. This formula gives us the Euclidean
distance between two points in a two-dimensional
Cartesian plane.
Finally, we use System.out.printIn to display the
calculated distance between the two points to the
‘user.
15. Create a program that prompts
the user for the radius of a sphere and
calculates and displays its volume.
import java.util.Scanner;
public class SphereVolumeCalculator {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the radius of the
sphere
System.out.print("Enter the radius of the sphere: ");
double radius = scanner.nextDouble();
// Calculate the volume of the sphere
double volume = (4.0 / 3.0) * Math.PI* Math .pow(ra-dius, 3);
// Display the volume of the sphere
System.out.println('Volume of the sphere: " +
volume);
// Close the Scanner
scanner.close();
}
}
In this program, we prompt the user to enter the
radius of the sphere. The entered value is then stored
in the variable radius. We then calculate the volume
of the sphere using the provided formula V = (4/3)
*n*r?, where 7 is the mathematical constant rep-
resenting pi (approximately 3.14159), andr? means
the radius raised to the power of 3. To calculate the
volume, we use the Math.pow() method to raise the
radius to the power of 3, and then we multiply it
with 4.0 / 3.0 and Math.PI, which gives us the vol-
ume of the sphere.
Finally, we display the calculated volume of the
sphere to the user.Conditionals
Before moving on to the exercises and their re-
spective commented solutions, let's make an intro-
duction to some important content for solving the
activities.
Comparison Operators
Comparison operators are used to compare two
values in Java. These operators can be used with
many types of values, including integers, floating-
point numbers, and strings.
All of these operators return a boolean result ei-
ther true or false and are often used in conditional
statements like if, while, do-while, etc.
Here are the comparison operators in Java:
Equal to (==): Checks if two values are equal.
intx=5;
if (x ==5){
System.out.println("x is 5");Not equal to (/=): Checks if two values are not
equal.
intx=5;
if (x!= 10) {
System.out.printIn("x is not 10");
}
Greater than (>): Checks if the left operand is
greater than the right operand.
intx=5;
if(x>3){
System.out.printIn("x is greater than 3");
j
Less than (<): Checks if the left operand is less
than the right operand.
intx=5;
if(x<10){
System.out.printIn("x is less than 10");
}Greater than or equal to (>=): Checks if the left op-
erand is greater than or equal to the right operand.
int x= 5;
if(x>=5){
System.out.println("x is greater than or equal to 5");
}
Less than or equal to (<=): Checks if the left oper-
and is less than or equal to the right operand.
int x= 5;
if(x<=5){
System.out.printIn("x is less than or equal to 5");
}
Logical Operators
In Java, there are three main logical operators: and
(&&), or (||) and not (/). These operators are used to
combine logical expressions and evaluate complex
conditions. Here is a detailed explanation of each
operator:
and operator - &&:The and operator is used to combine two or more
logical expressions. It returns true only if all expres-
sions are true. Otherwise, it returns false. The truth
table for the and operator is as follows:
x y xandy
true true true
true | false | false
false | true | false
false | false | false
intx=5;
if(x>O&&x<10){
System.out.println("x is a positive single digit num-
ber.");
}
or operator:
The or operator is used to combine two or more
logical expressions. It returns True if at least one ofthe expressions is true. Returns False only if all ex-
pressions are false. The truth table for the or opera-
tor is as follows:
x y xory
True | True | True
True | False | True
False | True | True
False | False | False
intx=5;
if(x< Ollx>4)
System.out.println("x is either negative or greater
than 4.");
}
not operator:
The not operator is used to negate a logical expres-
sion. It reverses the value of the expression. If the ex-pression is True, the not operator returns False. If the
expression is False, the not operator returns True.
boolean isCold = false;
if (lisCold) {
System.out.printIn(It's not cold today.");
}
It's important to note that && and // are short-
circuit operators. This means that they only evaluate
the right-hand operand if it's necessary to determine
the result.
For instance, if A and B are two operands, then:
Inthe case ofA &&B, if Ais false, Java won't evalu-
ate B, because the result of the AND operation will be
false regardless of the value of B.
Inthe case of A //B, if A is true, Java won't evaluate
B, because the result of the OR operation will be true
regardless of the value of B.
This feature can be used to prevent errors during
runtime (for example, checking for a null reference
before accessing an object's methods or properties),and can also improve performance by avoiding un-
necessary calculations.
Conditionals in Java
Conditional statements in Java allow your pro-
gram to make decisions based on certain conditions.
Here are the main types of conditional statements in
Java:
if statement: The most basic control flow state-
ment supported by Java is the if statement.
int num = 10;
if (mum > 5) {
System.out.printIn("Number is greater than 5");
}
if-else statement: The if statement alone will exe-
cute a block of code if, and only if, a condition is true.
The if-else statement allows you to execute a block of
code if the condition is true and another block if it is
false.
intnum = 4;if (num > 5){
System.out.println("Number is greater than 5");
}else{
System.out.println("Number is not greater than 5");
}
else if statement: If you have multiple conditions
to check, you can use else if for this.
int num = 25;
if (num > 30) {
System.out.println("Number is greater than 30");
Jelse if (mum > 20) {
System.out.println("Number is greater than 20");
Jelse{
System.out.printIn("Number is not greater than 20");
}
switch statement: A switch statement allows a
variable to be tested for equality against a list of
values. Each value is called a case, and the variable
being switched on is checked for each switch case.
int day = 3;
switch (day) {case 1:
System.out.printIn("Monday");
break;
case 2;
System.out.println("Tuesday");
break;
case 3:
System.out.printIn("Wednesday");
break;
// You can have any number of case statements.
default: // Optional
System.out.printIn("Invalid day");
}
In this switch statement example, if the day vari-
able matches any case, the corresponding code block
will be executed. The break statement is used to ter-
minate the current case and move on to the next one.
If no case matches, the code under default will be
executed.16. Make a program that asks for a
person's age and displays whether
they are of legal age or not.
import java.util. Scanner;
public class LegalAgeChecker {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter their age
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Checkif the person is of legal age (age >= 18)
boolean isLegalAge = age >= 18;
// Display the result based on whether the person
is of legal age or not
if (isLegalAge) {
System.out.printIn("You are of legal age.");
}else {
System.out.printIn("You are not of legal age.");
}// Close the Scanner
scanner.close();
We start by importing the java.util.Scanner class,
which allows us to read user input from the console.
This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the LegalAgeChecker class, which
will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's input for their age.
We prompt the user to enter their age using
System.out.print and scanner.nextInt(). The entered
value is then stored in the variable age.
We use a boolean variable isLegalAge to check if
the person is of legal age. We do this by comparing
the age with the legal age threshold, which is 18 in
this case. If the age is greater than or equal to 18,
then isLegalAge will be true, indicating that the per-son is of legal age. Otherwise, it will be false, indicat-
ing that the person is not of legal age.
Finally, we use an if-else statement to display the
appropriate message based on whether the person is
of legal age or not. If isLegalAge is true, it means the
person is of legal age, so we display "You are of legal
age." If isLegalAge is false, it means the person is not
of legal age, so we display "You are not of legal age."
We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.
17. Write a program that reads two numbers
and tells you which one is bigger.
import java.util. Scanner;
public class BiggerNumberChecker {
public static void main(String] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the first numberSystem.out.print("Enter the first number: ");
double number1 = scanner.nextDouble();
// Prompt the user to enter the second number
System.out.print("Enter the second number: ");
double number2 = scanner.nextDouble();
// Check which number is bigger using an if state-
ment
if (number1 > number2) {
System.out.printIn("The bigger number is: " +
number1);
} else if (mumber2 > number1) {
System.out.printIn("The bigger number is: " +
number2);
}Jelse {
System.out.printIn("Both numbers are equal.");
}
// Close the Scanner
scanner.close();
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. Weuse this object to obtain the user's input for the two
numbers.
We prompt the user to enter the first number
using System.out.print and scanner.nextDouble().
The entered value is then stored in the variable num-
berl.
Similarly, we prompt the user to enter the
second number using System.out.print and scan-
ner.nextDouble(). The entered value is then stored in
the variable number2.
We use an if statement to compare the two num-
bers and determine which one is bigger.
- If number] is greater than number2, the con-
dition number1 > number2 evaluates to true, and
the code inside the if block will be executed. It
means number1 is bigger than number2, so we
display "The bigger number is:" followed by num-
ber1.
- If number2 is greater than number1, the con-
dition number2 > number! evaluates to true, and
the code inside the else if block will be executed.
It means number2 is bigger than number1, so wedisplay "The bigger number is:" followed by num-
ber2.
- If both numbers are equal, none of the above
conditions will be true, and the code inside the
else block will be executed. It means both num-
bers are equal, so we display "Both numbers are
equal."
Another solution
import java.util.Scanner;
public class BiggerNumberChecker {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the first number
System.out.print("Enter the first number: ");
double number1 = scanner.nextDouble();
// Prompt the user to enter the second number
System.out.print("Enter the second number: ");
double number2 = scanner.nextDouble();
// Determine the bigger number using the Math.max() method
double biggerNumber = Math.max(number1,
number2);
// Display the result
System.out.println('The bigger number is: " +
biggerNumber);
// Close the Scanner
scanner.close();
}
}
In this solution, we use the Math.max() method to
determine the bigger number between number1 and
number2. This method returns the larger of the two
arguments. Finally, we display the bigger number to
the user.
18. Write a program that asks the user for
three numbers and displays the largest one.
import java.util. Scanner;
public class LargestNumberFinder {
public static void main(String|] args) {// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the three numbers
System.out.print("Enter the first number: ");
double number1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double number? = scanner.nextDouble();
System.out.print("Enter the third number: ");
double number3 = scanner.nextDouble();
// Find the largest number using if statements
double largestNumber;
if (number1 >= number2 && number1 >= num-
ber3) {
largestNumber = number1;
J else if (mumber2 >= numberl && number? >=
number3) {
largestNumber = number2;
Jelse {
largestNumber = number3;
}
// Display the largest numberSystem.out.printIn(''The largest number is: " +
largestNumber);
// Close the Scanner
scanner.close();
We start by importing the java.util.Scanner class,
which allows us to read user input from the console.
This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the LargestNumberFinder class,
which will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's input for three
numbers.
We prompt the user to enter the three numbers
using System.out.print and scanner.nextDouble().
The entered values are then stored in variables num-
ber1, number2, and number3, respectively.We use if statements to compare the three num-
bers and determine the largest one. Here's how the if
statements work:
- The first if statement checks if number1 is
greater than or equal to both number2 and num-
ber3. If this condition is true, it means that num-
ber1 is the largest number among the three, so
we assign its value to the variable largestNum-
ber.
- The first else if statement checks if number2
is greater than or equal to both number1 and
number3. If this condition is true, it means that
number? is the largest number among the three,
so we assign its value to the variable largest-
Number.
- If neither of the above conditions is true,
it means that number3 is the largest number
among the three, so we assign its value to the
variable largestNumber.
Finally, we use System.out.printIn to display the
largest number to the user.We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.
Another solution
import java.util.Scanner;
public class LargestNumberFinder {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the three numbers
System.out.print("Enter the first number: ");
double number1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double number2 = scanner.nextDouble();
System.out.print("Enter the third number: ");
double number3 = scanner.nextDouble();
// Find the largest number using the Math.max()
method
double largestNumber = Math.max(number1, Math--max(number2, number3));
// Display the largest number
System.out.printIn('The largest number is: " +
largestNumber);
// Close the Scanner
scanner.close();
In this program, we prompt the user to enter
three numbers. The entered values are then stored
in variables number1, number2, and number3, re-
spectively. We use nested Math.max() method calls
to find the largest number among the three. The
Math.max() method returns the larger of the two ar-
guments provided to it, so by nesting three calls, we
can find the largest number among the three
19. Write a program that reads a number
and reports whether it is odd or even.
import java.util.Scanner;public class OddEvenChecker {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Check if the number is odd or even using the
modulo operator (%)
if (number % 2 == 0) {
System.out.printIn(number + " is even.");
Jelse {
System.out.printIn(number + "is odd.");
}
// Close the Scanner
scanner.close();
In this program, we prompt the user to enter
a number using System.out.print and scanner.nex-tInt(). The entered value is then stored in the vari-
able number.
We use the modulo operator % to check if the
number is odd or even. When a number is divided by
2, the remainder will be 0 if it's even and 1 if it's odd.
So, if number % 2 == O, it means the number is even,
and we display "is even." Otherwise, if number % 2 !
= 0, it means the number is odd, and we display "is
odd."
20. Write a program that reads a
number and reports whether it is
positive, negative or zero.
import java.util. Scanner;
public class NumberClassifier {
public static void main(String] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number: ");
double number = scanner.nextDouble();// Check if the number is positive, negative, or
zero using if-else statements
if (number > 0) {
System.out.printIn("The number is positive.");
}else if (number < 0) {
System.out.printIn("The number is negative.");
Jelse {
System.out.printIn("The number is zero.");
}
// Close the Scanner
scanner.close();
In this program, we prompt the user to
enter a number using System.out.print and scan-
ner.nextDouble(). The entered value is then stored in
the variable number.
We use if-else statements to check if the number
is positive, negative, or zero:
- If number is greater than O (number > 0), it
means the number is positive, and we display
"The number is positive."- Ifnumber is less than O (number < 0), it means
the number is negative, and we display "The
number is negative."
- If neither of the above conditions is true, it
means number is equal to 0, and we display "The
number is zero."
21. Make a program that reads the scores of
two tests and reports whether the student
passed (score greater than or equal to 6) or
failed (score less than 6) in each of the tests.
import java.util. Scanner;
public class TestResults {
public static void main(String] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the score of the first
test
System.out.print("Enter the score of the first test: ");
double test1Score = scanner.nextDouble();// Prompt the user to enter the score of the second
test
System.out.print("Enter the score of the second test:
%
double test2Score = scanner.nextDouble();
// Check if the student passed or failed in the first
test
if (test1 Score >= 6) {
System.out.printIn("You passed the first test.");
Jelse {
System.out.printIn("You failed the first test.");
}
// Check if the student passed or failed in the
second test
if (test2Score >= 6) {
System.out.printIn("You passed the second test.");
}Jelse {
System.out.printIn("You failed the second test.");
}
// Close the Scanner
scanner.close();We start by importing the java.util.Scanner class,
which allows us to read user input from the console.
This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the TestResults class, which will
contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's input for the
scores of both tests.
We prompt the user to enter the score of the first
test using System.out.print and scanner.nextDou-
ble(). The entered value is then stored in the variable
test1Score.
Similarly, we prompt the user to enter the score
of the second test using System.out.print and scan-
ner.nextDouble(). The entered value is then stored in
the variable test2Score.
We use if statements to check if the student
passed or failed in each of the tests.- Ifthe test1Score is greater than or equal to 6,
it means the student passed the first test, so we
display "You passed the first test." Otherwise, we
display "You failed the first test."
- Similarly, if the test2Score is greater than or
equal to 6, it means the student passed the sec-
ond test, so we display "You passed the second
test." Otherwise, we display "You failed the sec-
ond test."
22. Make a program that reads the grades of
two tests, calculates the simple arithmetic
mean, and informs whether the student
passed (average greater than or equal
to 6) or failed (average less than 6).
import java.util. Scanner;
public class TestGradesChecker {
public static void main(String|] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);// Prompt the user to enter the grades of two tests
System.out.print("Enter the grade of the first test: ");
double grade1 = scanner.nextDouble();
System.out.print("Enter the grade of the second
test: ");
double grade? = scanner.nextDouble();
// Calculate the average grade
double average = (grade1 + grade2) / 2;
// Determine if the student passed or failed based
on the average
if (average >= 6) {
System.out.printIn("Congratulations! You
passed.");
Jelse {
System.out.println("Sorry, you failed.");
}
// Close the Scanner
scanner.close();We start by importing the java.util.Scanner class,
which allows us to read user input from the console.
This class is part of the Java standard library and
makes it easy to handle user input.
Next, we define the TestGradesChecker class,
which will contain our main method.
Inside the main method, we create a Scanner ob-
ject named scanner to read input from the user. We
use this object to obtain the user's input for the
grades of the two tests.
We prompt the user to enter the grade of the first
test using System.out.print and scanner.nextDou-
ble(). The entered value is then stored in the variable
gradel.
Similarly, we prompt the user to enter the grade
of the second test using System.out.print and scan-
ner.nextDouble(). The entered value is then stored in
the variable grade2.
We calculate the average grade by adding the
grades of the two tests and dividing the sum by 2.
We use an if statement to determine if the stu-
dent passed or failed based on the average. If theaverage is greater than or equal to 6, it means the
student passed, and we display "Congratulations! You
passed." Otherwise, if the average is less than 6, it
means the student failed, and we display "Sorry, you
failed."
We close the Scanner object to free up system re-
sources using the scanner.close() method. This step
is essential to prevent resource leaks and should be
done when we are done using the Scanner.
23. Make a program that reads
three numbers, and informs if their
sum is divisible by 5 or not.
import java.util. Scanner;
public class SumDivisibleByFiveChecker {
public static void main(String] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter three numbers
System.out.print("Enter the first number: ");
int number1 = scanner.nextInt();