Tutorials/Java/Getting Started
Lesson

data type and variable

Getting Started/Java

Data Types, Variables and Literals


1. Data Types

Definition

A data type defines the type of data that a variable can store.


Types of Data Types

1. Primitive Data Types

  • Predefined by Java

  • Store a single value

  • Efficient in memory and performance


2. Non-Primitive (Reference Data Types)

  • Created by programmer or provided by Java

  • Store references (addresses of objects)

  • Can hold multiple values

Predefined:

  • String

  • Array

  • Wrapper Classes

  • Collections

User-defined:

  • Class

  • Interface

  • Enum

  • Annotation


2. Variables

Definition

A variable is a container used to store data in memory.


Syntax

java
<data_type> variable_name = value;

Types of Variables

1. Class Level Variables

  • Declared inside class but outside methods

  • Stored in heap memory

  • Default values assigned by JVM

Types:

  • Instance Variable

  • Static Variable


2. Local Variables

  • Declared inside methods, blocks, or constructors

  • Stored in stack memory

  • Must be initialized before use

  • Accessible only within their scope


final Keyword

Used to declare constants. Value cannot be changed.

java
final int a = 10;

3. Memory (Heap and Stack)

Heap Memory

  • Stores objects and class-level variables

Stack Memory

  • Stores method calls and local variables

  • Each method has its own stack frame


4. Literals

Definition

A literal is a fixed value assigned to a variable.


Types of Literals


1. Integral Literals

Values without decimal points.

java
int a = 10;

Types:

  • Decimal → 10 (0-9)

  • Octal → 0123 (0-7)

  • Hexadecimal → 0x1A (0-9 a-f)

  • Binary → 0b1010

Octal:

  • Digits must be between 0–7

  • Must start with 0

Hexadecimal:

  • Digits: 0–9, A–F

  • Must start with 0x or 0X

Binary:

  • Only 0 and 1

  • Must start with 0b or 0B


2. Floating-Point Literals

Decimal values.

java
double d = 12.34;
float f = 12.34f;

Scientific notation:

java
double d = 1.2e3; // 1200

3. Boolean Literals

java
boolean b = true;

Valid values:

  • true

  • false

Invalid:

java
boolean b = 1; // not allowed

4. Character Literals

Single character enclosed in single quotes.

java
char ch = 'A';

Valid:

  • 'A', '1', '\n', '\t'

Invalid:

  • ''

  • 'AB'


5. String Literals

Enclosed in double quotes.

java
String s = "Hello";

Note:

  • String is not a primitive data type

  • It is a class from java.lang package


6. Null Literal

Represents absence of value.

java
String s = null;
  • Default value for reference types

  • Not equal to 0

data type and variable | Java | Softcrayons Tech Solutions