Java is a popular general-purpose programming language that also incorporates a range of object-oriented aspects. In this tutorial, we will begin at the beginning of the Java programming journey, discussing a concept known as variables and the first and most fundamental data type.
Variables in Java
Variables are fixations, which can store some value in the course of execution of a program. Before working on the Java variable, one has to declare it as the first step in this language. Variable declaration consists of a data type, which is used to specify the type of data that variable can contain and variable name which is used to identify the variable.
Syntax:
Example:
Example:
Types of Variables
Local Variables:
- Declared inside a method, constructor, or block.
- Scope is limited to the method, constructor, or block in which they are declared.
- No default value, must be initialized before use.
Instance Variables (Non-static fields):
- Declared in a class but outside a method, constructor, or block.
- Each instantiated object of the class has its own copy.
- Default values: 0 for numeric types,
null
for object references, andfalse
for boolean.
Class Variables (Static fields):
- Declared with the
static
keyword in a class, but outside a method, constructor, or block. - A single copy shared among all instances of the class.
- Default values are similar to instance variables.
- Declared with the
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable. Java has two categories of data types:
1.Primitive Data Types:
byte
: 8-bit integer, range: -128 to 127.short
: 16-bit integer, range: -32,768 to 32,767.int
: 32-bit integer, range: -2^31 to 2^31-1.long
: 64-bit integer, range: -2^63 to 2^63-1.float
: Single-precision 32-bit IEEE 754 floating point.double
: Double-precision 64-bit IEEE 754 floating point.boolean
: Has only two possible values:true
andfalse
.char
: A single 16-bit Unicode character.
Example:
- Non-Primitive Data Types (Reference/Object Types):
- These include classes, interfaces, and arrays.
- Default value for any reference variable is
null
.
Example:
Example Program
Here's a simple Java program that demonstrates the usage of different types of variables and data types: