Java Variables - Understanding Data Types and Their Usage

Learn about the different types of variables in Java, including String, int, float, char, and boolean. This guide covers how Java uses variables to store various data types and their specific characteristics, helping developers manage data efficiently in their programs.



Java Variables

Variables in Java are containers for storing data values. They are used to hold different types of data:

  • String: Stores text surrounded by double quotes, like "Hello"
  • int: Stores whole numbers without decimals, like 123 or -123
  • float: Stores floating-point numbers with decimals, like 19.99 or -19.99
  • char: Stores single characters surrounded by single quotes, like 'a' or 'B'
  • boolean: Stores values with two states: true or false

Declaring (Creating) Variables

To create a variable in Java:


type variableName = value;

Where type is one of Java's types (e.g., int or String), variableName is the name of the variable, and the equal sign assigns a value to it.

Example:

Create a variable called name of type String and assign it the value "John":

Syntax

String name = "John";
System.out.println(name);
Output

John

You can also declare a variable without assigning a value immediately:

Example:

Create a variable called myNum of type int and assign it the value 15:

Syntax

int myNum = 15;
System.out.println(myNum);
Output

15

If you assign a new value to an existing variable, it will overwrite the previous value:

Example:

Change the value of myNum from 15 to 20:

Syntax

int myNum = 15;
myNum = 20;  // myNum is now 20
System.out.println(myNum);
Output

20

Final Variables

If you want a variable to be constant and not changeable, use the final keyword:

Example:

Declare a final variable myNum with the value 15:

Syntax

final int myNum = 15;
// Trying to change will generate an error
// myNum = 20;

Other Types

Examples of declaring variables of other types:

Syntax

int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";