Java Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
public class Main {
public static void main(String[] args) {
int x = 100 + 50;
[Link](x);
Although the + operator is often used to add together two values, like in the example above, it can also
be used to add together a variable and a value, or a variable and another variable:
public class Main {
public static void main(String[] args) {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
[Link](sum1);
[Link](sum2);
[Link](sum3);
Java divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator Name Description Example Try it
+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1
Java Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
public class Main {
public static void main(String[] args) {
int x = 10;
x += 5;
[Link](x);
Java Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.
The return value of a comparison is either true or false. These values are known as Boolean
values, and you will learn more about them in the Booleans and If..Else chapter.
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
[Link](x > y); // returns true, because 5 is higher than 3
Java Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:
Operator Name Description Example Try it
Returns true if both statements are
&& Logical and x < 5 && x < 10
true
Returns true if one of the statements
|| Logical or x < 5 || x < 4
is true
Reverse the result, returns false if the
! Logical not !(x < 5 && x < 10)
result is true
Java Strings
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double quotes:
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
[Link](greeting);
String Length
A String in Java is actually an object, which contain methods that can perform certain operations
on strings. For example, the length of a string can be found with the length() method:
public class Main {
public static void main(String[] args) {
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
[Link]("The length of the txt string is: " + [Link]());
Type Conversion in Java with Examples
Java provides various data types just like any other dynamic language such as boolean, char, int,
unsigned int, signed int, float, double, long, etc in total providing 7 types where every datatype acquires
different space while storing in memory. When you assign a value of one data type to another, the two
types might not be compatible with each other. If the data types are compatible, then Java will perform
the conversion automatically known as Automatic Type Conversion, and if not then they need to be cast
or converted explicitly. For example, assigning an int value to a long variable.
Data Types and Their Memory Allocation
Datatype Bits Acquired In Memory
boolean 1
byte 8 (1 byte)
char 16 (2 bytes)
short 16(2 bytes)
int 32 (4 bytes)
long 64 (8 bytes)
float 32 (4 bytes)
double 64 (8 bytes)
Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This happens
when:
The two data types are compatible.
When we assign a value of a smaller data type to a bigger data type.
For Example, in java, the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.
Example:
// Java Program to Illustrate Automatic Type Conversion
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
int i = 100;
// Automatic type conversion
// Integer to long type
long l = i;
// Automatic type conversion
// long to float type
float f = l;
// Print and display commands
[Link]("Int value " + i);
[Link]("Long value " + l);
[Link]("Float value " + f);
}
}
Output
Int value 100
Long value 100
Float value 100.0
Type Conversion in Java
In Java, we work with different types of data. We have:
int for numbers without decimal points, like 5 or -6.
double for numbers with decimal points, like -5.6 or 7.84.
char for single characters, like 'a' or '1'.
Sometimes, we need to change data from one type to another, like from double to int or from int
to double. This process is called type conversion.
In this lesson, we'll learn how to do this type conversion in Java. Let's dive in!
Implicit Type Conversion
Sometimes in Java, one type of data is automatically changed to another type. Let's look at an
example:
class Main {
public static void main(String[] args) {
// create a double type variable
double num;
// assign int value to double
num = 15;
[Link](num);
}
}
Output-
15.0
In this program, we created a variable called num, which is of type double. However, we
assigned an integer value 15 to it.
Java automatically converted the integer value 9 to a double value 9.0. That's why the output is
15.0
This automatic type conversion is known as Implicit Type Conversion. It's like when you have
a toy car and you place it on a toy truck, and it automatically adjusts its size to fit on the truck.
The Java Math class provides several static methods that allows us to work on mathematical
calculations with numbers. These methods can be accessed by using the Math class with a given
method:
[Link]();
Math Constants
There are several mathematical constants defined in the Java Math class. These constants are
marked as public static final, which means they are public, class-level constants with
unchangeable values and can be accessed as follows:
Name value Definition
[Link] 3.141592653589793 This constant represents the mathematical constant π (pi).
Math.E 2.718281828459045 This constant represents the base of the natural logarithm, also known
Name value Definition
as Euler’s number.
Math Methods
Here are the Math methods in alphabetical order:
Math Methods
.abs()
Returns the absolute value of the argument.
.acos()
Returns the inverse cosine of the argument in radians.
.addExact()
Returns the sum of its arguments.
.asin()
Returns the inverse sine of the argument in radians.
.atan()
Returns the inverse tangent of the argument in radians.
.atan2()
Returns the counterclockwise angle, in radians, between a (x,y) point and the positive x-axis.
.cbrt()
Returns the cube root of a double-type value.
.ceil()
Returns the double value that is a mathematical integer and is greater than or equal to the
original value.
.cos()
Returns the trigonometric cosine of the specified angle.
.decrementExact()
Returns the argument decremented by one, throwing an exception if the result overflows the
datatype.
.floor()
Returns the largest integer value that is less than or equal to the argument. When the provided
value is either an integer, zero, not a number, or positive or negative infinity.
.hypot()
Returns the hypotenuse of a right-angled triangle.
.incrementExact()
Returns the argument incremented by one, throwing an exception if the result overflows the
datatype.
.log()
Returns the natural logarithm (base e) of a double value as a parameter.
.log10()
Returns the logarithm base 10 of a double value as a parameter.
.log1p()
Returns the natural logarithm (base e) of the sum of a double value as a parameter and 1.
.max()
Returns the maximum value from the given two arguments.
.min()
Returns the minimum value from the given two arguments.
.multiplyExact()
Returns the product of its arguments.
.negateExact()
Returns the negation of the argument and raises an exception if the result overflows.
.nextAfter()
Returns the floating-point number next to the first argument in the direction of the second
argument.
.nextDown()
Returns the floating-point value adjacent to the parameter provided in the direction of negative
infinity.
.pow()
Returns the first argument raised to the power of the second argument.
.random()
Returns a pseudorandom double that is 0.0 or greater, and less than 1.0.
.rint()
Returns a double that is rounded to the closest whole integer.
.round()
Returns an int or long value that is closest to the number provided.
.scalb()
Returns the first argument multiplied by 2 to the power of the second argument.
.signum()
Used to determine whether a number is positive, negative, zero, or NaN.
.sin()
Returns the trigonometric sine of the specified angle.
.sinh()
Returns the hyperbolic sine of a double-type value.
.sqrt()
Returns the positive, properly rounded square root of a double-type value.
.tan()
Returns the tangent of an angle given in radians.
.tanh()
Returns the hyperbolic sine of a double-type value.
.toDegrees()
Returns an angle measurement converted from radians to degrees.
.toIntExact()
Returns the integer value of a long type argument. An exception is thrown if the value of
argument overflows that of an int.
.toRadians()
Converts an angle in degrees to an approximately equivalent angle in radians.
.ulp()
Returns the size of the unit of last precision of a number.
Example
The following example uses [Link]() to return the absolute values of -6.5, 2, and -340.8:
class AbsoluteValue {
public static void main(String[] args) {
double x = -6.5;
int y = 2;
double z = -340.8;
[Link]([Link](x));
[Link]([Link](y));
[Link]([Link](z));
}
}
This produces the following output:
6.5
2
340.8
The Java Math class has many methods that allows you to perform mathematical tasks on
numbers.
[Link](x,y)
The [Link](x,y) method can be used to find the highest value of x and y:
[Link](x)
The [Link](x) method returns the absolute (positive) value of x:
public class Main {
public static void main(String[] args) {
[Link]([Link](-4.7));
Random Numbers
[Link]() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):
public class Main {
public static void main(String[] args) {
[Link]([Link]());
}
Number Comparison Basics
Introduction to Number Comparison in Java
In Java programming, comparing numbers is a fundamental operation that requires careful
attention to detail. Different data types and comparison methods can lead to unexpected results if
not handled correctly.
Primitive Number Types
Java provides several primitive number types for storing numeric values:
Type Size Range
byte 8 bits -128 to 127
short 16 bits -32,768 to 32,767
int 32 bits -2^31 to 2^31 - 1
long 64 bits -2^63 to 2^63 - 1
float 32 bits Approximate decimal values
double 64 bits Precise decimal values
Basic Comparison Operators
Java offers several comparison operators for numeric values:
Comparison Operators
== Equality
!= Inequality
> Greater Than
< Less Than
>= Greater or Equal
<= Less or Equal
Comparison Example
Here's a basic example demonstrating number comparisons:
public class NumberComparison {
public static void main(String[] args) {
int a = 10;
int b = 20;
// Basic comparisons
[Link]("a == b: " + (a == b)); // false
[Link]("a < b: " + (a < b)); // true
[Link]("a >= b: " + (a >= b)); // false
}
}
Java program to get minimum and maximum from a list
import [Link];
import [Link];
import [Link];
public class Demo {
public static void main(String[] args) {
[Link]("Required packages have been imported");
List<Integer> input_list = new ArrayList<>();
input_list.add(500);
input_list.add(650);
input_list.add(300);
input_list.add(250);
input_list.add(110);
[Link]("The list is defined as " +input_list);
List<Integer> sortedlist = new ArrayList<>(input_list);
[Link](sortedlist);
if (sortedlist == null || [Link]() == 0) {
[Link]("\nThe minimum value of the list is: "
+Integer.MAX_VALUE);
}
[Link]("\nThe minimum value of the list is: "
+[Link](0));
if (sortedlist == null || [Link]() == 0) {
[Link]("The maximum value of the list is: " +
Integer.MIN_VALUE);
return ;
}
int list_size = [Link]() - 1;
[Link]("The maximum value of the list is: " +
[Link](list_size));
}
}
Output
Required packages have been imported
The list is defined as [500, 650, 300, 250, 110]
The minimum value of the list is: 110
The maximum value of the list is: 650
Code Java Dice Roll Program
package [Link];
import [Link];
public class DiceRollSLB {
public static void main(String[] args) {
Random random = new Random();
int dice1 = [Link](6) + 1;
int dice2 = [Link](6) + 1;
[Link]("Dice 1: " + dice1);
[Link]("Dice 2: " + dice2);
}
}
OP: 1
Dice 1: 3
Dice 2: 5
OP: 2
Dice 1: 3
Dice 2: 6
OP: 3
Dice 1: 1
Dice 2:
Code Explanation
The above program calculates rolling of a specified number of dice with a specified number of
sides on each die, and prints out the results of each roll. In above example we have rolled it 3
times that means we ran this above program 3 times.
What is dice roll ?
Dice Roll
Rolling dices is a form of chance that involves rolling at least one die. Once rolled, the face
value of the die will determine its outcome; and depending on how many sides there are on
it, values ranging from 1 to 6 inclusive can be produced from that roll. Dice rolls are board
games or gambling games in order to add an element of chance and uncertainty into gameplays.
JavaScript Comparison and Logical Operators
Comparison and Logical operators are used to test for true or false.
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
[Link](x > y); // returns true, because 5 is higher than 3
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
[Link](x != y); // returns true because 5 is not equal to 3
Java Conditions and If Statements
You already know that Java supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
Java has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of Java code to be executed if a condition is true.
public class Main {
public static void main(String[] args) {
int x = 20;
int y = 18;
if (x > y) {
[Link]("x is greater than y");
Steps to calculate the roots of a quadratic equation
Following are the steps to calculate the roots of a quadratic equation â
Start by importing the Scanner class from [Link] package.
Define the class, which contains the main method and declare variables for the two roots,
firstRoot and secondRoot, to store the results.
Instantiate a Scanner object to read values entered by the user and ask the user to input
the coefficients ð, ð, and ð of the quadratic equation and store these
values.
Calculate Determinant: Compute the determinant based on the coefficients, which helps
to determine the nature of the roots.
Check Determinant: If the Determinant is Positive: Calculate and display two distinct real
roots.
If the Determinant is Zero: Determine and display one real root, indicating that it is a
repeated root.
If the Determinant is Negative: Calculate the real and imaginary parts to indicate the
presence of complex roots, then display them accordingly.
Finally, close the scanner to free up resources.
Java program to find the roots of a quadratic equation
import [Link];
public class RootsOfQuadraticEquation {
public static void main(String args[]) {
double secondRoot = 0, firstRoot = 0;
Scanner sc = new Scanner([Link]);
[Link]("Enter the value of a ::");
double a = [Link]();
[Link]("Enter the value of b ::");
double b = [Link]();
[Link]("Enter the value of c ::");
double c = [Link]();
// Calculate the determinant
double determinant = (b * b) - (4 * a * c);
// Check the value of the determinant
if (determinant > 0) {
double sqrt = [Link](determinant);
firstRoot = (-b + sqrt) / (2 * a);
secondRoot = (-b - sqrt) / (2 * a);
[Link]("Roots are :: " + firstRoot + " and " +
secondRoot);
} else if (determinant == 0) {
firstRoot = (-b) / (2 * a);
[Link]("Root is :: " + firstRoot);
} else {
// If the determinant is negative, calculate complex roots
double realPart = -b / (2 * a);
double imaginaryPart = [Link](-determinant) / (2 * a);
[Link]("Roots are complex: " + realPart + " + " +
imaginaryPart + "i and " + realPart + " - " + imaginaryPart + "i");
}
// Close the scanner
[Link]();
}
}
Java Switch
Java Switch Statements
Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed:
SyntaxGet your own Java Server
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break and default keywords are optional, and will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
}
}
}
The break Keyword
When Java reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more
testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.
Java While Loop
Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
Java While Loop
The while loop loops through a block of code as long as a specified condition is true:
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
[Link](i);
i++;
}
}
}
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
The example below uses a do/while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:
public class Main {
public static void main(String[] args) {
int i = 0;
do {
[Link](i);
i++;
}
while (i < 5);
}
}
Java For Loop
When you know exactly how many times you want to loop through a block of code, use the for
loop instead of a while loop:
SyntaxGet your own Java Server
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
[Link](i);
}
}
}
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is
true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Another Example
This example will only print even values between 0 and 10:
public class Main {
public static void main(String[] args) {
for (int i = 0; i <= 10; i = i + 2) {
[Link](i);
}
}
}
What is an Array?
An array is a collection of values.
The image below shows how we can think of an array named myFruits, with the values
'banana', 'apple', and 'orange' stored inside it.
'apple''orange''banana'ValuesArray NamemyFruitsIndexes01
Each value in an array has a position, called index, which starts at 0.
Below is how the myFruits array is created, using Python code:
myFruits = Name['banana','apple','orange']ValuesIndexes012
The first value 'banana' is positioned at index 0 in the array.
What Can I Do With an Array?
Arrays make it easier to work with groups of values compared to using a separate variable for
each value.
So instead of creating 3 variables:
fruit1 = 'banana'
fruit2 = 'apple'
fruit3 = 'orange'
We can just create an array:
myFruits = ['banana','apple','orange']
With an array, you can:
Store a collection of numbers, words, or objects.
Access any value using its index (position).
Read, update, insert, or remove any of the array values.
See how an array can be created and used in the sections below.
Creating an Array
When creating an array we must specify the name of the array and the values inside it.
Here is how the myFruits array can be created using different programming languages:
import [Link];
public class Main {
public static void main(String[] args) {
String[] myFruits = {"banana","apple","orange"};
[Link]([Link](myFruits));
Array Operations
Arrays can be read and manipulated in many different ways, here are some common things you
can do with an array:
Operation Description
read Reads a value from an index in the array.
update Updates the existing value at an array index position.
insert Inserts a new value in the array, in addition to the existing values.
remove Removes a value from the array at a given index position.
length Gives us the number of values in the array. The number of values is the length of an array.
loop Visits each value in the array, using a loop.
Updating an Array Value
To update a value in an array, we use the array name with the index position of the value we
want to update, like this myFruits[0], and then we use the equal sign = to store a new value
there.
Inserting an Array Value
To insert a value into an array, in addition to the existing values, we need:
the array name
a command to do the insert operation
the value to be inserted
Strict Definition of an Array
Arrays found in modern languages like Python or JavaScript are flexible, meaning arrays can
grow, shrink, and hold different types of values. Other programming languages, like C and Java,
require arrays to be defined more strictly.
A more strict definition of an array means that in addition to being a collection of values, an
array is also:
fixed length
same data type for all values
stored contiguously in memory
Fixed length means that the array length (the number of values inside the array), cannot be
changed.
When using the C programming language for example, if you have created an array of 4 values,
the array length (4) is fixed and cannot be changed. So if you want to insert a 5th value at the end
of your array, you must create a new array 5 values long, put in the original 4 values, and put the
5th value in the last place in new array where there is now place for it.
Same datatype means that all values in the array must be of the same type, so they must all be
whole numbers for example, or decimal numbers, or characters, or strings, or some other data
type.
Having the array stored contiguously in memory means that the values are stored right after
each other in one block of memory, like a group of friends living right next to each other on the
same street. Read more about how arrays are stored in memory here.
Using arrays in their strict form gives the user full control over how the program actually
executes, but it also makes it hard to do certain things, and it is more prone to errors.
When in need for more flexible/dynamic array functionality in languages such as C or Java,
developers often use libraries to help them get the expanded dynamic array functionality they are
looking for.
In the code examples on this page, to achieve a dynamic array length so that we can insert and
remove values, we have used Python Lists, JavaScript Arrays, Java ArrayList, and C++ Vectors.