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);
}
}
- In this example, we declare three variables: age of type int, height of type double, and isStudent of type boolean. We then initialize these variables with specific values.
- To access the value stored in a variable, we can use the variable's name. In this case, we print the values of the variables using the System.out.println() statement.
3.1 Primitive Data Types:
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);
}
}
In this example, we declare and initialize variables of different primitive data types and print their values.
3.2 Working with Strings:
Strings are used to represent sequences of characters in Java. They are widely used for storing text and are denoted by double quotation marks (””).
- Here's an example:
public class StringsExample {
public static void main(String[] args) {
String name = "CM Programming";
String message = "Hello, " + name + "!";
System.out.println(message);
}
}
- In this example, we declare a variable name of type String and initialize it with the value "CM Programming".
- We then concatenate the name with a greeting message using the + operator.
- Finally, we print the concatenated message.
3.3 Understanding Type Conversion:
In Java, type conversion, also known as type casting, allows you to convert a value from one data type to another.
- There are two types of type conversion: implicit and explicit.
- Implicit conversion happens automatically when a value of a smaller data type is assigned to a variable of a larger data type.
- For example:
int x = 5;
double y = x; // Implicit conversion from int to double
- Explicit conversion, on the other hand, requires manual intervention using casting.
- Here's an example:
double a = 3.14;
int b = (int) a; // Explicit conversion from double to int using casting