Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Variables

Java Variables

Variables serve as containers for holding data values.

In Java, various types of variables exist, including:

  1. String: Holds text enclosed in double quotes, like “Hello”.
  2. int: Stores integers, without decimals, such as 123 or -123.
  3. float: Contains floating-point numbers, including decimals, like 19.99 or -19.99.
  4. char: Holds single characters, like ‘a’ or ‘B’, enclosed in single quotes.
  5. boolean: Holds values representing two states: true or false.

Declaring (Creating) Variables

When creating a variable, you need to define its type and assign it a value.

Syntax

type variableName = value;

The type refers to one of Java’s data types (like int or String), and variableName is the chosen identifier for the variable (such as x or name). The equal sign (=) is employed to assign values to the variable.

Consider the following example to create a variable intended for storing text:

Example

Declare a variable named “name” of type String and initialize it with the value “John”:

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

For creating a variable intended to store a number, refer to the following example:

Example

Declare a variable named “myNum” of type int and initialize it with the value 15:

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

It's also possible to declare a variable without assigning a value initially, and then assign a value later:

Example

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

Keep in mind that assigning a new value to an existing variable will replace the previous value:

Example

Update the value of myNum from 15 to 20 :

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

Final Variables

To prevent others, or yourself, from altering existing values, employ the final keyword. This designates the variable as “final” or “constant,” rendering it immutable and read-only.

Example

final int myNum = 15;
myNum = 20;  // will generate an error: cannot assign a value to a final variable

Other Types

An illustration showcasing the declaration of variables of different types:

Example

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

In the next section, you’ll delve deeper into understanding various data types.