Expressions and Assignment Statements in Java
Welcome to the world of programming! Today, we'll dive into some fundamental concepts in Java: expressions and assignment statements. These are the building blocks of any program. Let's break them down step by step.
1. Literals
A literal is a fixed value that we write directly in the code. Think of it as a number or text that doesn't change. Here are some examples:
2. Arithmetic Expressions
Arithmetic expressions use arithmetic operators to perform calculations. The basic operators are:
Examples:
3. Integer and Double Arithmetic
Examples:
4. Compound Expressions
We can combine multiple arithmetic operations in one expression. For example, 5 + 3 * 2 is a compound expression.
Operator Precedence
Operator precedence determines the order in which operations are performed. Multiplication and division have higher precedence than addition and subtraction.
Example:
5. Division by Zero
Attempting to divide an integer by zero in Java will result in an ArithmeticException.
Example:
6. Assignment Statements
An assignment statement assigns a value to a variable. It uses the = operator.
Example:
int a = 5; // Assigns the value 5 to the variable a
Real-World Example
Imagine you are calculating the total cost of items in a shopping cart. Each item has a price, and you want to find the total.
Example:
double item1 = 5.99;
double item2 = 3.49;
double totalCost = item1 + item2;
System.out.println("Total cost: " + totalCost);
Full Program Demonstrating the Concepts
Here is a simple Java program that demonstrates arithmetic expressions and assignment statements:
public class ArithmeticDemo {
public static void main(String[] args) {
// Literals
int num1 = 10; // integer literal
double num2 = 5.5; // double literal
// Arithmetic expressions
int sum = num1 + 5; // addition
double product = num2 * 2; // multiplication
// Compound expression
double result = (num1 + 5) * num2; // (10 + 5) * 5.5 = 15 * 5.5 = 82.5
// Division by zero (uncommenting the next line will cause an error)
// int error = num1 / 0;
// Printing the results
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
System.out.println("Result: " + result);
}
}
Programming Problem
Write a program that calculates the average of three numbers. Use literals for the three numbers and use arithmetic expressions to find their average. Then, print the result.
Steps:
Example:
public class AverageCalculator {
public static void main(String[] args) {
// Step 1: Assign numbers to variables
int num1 = 8;
int num2 = 12;
int num3 = 15;
// Step 2: Calculate the sum
int sum = num1 + num2 + num3;
// Step 3: Calculate the average
double average = sum / 3.0;
// Step 4: Print the average
System.out.println("Average: " + average);
}
}
Happy coding! Understanding these basics will set a strong foundation for your programming journey.