Java Variables

In Java, variables are used to store data values that can be referenced and manipulated in a program. Every variable in Java has a data type, a name, and a value


Primitive Data Types:

  • Directly store values (e.g., numbers, characters).
  • Default Values: Automatically initialized for instance/static variables.

Type

Size

Default Value

Description

Example

byte

8 bits

0

Small integer range (-128 to 127).

byte b = 10;

short

16 bits

0

Medium integer range (-32,768 to 32,767).

short s = 3000;

int

32 bits

0

Standard integer range (-2^31 to 2^31-1).

int age = 25;

long

64 bits

0L

Large integer range (-2^63 to 2^63-1).

long distance = 100000L;

float

32 bits

0.0f

Decimal with 6-7 digits of precision.

float pi = 3.14f;

double

64 bits

0.0d

Decimal with 15-16 digits of precision.

double e = 2.71828;

char

16 bits

\u0000

A single character (Unicode).

char grade = 'A';

boolean

8 bits

false

Logical true/false.

boolean isActive = true;

Example
byte b = 10; // Small Integer variable
short s = 3000; // Medium Integer variable
int age = 25; // Standard Integer variable
long distance = 100000L; // Long Integer variable
float pi = 3.14f; // Decimal with 6-7 digits of precision
double price = 19.99; // Decimal with 15-16 digits of precision
char grade = 'A'; // Character variable
boolean isActive = true; // Boolean variable

Try it yourself


Reference Data Types

  • Definition: Reference variables store the memory address (reference) of an object instead of the actual value.
  • Characteristics:
  • Used to reference objects (like arrays, strings, or user-defined objects).
  • Default value is null.
  • You can call methods on reference types.

Type

Description

Default Value

Example

String

Stores a sequence of characters. Immutable in nature.

null

String name = "John";

Array

Stores a fixed-size collection of elements of the same data type.

null

int[] numbers = {1, 2, 3};

Class/Object

Represents an instance of a user-defined class or an object.

null

MyClass obj = new MyClass();

Example
String name = "John";
int[] numbers = {1, 2, 3};

Try it yourself


Variable Naming Rules:

  1. Must start with a letter, _, or $.
  2. Cannot start with a number.
  3. Cannot use reserved keywords.
  4. Should be descriptive and use camelCase.
Example
int validVariable = 10; // Valid
int $amount = 100; // Valid
int _counter = 5; // Vali
int 1number = 20; // Invalid (starts with a number)
int class = 30; // Invalid (uses reserved keyword)

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.