Variables, data types and operators, step by step

Type

int

Name

age

Value

= 25;
Fixed type: it never changes while running
int age

25

double price

99.99

boolean isStudent

true

char initial

'F'

final double PI = 3.14159;

Constant: assigned once, it cannot be modified

Scope

Where a name can be used

The region of code

Visibility

From which lines it is reachable

Who can see it

Lifetime

How long its value exists

During execution

Class Account

Method credit(...)

Block { }

There are no free global variables
Category Visibility Lifetime
Local variable From its declaration to the end of the block That call and block
Block-scoped Only inside that block Until the block ends
Parameter The whole method body During the call
Instance field Per its access modifier While the object is reachable
Class field (static) Per its access modifier From the moment the class loads

Numeric

0

int, double…

boolean

false

unassigned field

References

null

String, Cuenta…

Default is not the same as valid for your domain

Fields of Account

static int totalAccounts int balance

Constructor Account(int balance)

The balance parameter shadows the balance field

this.balance = balance; · field = parameter
1 amount <= 0 · parameter: rejected and returns
2 int previousBalance = balance; · local variable
3 balance += amount; · updates the field
4 balance < previousBalance · overflow: it is restored

Method · age visible

if (age >= 18) {

String message = "Access granted";
Outside the block: message is not visible

Does not compile

int result;

Reading it: it may not be initialized

Compiles

int safeResult = 0;

Only if 0 is a valid value

If a required value is missing: validate and report it
byte

8 bits

-128 … 127

short

16 bits

-32,768 … 32,767

int

32 bits

±2,147,483,647

long

64 bits

10000000000L

float

32 bits

3.14f

double

64 bits

3.14159265

boolean

true / false

true or false

char

16 bits

'A' · Unicode

Arithmetic · + - * / %

10 / 3

3

integer quotient: no decimals

10 % 3

1

modulo: the division remainder

Relational · == != > < >= <=

isAdult true && isStudent true

canEnter = true

&& AND || OR ! NOT
grade1

7.0

grade2

6.0

grade3

8.0

double average

?

double average

(7.0 + 6.0 + 8.0) / 3 = 7.0

boolean passed

?

boolean passed

7.0 >= 6.0 = true

1 · Variables and constants 2 · Scope and lifetime 3 · Primitives and references 4 · Casting 5 · Operators 6 · Exercise

CursoDeJava · l02_variables_tipos_datos_y_operadores

Primitive types Wrappers · autoboxing · unboxing Text and unit conversion Operators