Java Variables
Variables are containers for storing data values.
In Java there are different types of variables, for example:
String |
Store text, such as “hey SparkDatabox”, Sring values
are surrounded by double quotes. |
int |
Stores integers which is “whole numbers”, without decimals,
such as 1234 or -1234 |
float |
Stores floating point numbers, with decimals, such as
9.99 or -9.99 |
char |
Stores single character, such as ‘a’ or ‘X’. Char
values are surrounded by single quotes. |
boolean |
Stores values with two states such as True or False |
Declaring Variables
To create a variable, the type should be specified and value is assigned to it.
Syntax:
type variable = value
Where type is a Java variable types ( such as int, String, float, char, Boolean), variable is the name of the variable (such as x ), the = is the assignment operator which is used to assign values to the variables and value is the value assigned to the variable (such as x=10)
Examples:
String name = "SparkDatabox"; int value = 1000; float z = 3.4F;
We can declare a variable without assigning the value to it. The value can be assigned to the variable later as well. For example,
int value; value = 1000;
The above one gives the same meaning as the previous one.
Display Variables
The println() method is used to display variables. To concatenate the variables with the strings, we use ‘+’ operator.
Example:
String name = "Databox"; System.out.println("Spark"+name);
For numeric values, the ‘+’ operator works as a mathematical operator to add the numbers.
Example:
int x = 2; int y = 3; System.out.println(x+y);
Declaring many
variables
We can declare more than one variable of the same type with a comma-separated.
Example:
int x = 2, y = 3, z = 4; System.out.println(x+y+z);
Java Identifiers
All Java variables should be identified with unique names. These unique names are known as identifiers. There are some set of rules for constructing names for variables such as,