In this module, you'll learn about variable declaration, initialization, console output, and performing arithmetic operations in Java. You'll understand data types, expressions, and basic operations in Java programming.
Variables are containers for storing data values. In Java, each variable must have a specific data type that determines what kind of value it can hold.
// Declaration
dataType variableName;
// Initialization
variableName = value;
// Declaration and initialization in one step
dataType variableName = value;
Java has eight primitive data types:
int
- Integers, 32 bits. Example: int age = 25;
double
- Double precision floating point numbers, 64 bits. Example: double price = 19.99;
boolean
- true or false values. Example: boolean isActive = true;
char
- Single characters, 16 bits. Example: char grade = 'A';
float
- Single precision floating point numbers, 32 bits. Example: float temperature = 98.6f;
long
- Long integers, 64 bits. Example: long population = 8000000000L;
short
- Short integers, 16 bits. Example: short productCode = 32767;
byte
- Very small integers, 8 bits. Example: byte level = 127;
myVar
and myvar
are different variables)int
or class
as variable namesfirstName
, totalAmount
)// Declaring and initializing variables
int age = 25;
double height = 5.9;
char initial = 'J';
boolean isStudent = true;
// Using variables in expressions
int birthYear = 2023 - age;
double heightInCm = height * 30.48;
// Updating variable values
age = age + 1; // Now age is 26
Java provides several ways to display output to the console. The most common method is to use the System.out.println()
method.
System.out.println(x)
- Prints the value of x and then moves to a new lineSystem.out.print(x)
- Prints the value of x without moving to a new lineSystem.out.printf(format, args...)
- Prints formatted text using format specifiers// Printing strings
System.out.println("Hello, Java!");
// Printing variables
int score = 95;
System.out.println("Your score is: " + score);
// Printing multiple values
String name = "Alice";
int age = 30;
System.out.println(name + " is " + age + " years old.");
// Formatted printing
double price = 19.99;
System.out.printf("The price is $%.2f\n", price); // Outputs: The price is $19.99
Format specifiers for printf
and String.format()
:
%d
- for integers%f
- for floating-point numbers%s
- for strings%c
- for characters%b
- for boolean values%n
- for a new line (platform-independent)// Formatting examples
System.out.printf("Name: %s, Age: %d, GPA: %.1f%n", "John", 20, 3.85);
String formatted = String.format("Balance: $%.2f", 1250.575);
System.out.println(formatted); // Outputs: Balance: $1250.58
Java supports various arithmetic operators to perform calculations.
+
(Addition) - Adds values on either side of the operator-
(Subtraction) - Subtracts right-hand operand from left-hand operand*
(Multiplication) - Multiplies values on either side of the operator/
(Division) - Divides left-hand operand by right-hand operand%
(Modulus) - Returns the remainder after division+=
- Adds right operand to the left operand and assigns the result to left operand-=
- Subtracts right operand from the left operand and assigns the result to left operand*=
- Multiplies right operand with the left operand and assigns the result to left operand/=
- Divides left operand with the right operand and assigns the result to left operand%=
- Takes modulus using two operands and assigns the result to left operandWhen dividing two integers, Java performs integer division, which truncates any decimal portion:
int a = 5;
int b = 2;
int result = a / b; // result is 2, not 2.5
To preserve decimal precision when dividing integers, cast at least one operand to a floating-point type:
int a = 5;
int b = 2;
double result = (double) a / b; // result is 2.5
// Alternative approach
double result2 = a / (double) b; // result is 2.5
double result3 = (double) (a / b); // result is 2.0 (wrong way to do it)
Java follows the standard mathematical order of operations:
()
++
, --
, +
, -
)*
, /
, %
)+
, -
)=
, +=
, etc.)// Order of operations example
int result1 = 10 + 5 * 2; // result is 20, not 30
int result2 = (10 + 5) * 2; // result is 30
// Compound calculations
int a = 10;
int b = 4;
int c = 3;
double result3 = (double) (a + b) / c; // result is 4.67
// Compound assignment
int count = 10;
count += 5; // same as count = count + 5
System.out.println(count); // outputs 15
This complete example demonstrates variables, console output, and arithmetic operations:
public class StudentGradeCalculator {
public static void main(String[] args) {
// Variable declarations
String studentName = "John Smith";
int mathScore = 85;
int scienceScore = 92;
int englishScore = 78;
// Calculate total and average
int totalScore = mathScore + scienceScore + englishScore;
double averageScore = (double) totalScore / 3;
// Calculate percentage (assuming max score is 100 per subject)
double maxPossibleScore = 3 * 100;
double percentage = (totalScore / maxPossibleScore) * 100;
// Output results
System.out.println("Student Grade Report");
System.out.println("-------------------");
System.out.println("Name: " + studentName);
System.out.println("Math: " + mathScore);
System.out.println("Science: " + scienceScore);
System.out.println("English: " + englishScore);
System.out.println("-------------------");
System.out.println("Total Score: " + totalScore);
System.out.printf("Average Score: %.2f\n", averageScore);
System.out.printf("Percentage: %.2f%%\n", percentage);
// Determine pass/fail status (pass if average >= 60)
boolean isPassed = averageScore >= 60;
System.out.println("Status: " + (isPassed ? "PASSED" : "FAILED"));
}
}
This program calculates a student's grades, demonstrating:
In this guided project, you'll apply your knowledge of variables, console output, and arithmetic operations to solve real-world problems:
This project involves creating a program that:
This visual project demonstrates:
By completing these projects, you'll gain hands-on experience with the core concepts of this module and see how they can be applied in different contexts.