Unit 1 - Primitive Types

1.3 Expressions and Assignment Statements

1.3 Expressions and Assignment Statements
Expressions and Assignment Statements in Java

Expressions and Assignment Statements in Java

Expressions

An expression is a combination of variables, operators, literals, and method calls, which evaluates to a single value. They enable operations on data and computation of values.

Types of Expressions

  • Arithmetic expressions: Perform mathematical operations. Example: int result = 7 + 3 * 4;
  • Boolean expressions: Evaluate to true or false. Example: boolean isAdult = age >= 18;
  • String expressions: Operations on strings, like concatenation. Example: String fullName = firstName + " " + lastName;

Operators in Expressions

Operators perform operations on operands (variables or values).

  • Arithmetic operators: +, -, *, /, %
  • Relational operators: ==, !=, >, <, >=, <=
  • Logical operators: &&, ||, !

Assignment Statements

Assignment statements change the value of a variable by assigning it the result of an expression.

variable = expression;

Example of Assignment Statement

int total = 0;
total = total + 5;

Compound Assignment Operators

Combine an arithmetic operation with an assignment for concise code.

  • Addition assignment: +=
  • Subtraction assignment: -=
  • Multiplication assignment: *=
  • Division assignment: /=
  • Modulus assignment: %=

Example of Compound Assignment

int score = 10;
score += 5; // Equivalent to score = score + 5;

Increment and Decrement Operators

Java also has increment (++) and decrement (--) operators for adding or subtracting one from a variable's current value. These can be used in a "prefix" form (before the variable, ++var) or "postfix" form (after the variable, var++), which can affect the order of operations in expressions.

Example of Increment and Decrement

int counter = 0;
counter++; // Postfix increment: adds 1 to counter
--counter; // Prefix decrement: subtracts 1 from counter
Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *