Understanding Variables and Data Types
Variables and data types are fundamental concepts in Java programming. This tutorial will teach you about different types of variables and how to use them.
Types of Variables
In Java, there are three types of variables:
- Local Variables: Declared inside a method and accessible only within that method.
- Instance Variables: Declared inside a class but outside any method, and accessible by all methods of the class.
- Class Variables: Declared with the
static
keyword inside a class but outside any method. They are shared among all instances of the class.
Primitive Data Types
Java supports several primitive data types:
int
: Integer data type (e.g.,int x = 10;
)float
: Floating-point data type (e.g.,float y = 20.5f;
)double
: Double-precision floating-point data type (e.g.,double z = 30.6;
)char
: Character data type (e.g.,char a = 'A';
)boolean
: Boolean data type (e.g.,boolean isTrue = true;
)
Reference Data Types
Reference data types refer to objects and are created using constructors of classes. They are used to access objects.
- Arrays
- Objects
Declaring and Initializing Variables
To declare and initialize a variable, use the following syntax:
int num = 100; // Declaring and initializing an integer variable
String name = "Java"; // Declaring and initializing a string variable
Type Conversion and Casting
Type conversion allows you to convert a variable from one data type to another. There are two types of type conversion:
- Implicit Casting: Automatic conversion performed by the compiler.
- Explicit Casting: Manual conversion performed by the programmer.
Example of explicit casting:
double d = 100.04;
int i = (int) d; // Explicit casting
Continue exploring our beginner tutorials to learn more about Java programming.