Data

Variable

Java

 

Defining Variable

Java 8
int age;

String name = "Sam";

Here, we are defining a variable age of type Integer and name of type String.

You can optionally initialize a variable with a value in its declaration.

Variable names are:

  • Case sensitive
  • Can contain letters, digits, $ or _
  • Cannot start with a digit
  • Cannot be any of the reserved keywords
 

Variable Types

Java 8
// Primative Data Types
boolean booleanVar = true;
byte    byteVar = 12;
short shortVar = 12;
int   intVar = 12;
long  longVar = 12L;
float floatVar = 1.618F;
double doubleVar = 1.618;
char   charVar = 'c';

// Non-Primative Data Types
String stringVar = "Hello";
int[]  arrayVar = new int[7];

Data Types in Java are divided into two groups:

  • Primitive Data Types:
    These are the most basic data types, which are: boolean, byte, short, int, long, float, double, char.

  • Non-Primitive Data Types:
    These are types that are using Primitive Types to create new Types: String, Array, Class object types, etc.

 

Type Safety

Java 8
int status = 0;

status = "success";   // Error

Java is a Type-Safe programming language, meaning that variables can only accept values of their type.

 

Defining Variables in one line

Java 8
int x, y=7, z=12;

You can define multiple variables in one statement.

Here, we are creating variables x, y, and z of type integer, and initialize y to 7 and z to 12.

 

Setting Variable value

Java 8
int age;

age = 21;

Here, we are defining a variable age of type integer first and assign a value 21 to it.

 

Getting Variable value

Java 8
int age = 21;

int samAge = age + 3;   // samAge -> 24

To get the value of a variable, you can simply use its name.