Lesson Overview

All set, astronaut! Today, we're diving deep into Java, mastering arithmetic and logical operations on primitive types. These skills are crucial for data manipulation and decision-making during our space voyage.

Arithmetic Operations Uncovered

Recall from our previous sessions that Java's primitive data types include int for whole numbers, float for decimal numbers, boolean for true/false values, and char for single characters. Both int and float have limitations on their numerical range, which will come into play when we discuss overflow later in this lesson.

We can perform arithmetic operations — addition (+), subtraction (-), multiplication (*), division (/), and modulus - the remainder of the division (%) — on numerical types. For example,

int a = 10;
int b = 2;
System.out.println(a + b); // Outputs: 12
System.out.println(a - b); // Outputs: 8
System.out.println(a * b); // Outputs: 20;
System.out.println(a / b); // Outputs: 5
System.out.println(a % b); // Outputs: 0

Java allows order alteration using parentheses and provides the modulus (%) operation — useful for identifying whether numbers are even or odd!

Logical Operations Explained

Logical operators — && (AND), || (OR), ! (NOT) — serve as decision-makers in Java and evaluate to boolean values — true or false. Here's how we can use them with two boolean values:

System.out.println(true && true); // true
System.out.println(true && false); // false
System.out.println(false && true); // false
System.out.println(false && false); // false

System.out.println(true || true); // true
System.out.println(true || false); // true
System.out.println(false || true); // true
System.out.println(false || false); // false

System.out.println(!true); // false
System.out.println(!false); // true

Here, && produces true only if both boolean values are true. || delivers true if either is true. And ! reverses the boolean value.

But, of course, the main application of logical operations is for variables. Here is a quick, simple example of how they can help to make decisions:

int speed = 60;
int minSpeed = 30;
int maxSpeed = 70;
// Check if the speed is inside the expected bounds.
System.out.println(speed > minSpeed && speed < maxSpeed); // Prints: true
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal