Variables in Java are used to **store data** in memory. Each variable has a **data type**, a **name**, and a **value**.
Java Variables and Data Types
What are Variables?
Variables in Java are used to **store data** in memory. Each variable has a **data type**, a **name**, and a **value**.
Declaring Variables in Java
In Java, variables are declared using the syntax:
dataType variableName = value;
Example:
int age = 25;
double price = 99.99;
char grade = 'A';
String name = "John";
Types of Variables
- Local Variables: Declared inside a method and can only be used within that method.
- Instance Variables: Declared inside a class but outside methods. They belong to an object.
- Static Variables: Declared with the
static
keyword and shared among all instances of a class.
Data Types in Java
Java has two types of data types:
1. Primitive Data Types
These are the **basic data types** in Java:
byte
- 1 byte, stores small whole numbers (-128 to 127)short
- 2 bytes, stores larger whole numbersint
- 4 bytes, stores integerslong
- 8 bytes, stores large numbersfloat
- 4 bytes, stores decimal numbersdouble
- 8 bytes, stores large decimal numberschar
- 2 bytes, stores a single characterboolean
- 1 byte, storestrue
orfalse
Example:
public class DataTypesExample {
public static void main(String[] args) {
int age = 30;
double price = 50.5;
char letter = 'A';
boolean isJavaFun = true;
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Letter: " + letter);
System.out.println("Is Java Fun? " + isJavaFun);
}
}
2. Non-Primitive Data Types
These include **Strings, Arrays, Classes, and Interfaces.** They store references to objects.
Example:
public class NonPrimitiveExample {
public static void main(String[] args) {
String message = "Hello, Java!";
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(message);
System.out.println("First Number: " + numbers[0]);
}
}
Type Casting in Java
Java allows conversion between different data types:
1. Implicit Casting (Widening Conversion)
Smaller data types can be converted to larger data types automatically.
int num = 100;
double newNum = num; // int to double (automatic)
2. Explicit Casting (Narrowing Conversion)
Larger data types must be manually converted to smaller types.
double price = 99.99;
int newPrice = (int) price; // double to int (manual)
Conclusion
Java provides a variety of data types for storing different kinds of values. Understanding variables and data types is essential for writing efficient Java programs.
📌 Next Topic: Operators in Java