Java Expressions
In Java, an expression is a combination of values, variables, and operators that evaluates to a single value.
Expressions are used to perform calculations or to evaluate a condition.
There are different types of expressions in Java, including:
Arithmetic Expressions
Arithmetic expressions are used to perform mathematical calculations. Some examples of arithmetic expressions include:int x = 5; int y = 10; int z = x + y; int a = x * y; double b = y / x;
In this example, we create two integer variables x
and y
, and use arithmetic expressions to perform calculations and assign the results to z
, a
, and b
. The first expression calculates the sum of x
and y
, the second expression calculates the product of x
and y
, and the third expression calculates the quotient of y
divided by x
.
Relational Expressions
Relational expressions are used to compare values and return a boolean result. Some examples of relational expressions include:int x = 5; int y = 10; boolean isEqual = x == y; boolean isGreaterThan = x > y; boolean isLessThanOrEqual = x <= y;
In this example, we use relational expressions to compare the values of x
and y
and assign the results to boolean variables. The first expression checks whether x
is equal to y
, the second expression checks whether x
is greater than y
, and the third expression checks whether x
is less than or equal to y
.
Logical Expressions
Logical expressions are used to combine boolean values and return a boolean result. Some examples of logical expressions include:boolean x = true; boolean y = false; boolean andResult = x && y; boolean orResult = x || y; boolean notResult = !x;
In this example, we use logical expressions to combine boolean values and assign the results to boolean variables. The first expression uses the logical AND operator &&
to check whether both x
and y
are true, the second expression uses the logical OR operator ||
to check whether at least one of x
and y
is true, and the third expression uses the logical NOT operator !
to invert the value of x
.
Conditional Expressions
Conditional expressions, also known as ternary expressions, are used to make a decision based on a condition. They have the following syntax:condition ? value1 : value2
If the condition is true, the expression evaluates to value1
. Otherwise, it evaluates to value2
. Here's an example:
int x = 5; int y = 10; int max = x > y ? x : y;
In this example, we use a conditional expression to assign the maximum value of x
and y
to the variable max
. If x
is greater than y
, the expression evaluates to x
, otherwise it evaluates to y
.