In the previous lessons of our Complete Java Course, we learned several important Java basics, including variables, data types, operators, type casting, and taking input from the user. In this lesson, we will put those concepts into practice by solving three beginner-friendly Java programming exercises.
The purpose of this lesson is not only to write programs but also to understand how the concepts we have already learned work together in a real program.
We will build:
-
A basic arithmetic calculator using user input.
-
A program to demonstrate type casting from
floattoint. -
A real-world shopping bill calculator with a 10% discount.
We will also see an important concept related to string concatenation and arithmetic addition, along with the difference between print() and println().
Exercise 1: Basic Arithmetic Calculator
Our first exercise is to create a simple calculator that takes two numbers from the user and calculates:
-
Sum
-
Difference
-
Product
-
Quotient
-
Remainder
To take input from the user, we will use the Scanner class.
Importing Scanner
Before using Scanner, we need to import it:
import java.util.Scanner;
We can then create a Scanner object:
Scanner scan = new Scanner(System.in);
The System.in tells the Scanner that we want to receive input from the standard input, which normally means the keyboard.
Taking Two Numbers as Input
We can ask the user for the first number:
System.out.print("Enter first number: ");
float a = scan.nextFloat();
And then take the second number:
System.out.print("Enter second number: ");
float b = scan.nextFloat();
Here, nextFloat() reads a floating-point number entered by the user.
We are using float rather than int, which allows the program to work with decimal values as well.
Calculating Arithmetic Operations
Once we have the two numbers, we can perform different arithmetic operations.
Addition
System.out.println("Sum: " + (a + b));
The expression:
a + b
performs numerical addition.
For example, if:
a = 10
b = 5
then:
a + b = 15
Difference
System.out.println("Difference: " + (a - b));
This subtracts b from a.
Product
System.out.println("Product: " + (a * b));
This multiplies the two numbers.
Quotient
System.out.println("Quotient: " + (a / b));
This performs division.
Because our variables are float, the result can contain a decimal value.
Remainder
System.out.println("Remainder: " + (a % b));
The % operator returns the remainder of the division.
For example:
10 % 3 = 1
because 3 can be multiplied by 3 to get 9, leaving a remainder of 1.
An important point is that Java's % operator also works with floating-point values such as float and double.
Why Are Parentheses Used in "Sum: " + (a + b)?
This is an important concept from the exercise.
Consider:
System.out.println("Sum: " + a + b);
You might expect Java to first calculate:
a + b
and then attach "Sum: " to the result.
However, Java evaluates the expression from left to right.
Because "Sum: " is a String, the + operator begins performing string concatenation.
For example, if:
a = 10
b = 5
then:
"Sum: " + a + b
can produce:
Sum: 105
rather than:
Sum: 15
To make sure the addition happens first, we use parentheses:
"Sum: " + (a + b)
Now Java calculates:
a + b
first and then concatenates the result with "Sum: ".
Therefore, using parentheses here is important.
print() vs println()
You may have noticed that we used:
System.out.print("Enter first number: ");
instead of:
System.out.println("Enter first number: ");
The difference is that println() moves the cursor to the next line after printing, while print() keeps the cursor on the same line.
For example:
System.out.print("Enter your name: ");
allows the user to enter their input on the same line:
Enter your name: Rohan
With:
System.out.println("Enter your name: ");
the cursor moves to the next line after the message.
For user prompts, print() is often useful because it provides cleaner inline formatting.
Complete Calculator Program
Here is the complete program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number: ");
float a = scan.nextFloat();
System.out.print("Enter second number: ");
float b = scan.nextFloat();
System.out.println("Sum: " + (a + b));
System.out.println("Difference: " + (a - b));
System.out.println("Product: " + (a * b));
System.out.println("Quotient: " + (a / b));
System.out.println("Remainder: " + (a % b));
scan.close();
}
}
This single program combines several concepts we have learned so far: Scanner, variables, float, arithmetic operators, string concatenation, print(), and println().
Exercise 2: Type Casting from Float to Integer
Our second exercise focuses on type casting.
We will ask the user to enter a decimal number, store it in a float, and then explicitly convert that value into an int.
The basic idea is:
float → int
This is an example of narrowing type casting because int cannot store the fractional part of a floating-point value.
Taking a Decimal Number
First, we create our Scanner:
Scanner scan = new Scanner(System.in);
Then we ask the user for a decimal number:
System.out.print("Enter a decimal number: ");
float c = scan.nextFloat();
Suppose the user enters:
25.645
The value stored in c is:
25.645
Explicit Type Casting
Now we want to convert the float into an int.
We can explicitly cast it using:
int d = (int) c;
The (int) tells Java that we explicitly want to convert the value of c into an integer.
If:
c = 25.645
then:
d = 25
The decimal part is removed.
It is important to understand that this is truncation, not rounding.
For example:
25.645 → 25
25.999 → 25
25.1 → 25
Java does not round these values to 26 when converting them to int.
Printing Original and Converted Values
We can display both values:
System.out.println("Original Value: " + c);
System.out.println("Converted Value: " + d);
This makes the effect of type casting easy to observe.
Complete Type Casting Program
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
float c = scan.nextFloat();
int d = (int) c;
System.out.println("Original Value: " + c);
System.out.println("Converted Value: " + d);
scan.close();
}
}
This exercise demonstrates how explicit narrowing conversion can cause loss of the fractional part of a number.
Exercise 3: Real-World Discount Calculator
For our third exercise, we will use Java to solve a simple real-world problem.
Imagine that you are building a shopping application. The application needs to calculate the final amount a customer has to pay after receiving a 10% discount.
We need three main pieces of information:
-
Product price
-
Quantity purchased
-
Discount percentage
The calculation will happen in three steps.
Step 1: Calculate Total Price
First, we calculate the total price:
Total Price = Price × Quantity
In Java:
float totalPrice = price * quantity;
Step 2: Calculate the Discount
The discount is 10% of the total price.
We can calculate it using:
Discount = Total Price × 0.1
In Java:
float discount = totalPrice * 0.1f;
The f suffix indicates that 0.1 is a float literal.
Step 3: Calculate the Final Price
Finally, we subtract the discount from the total price:
Final Price = Total Price − Discount
In Java:
float finalPrice = totalPrice - discount;
Complete Discount Calculator
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter product price: ");
int price = scan.nextInt();
System.out.print("Enter quantity: ");
float quantity = scan.nextFloat();
float totalPrice = price * quantity;
float discount = totalPrice * 0.1f;
float finalPrice = totalPrice - discount;
System.out.println("Total Price: " + totalPrice);
System.out.println("Discount (10%): " + discount);
System.out.println("Final Price: " + finalPrice);
scan.close();
}
}
Understanding the Calculation With an Example
Suppose the user enters:
Enter product price: 500
Enter quantity: 3
The total price will be:
500 × 3 = 1500
The 10% discount will be:
1500 × 0.1 = 150
Therefore, the final price will be:
1500 − 150 = 1350
The output will be approximately:
Total Price: 1500.0
Discount (10%): 150.0
Final Price: 1350.0
This is a simple example of how variables, arithmetic operators, floating-point numbers, and user input can work together to solve a real-world problem.
What Did We Learn?
In this practice lesson, we combined several concepts from the previous Java lessons.
1. Scanner
We used:
Scanner scan = new Scanner(System.in);
to take input from the user.
We also used:
scan.nextFloat();
and:
scan.nextInt();
to read different types of numeric input.
2. Arithmetic Operators
We practiced:
+
-
*
/
%
for addition, subtraction, multiplication, division, and remainder calculations.
3. String Concatenation
We learned why:
"Sum: " + (a + b)
is different from:
"Sum: " + a + b
Parentheses ensure that the numerical addition happens before string concatenation.
4. print() and println()
We used print() when we wanted the user input to remain on the same line as the prompt:
System.out.print("Enter first number: ");
and println() when we wanted to print the result and move to the next line:
System.out.println("Sum: " + (a + b));
5. Type Casting
We practiced explicit narrowing conversion:
int d = (int) c;
When a decimal float is converted to an int, the fractional part is truncated.
6. Real-World Calculations
Finally, we used these concepts together to calculate a shopping bill and a 10% discount.
Conclusion
Practice is one of the most important parts of learning a programming language. Reading about operators, variables, type casting, or Scanner is useful, but writing programs using these concepts helps you understand how they actually work together.
In this lesson, we created three beginner-friendly programs:
-
An arithmetic calculator
-
A float-to-int type casting program
-
A real-world shopping discount calculator
These exercises also introduced some important details that can easily cause mistakes, such as the difference between arithmetic addition and String concatenation, the behavior of print() versus println(), and the loss of the fractional part during narrowing type casting.
As we continue with the Java course, we will use these fundamental concepts repeatedly while building more complex programs and solving problems.
The next lessons will move toward conditional statements, where we will learn how Java programs can make decisions using conditions such as if, else if, and else.