Java Docs

Java Documentation

Java Variables and Literals

In the previous tutorial you learnt about Java comments. Now, let's learn about variables and literals in Java.

Java Variables

A variable is a location in memory (storage area) to hold data.

To indicate the storage area, each variable should be given a unique name (identifier).


Create Variables in Java

Here's how we create a variable in Java:

int speedLimit = 80;

Here, speedLimit is a variable of int data type and we have assigned value 80 to it.

The int data type suggests that the variable can only hold integers. To learn more, visit Java data types.

In the example, we have assigned value to the variable during declaration. However, it's not mandatory.

You can declare variables and assign values separately:

int speedLimit;
speedLimit = 80;

Note: Java is a statically-typed language. It means that all variables must be declared before they can be used.


Change values of variables

The value of a variable can be changed in the program, hence the name variable. For example:

int speedLimit = 80;
... .. ...
speedLimit = 90;

Here, initially the value of speedLimit is 80. Later, we changed it to 90.

However, we cannot change the data type of a variable in Java within the same scope.

What is the variable scope?

Don't worry about it for now. Just remember that we can't do something like this:

int speedLimit = 80;
... .. ...
float speedLimit;

Java Literals

Integer Literals

Integer literals are numeric values without any fractional or exponential part.

// binary
int binaryNumber = 0b10010;
// octal 
int octalNumber = 027;

// decimal
int decNumber = 34;

// hexadecimal 
int hexNumber = 0x2F;

Note: Integer literals initialize variables of byte, short, int, and long.


Floating-point Literals

double myDouble = 3.4;
float myFloat = 3.4F;
double myDoubleScientific = 3.445e2;

Character Literals

char letter = 'a';

String Literals

String str1 = "Java Programming";
String str2 = "Programiz";

Boolean Literals

boolean flag1 = false;
boolean flag2 = true;