Lesson 2: Java Theory - Data Types and Type Casting
Understanding data types, type casting, and practical applications.
Numeric Data Types in Java
In Java, numeric data types are divided into two categories: integer types and floating point types.
Integer Types
Java provides four integer data types: byte, short, int, and long.
Floating Point Types
Java offers two floating point data types:
-
▶
float— single precision -
▶
double— double precision (has approximately twice the range and precision of float)
Guideline: For simplicity and consistency, this course will primarily use int for integer values and double for floating point values.
Numeric Types: Ranges and Memory Usage
| Data Type | Value Range | Memory Size |
|---|---|---|
byte |
-128 to 127 | 8 bits (signed) |
short |
-32,768 to 32,767 | 16 bits (signed) |
int |
-2,147,483,648 to 2,147,483,647 | 32 bits (signed) |
long |
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 64 bits (signed) |
float |
±1.4E-45 to ±3.4E+38 | 32 bits (IEEE 754) |
double |
±4.9E-324 to ±1.8E+308 | 64 bits (IEEE 754) |
Type Casting in Java
Type casting is a unary operation that converts a value of one data type into a value of another data type.
Types of Type Casting
Widening (expansion) — casting from a type with a smaller range to a type with a larger range.
In Java, widening is performed automatically (implicitly).
Narrowing — casting from a type with a larger range to a type with a smaller range.
In Java, narrowing must be done explicitly by the programmer.
Syntax for Type Casting:
(DataType)variableName
(DataType)value
Examples
Casting double to int (narrowing):
System.out.println((int)1.7); // Outputs: 1
Note: The fractional part is truncated when casting double to int.
Casting int to double (widening):
System.out.println((double)1 / 2); // Outputs: 0.5
Important Warning: Be cautious with type casting, as data loss may lead to inaccurate results.
double d = 4.5;
int i = (int)d; // i = 4, but d remains 4.5
Type casting does not modify the original variable's value.
Boolean Data Type
The boolean data type is used to declare variables with values true or false.
Example of boolean variable declaration:
boolean lightsOn = true;
boolean isComplete = false;
The literals true and false are reserved words and cannot be used as identifiers in your program.
Relational Operators (Comparison Operators)
Java provides six relational operators to compare two values:
| Java Operator | Mathematical Symbol | Operator Name | Example (radius = 5) | Result |
|---|---|---|---|---|
< |
< | Less than | radius < 0 |
false |
<= |
≤ | Less than or equal to | radius <= 0 |
false |
> |
> | Greater than | radius > 0 |
true |
>= |
≥ | Greater than or equal to | radius >= 0 |
true |
== |
= | Equal to | radius == 0 |
false |
!= |
≠ | Not equal to | radius != 0 |
true |
Important Warning!
- ▶ The equality operator consists of two equal signs (==), not one (=). A single equal sign (=) is used for assignment.
-
▶
The result of a comparison is always a boolean value (
trueorfalse).
Example of comparison:
double radius = 1;
System.out.println(radius > 0); // Outputs: true
Laboratory Works
Laboratory Work: Loan Payment Calculator
[File name and class name: L2Lab1.java]
Problem Statement: Write a program that calculates loan payments (applicable to mortgages, auto loans, educational loans, etc.).
The program must meet the following requirements:
- ▶ Allow the user to input the annual interest rate (in percent), loan amount (in rubles), and loan term (in years)
- ▶ Compute and display the monthly payment and the total cost of the loan:
- monthly payment is computed as
loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * MONTHS_PER_YEAR))- total cost is computed as
monthlyPayment * numberOfYears * MONTHS_PER_YEAR - ▶ Use the standard annuity formula for calculations
Expected Output:
User Input: Enter annual interest rate (%): 6.5 Enter loan term (years): 15 Enter loan amount (rubles): 2000000 Program Output: Monthly payment: 17140.12 rubles Total loan cost: 3085221.60 rubles
How to Run Java files (even if there is no java extension) :
- Save the file (filename.java).
- Compile:
bash (terminal):
javac filename.java
- Run:
bash (terminal):
java filename
Complete Solution Code:
/* Laboratory Work: Loan Payment Calculator */
import java.util.Scanner;
public class L2Lab1 {
public static void main(String[] args) {
// Constant: months per year
final int MONTHS_PER_YEAR = 12;
// Create a Scanner for user input
Scanner scanner = ...
// Step 1: get annual interest rate
System.out.print("Enter annual interest rate (%): ");
double annualInterestRate = scanner.nextDouble();
// Convert to monthly fraction
double monthlyInterestRate = annualInterestRate / 12 / 100;
// Step 2: get loan term in years
System.out.print("Enter loan term (years): ");
int numberOfYears = scanner.nextInt();
// Step 3: get loan amount
System.out.print("Enter loan amount (rubles): ");
double loanAmount = ...
// Step 4.1: calculate monthly payment
double monthlyPayment = ...
// Step 4.2: calculate total payment
double totalPayment = ...
// Round in borrower's favor (down to nearest kopeck)
monthlyPayment = Math.floor(monthlyPayment * 100) / 100;
totalPayment = Math.floor(totalPayment * 100) / 100;
// Step 5: display results
System.out.printf(...
System.out.printf(...
// Close the scanner
...
}
}
Laboratory Work: Calculating Taxi Fare
[File name and class name: L2Lab2.java]
Problem Statement: Write a program that calculates the cost of a taxi ride based on odometer readings and a fixed rate (8 rubles 50 kopecks per kilometer).
The program must:
- ▶ Prompt the user for initial and final odometer readings
- ▶ Calculate the distance traveled
- ▶ Compute the trip cost using the given rate and display the result
Expected Output:
Input: Enter the initial odometer reading: 13505 Enter the final odometer reading: 13810 Output: You traveled 305 km. At a rate of 8 rubles 50 kopecks per km, the fare is 2592 rubles 50 kopecks.
How to Run Java files (even if there is no java extension) :
- Save the file (filename.java).
- Compile:
- Run:
bash (terminal):
javac filename.java
bash (terminal):
java filename
Complete Solution Code:
/* Laboratory Work: Calculating Taxi Fare */
import java.util.Scanner;
public class L2Lab2 {
public static void main(String[] args) {
// Constant: rate per kilometer (8 rubles 50 kopecks)
final double RATE_PER_KM = ...
// Create a scanner object for user input
Scanner scanner = ...
// Step 1: display the program header
System.out.println("TAXI FARE CALCULATOR");
// Step 2: prompt for initial odometer reading
System.out.print("Enter the initial odometer reading: ");
int startOdometer = ...
// Step 3: prompt for final odometer reading
System.out.print("Enter the final odometer reading: ");
...
// Step 4: calculate the distance traveled
int distance = ...
// Step 5: compute the trip cost
double totalCost = ...
// Step 6: display the result
System.out.println("You traveled " + distance + " km. At a rate of 8 rubles 50 kopecks per km,");
System.out.printf("the fare is %.0f rubles %.0f kopecks.%n",
Math.floor(totalCost), (totalCost - Math.floor(totalCost)) * 100);
// Close the scanner
...
}
}
Lab 3: Boolean Type and Double Inequality
Objective: Check if double inequality A < B < C is true for three given integers. Note: Do not use the conditional operator.
[File name and class name: L2Lab3.java]
Expected output:
Input three numbers, please 5 7 10 The result: true --- Input three numbers, please 8 7 10 The result: false
Algorithm:
- Open Visual Studio Code.
- Create a new file named
L2Lab3.java. - Import the Scanner library:
import java.util.Scanner; - Inside the main function, ask user to input three numbers.
- Create a Scanner object:
Scanner scanner = new Scanner(System.in); - Read three integers using Scanner methods.
- Use logical operator
&&to check double inequality:a < b && b < c - Output the result directly without using conditional operator.
How to Run Java files (even if there is no java extension) :
- Save the file (filename.java).
- Compile:
- Run:
bash (terminal):
javac filename.java
bash (terminal):
java filename
Task 1: Compare Sums of Number Pairs
Objective: Four integers are given. Check if sum of first two numbers is greater than sum of next two numbers. Output the result as true or false directly without using conditional operator.
Expected output:
Please, input four integers: 5 7 10 4 5 + 7 > 10 + 4 : false --- Please, input four integers: 8 7 10 2 8 + 7 > 10 + 2 : true
[File name and class name: L2Task1.java]
Lab1 0.5
Lab2 0.5
Lab3 0.5
Task1 0.5