D3: Assignment Statements, Type Casting, Booleans, and Operators
Variable Initialization and Assignment Statements
Assignment Operator (
=):In computer programming, the
=symbol represents the assignment operator, meaning a value is assigned to a variable.In the expression
, the=operator assigns the integer valueto the variable.
Variable Initialization Rules:
A variable must be initialized with a value before it can be used or referenced within a program.
Data Type Matching: The value assigned to a variable must match the declared data type of that variable.
Initialization via Expressions:
A variable can be initialized or updated using an expression rather than a simple literal value.
Example expression assignment:
.Variable Reassignment Trace Example:
Evaluation:
evaluates to, resulting inholding the final value of.
Type Conversion and Casting
Definition of Casting:
Casting is defined as converting a value from one data type into another data type.
Implicit Conversion to Decimal:
When an
value is assigned to avariable, Java automatically converts the integer value into a decimal numerical format.
Integer Division and Rounding Techniques
Behavior of Integer Division:
When dividing two
values, the resulting value retains only the integer portion of the quotient, truncating any fractional remainder.Division of integers example:
evaluates to and returns.Division with floating-point values example:
evaluates to.
Explicit Type Casting Syntax:
Type casting can be performed explicitly during expression evaluation:
.Casting double to int:
converts a floating-point result into an integer data type by discarding the decimal portion.
Rounding to the Nearest Integer:
Casting can be utilized to round floating-point numbers to the nearest whole integer.
Procedure to round a positive floating-point number to the nearest integer:
Add
to thevalue.Explicitly cast the resulting
value as an.
Boolean Logic and Relational Operators
Boolean Fundamentals:
Booleans (
) store simple binary values, specificallyor.When a boolean variable is output or printed, it displays the exact binary value (
or) stored within it.
Relational Operators:
Relational operators compare two values and yield a
result (or).Expressions using relational operators require evaluated values on both sides (e.g.,
evaluates to a).List of Relational Operators:
<: Less than>: Greater than==: Equal to>=: Greater than or equal to<=: Less than or equal to!=: Not equal to
Relational Operator Code Trace Example:
Code snippet:
java boolean timeToEat; int time = 5; timeToEat = time >= 5; Evaluation: The expression
compares, which evaluates to. Consequently,is assigned.
Shortcut Operators and Compound Assignment
Increment and Decrement Shortcut Operators:
: Increments the value stored inby.: Decrements the value stored inby.
Compound Assignment Shortcut Operators:
: Incrementsby(equivalent to).: Decrementsby(equivalent to).: Multipliesby(equivalent to).