Java Variables

Soumyadip
The Dev Newbie

--

Variables are containers for storing data values.

In Java, there are many different types of variables, for example:

  • String - stores text, such as "Hello". String values are surrounded by double quotes.
  • int - stores integers (whole numbers), without decimals, such as 123 or -123.
  • float - stores floating point numbers, with decimals, such as 19.99 or -19.99.
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes.
  • boolean - stores values with two states: true or false.
  • array - stores multiple values of any data type into a single place.

long and double are just int and float variables which can store more digits.

Syntax

*type* *variable* = *value*;

You can add the final keyword at the start of declaration if you don't want others (or yourself) to overwrite existing values (this will declare the variable as "final" or "constant", which means unchangeable and read-only).

Example

int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
int myArray[] = {1,2,3,4,5};

More on Arrays is given in this article.

Method Scope

In Java, variables are only accessible inside the region they are created. This is called scope.

Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared:

Example:

public class MyClass {
public static void main(String[] args) {

// Code here CANNOT use x

int x = 100;

// Code here can use x
System.out.println(x);
}
}

--

--

Soumyadip
The Dev Newbie

HTML, CSS, Angular and Java amateur at 16 years old. Is also learning UI/UX design as an encore.