3.1 Declaring and Initializing Variables: In Java, variables are used to store and manipulate data.
Let's learn how to declare and initialize variables using a simple example:
public class VariablesExample {
public static void main(String[] args) {
// Declaring variables
int age;
double height;
boolean isStudent;
// Initializing variables
age = 25;
height = 1.75;
isStudent = true;
// Printing variable values
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Is Student: " + isStudent);
}
}
age of type int, height of type double, and isStudent of type boolean. We then initialize these variables with specific values.System.out.println() statement.Java provides several primitive data types to store different kinds of information.
Here are a few commonly used ones:
int: Used to store whole numbers, such as 42 or -10.double: Used to store decimal numbers, such as 3.14 or -2.5.boolean: Used to store either true or false.char: Used to store a single character, such as 'a' or '$'.Here's an example that demonstrates the usage of these primitive data types:
public class PrimitiveDataTypesExample {
public static void main(String[] args) {
int age = 25;
double height = 1.75;
boolean isStudent = true;
char grade = 'A';
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Is Student: " + isStudent);
System.out.println("Grade: " + grade);
}
}