Variables
3. Examples
3.4. Practical Example in Java
Below is a Java program demonstrating assignment statements and various operators, adapted from the structure of your previous Python example. It includes basic data types, assignment statements, and expressions using different operators.
public class AssignmentAndOperators { public static void main(String[] args) { // Assignment statements int age = 25; // Simple assignment (integer) double height = 5.9; // Simple assignment (double) boolean isStudent = true; // Simple assignment (boolean) String name = "Alice"; // Simple assignment (String) char initial = 'A'; // Simple assignment (character)
// Compound assignment and arithmetic operators
age += 1; // age = age + 1 (now 26)
double heightInMeters = height * 0.3048; // Convert feet to meters
// Relational and logical operators
boolean isAdult = age >= 18; // Relational operator
boolean canEnroll = isStudent && isAdult; // Logical operator
// String concatenation operator
String greeting = "Hello, " + name;
// Increment operator
int yearsUntilRetirement = 65 - age++; // Post-increment: uses age (26), then increments to 27
// Ternary operator
String status = age >= 18 ? "Adult" : "Minor";
// Output results
System.out.printf("Age: %d%n", age);
System.out.printf("Height: %.1f feet (%.2f meters)%n", height, heightInMeters);
System.out.printf("Is student? %b%n", isStudent);
System.out.printf("Name: %s%n", name);
System.out.printf("Initial: %c%n", initial);
System.out.printf("Years until retirement: %d%n", yearsUntilRetirement);
System.out.printf("Can enroll? %b%n", canEnroll);
System.out.printf("Greeting: %s%n", greeting);
System.out.printf("Status: %s%n", status);
}
}