Skip to main content
EDU-MMCS
You are currently using guest access (Log in)

Java Programming Language (Eng)

  1. Home
  2. Courses
  3. Весенний семестр
  4. Java Eng
  5. Basic Programming Language Constructs
  6. Lesson 2. Data Types and Type Casting. Boolean type

Lesson 2. Data Types and Type Casting. Boolean type

Completion requirements
Due: Friday, 20 February 2026, 8:00 AM

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 (true or false).

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) :
  1. Save the file (filename.java).
  2. Compile:

bash (terminal):

javac filename.java

  1. 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 = ...new Scanner(System.in);

        // 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 = ...scanner.nextDouble();

        // Step 4.1: calculate monthly payment
        double monthlyPayment = ...loanAmount * monthlyInterestRate /
                (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * MONTHS_PER_YEAR));

        // Step 4.2: calculate total payment
        double totalPayment = ...monthlyPayment * numberOfYears * MONTHS_PER_YEAR;

        // 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(..."Monthly payment: %.2f rubles%n", monthlyPayment);
        System.out.printf(..."Total loan cost: %.2f rubles%n", totalPayment);

        // Close the scanner
        ...scanner.close();
    }
}

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) :

  1. Save the file (filename.java).
  2. Compile:
  3. 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 = ...8.50;

        // Create a scanner object for user input
        Scanner scanner = ...new Scanner(System.in);

        // 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 = ...scanner.nextInt();

        // Step 3: prompt for final odometer reading
        System.out.print("Enter the final odometer reading: ");
        ...int endOdometer = scanner.nextInt();

        // Step 4: calculate the distance traveled
        int distance = ...endOdometer - startOdometer;

        // Step 5: compute the trip cost
        double totalCost = ...distance * RATE_PER_KM;

        // 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
        ...
        scanner.close();
    }
}

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:

  1. Open Visual Studio Code.
  2. Create a new file named L2Lab3.java.
  3. Import the Scanner library: import java.util.Scanner;
  4. Inside the main function, ask user to input three numbers.
  5. Create a Scanner object: Scanner scanner = new Scanner(System.in);
  6. Read three integers using Scanner methods.
  7. Use logical operator && to check double inequality: a < b && b < c
  8. 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

Complete Solution Code:


/* Lab 3: Check if A < B < C for three integers */
import java.util.Scanner;

public class L2Lab3 {
    public static void main(String[] args) {
        // Create Scanner object for input
        Scanner scanner = new Scanner(System.in);
        
        // Ask user for input
        System.out.println("Input three numbers, please");
        
        // Read three integers
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int c = scanner.nextInt();
        
        // Check double inequality using logical AND operator
        boolean result = (a < b) && (b < c);
        
        // Output the result (no conditional operator used)
        System.out.println("The result: " + result);
        
        // Alternative: output with formatted message
        System.out.printf("Double inequality %d < %d < %d is %b%n", a, b, c, result);
        
        // Close the scanner
        scanner.close();
    }
}

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]

Complete Solution Code:


/* Task 3: Check if (x1 + x2) > (x3 + x4) */
import java.util.Scanner;

public class L1Task1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Please, input four integers:");
        int x1 = scanner.nextInt();
        int x2 = scanner.nextInt();
        int x3 = scanner.nextInt();
        int x4 = scanner.nextInt();
        
        // Calculate sums and compare
        int sum1 = x1 +  x2;
        int sum2 = x3 + x4;
        boolean result = sum1 > sum2;
        
        System.out.println("The result: " + result);
        System.out.printf("(%d+%d) > (%d+%d) = %b%n", x1, x2, x3, x4, result);
        
        scanner.close();
    }
}

Lab1 0.5
Lab2 0.5
Lab3 0.5
Task1 0.5

© 2026 

Some matherisals are taken from labs-org.ru

◄ Lesson 1. Programming on Java in Microsoft Visual Code
Lesson 3. Java Conditional statement IF ►
Skip Navigation
Navigation
  • Home

    • Site pages

      • My courses

      • Tags

    • My courses

    • Courses

      • Весенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

        • МО_4курс

        • KP

        • АБМ1_ИИБ_25-26

        • Java Eng

          • Lesson 0. Introduction

          • Basic Programming Language Constructs

            • AssignmentLesson 1. Programming on Java in Microsoft Visual ...

            • AssignmentLesson 2. Data Types and Type Casting. Boolean type

            • AssignmentLesson 3. Java Conditional statement IF

            • AssignmentLesson 4: Ternary Operator and Switch Statement

            • AssignmentLesson #5: Mathematical Functions in Java

            • AssignmentLesson #6: Characters and Strings in Java

            • AssignmentLesson # 7: For and Foreach

          • Methods (functions)

          • Arrays

          • Topic 5

          • Topic 6

          • Topic 7

          • Topic 8

          • Topic 9

          • Topic 10

          • Topic 11

          • Topic 12

          • Topic 13

          • Topic 14

          • Topic 15

          • Topic 16

        • МО (ПО)

      • Осенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

      • Воскресная компьютерная школа

        • Пользователь компьютера плюс

        • Пользователь прикладных программ

        • Программирование I ступень

        • Программирование II ступень

        • Программирование III ступень

        • Архив

      • Воскресная математическая школа

        • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2025

        • Олимпиадная математическая школа

        • Повышение квалификации

        • Доступная математика

        • Лаборатория математического онлайн-образования мех...

        • Осенняя универсиада

        • Научно-практическая конференция

        • ВМШ

          • ВМШ -2025

        • Летняя олимпиадная математическая школа РНОМЦ и ме...

      • Государственная итоговая аттестация

      • Дополнительное образование

      • Олимпиады

      • Видеолекции

      • Разное

      • Архив курсов

      • Заочная школа мехмата ЮФУ

You are currently using guest access (Log in)
Java Eng
Data retention summary
Get the mobile app Яндекс.Метрика