Java Variables
Variables are containers for storing data values.
In Java, there are different types of variable.
String - stores text. String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals
float - stores floating point numbers, with decimals, such as 9.99 or -1.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)
Variable Declaration
Syntax -:
type name_of_variable = value;
type -: String/ int/ float/ char/ boolean
name_of_variable -: such as x,x1,y
equal sign used to assign values to the variable.
ex -: String name= "mala"
int age=24;
float decnum=5.99f;
char letter ='D';
bloolean myBool= true;
Final Variables
We declare the variable as "final" or "constant", which means unchangeable and read-only.
you can add the "final" keyword if you don't want to overwrite existing values
ex -: final int num=15;
num =25 // will generate an error: can't assign a value to a final variable
The general rules for constructing names for variables (unique identifiers) are _:
- Names can contain letters, digits, underscores, and dollar signs
- Names must begin with a letter
- Names should start with a lowercase letter and it cannot contain white space
- Names can also begin with $ and _ (but we will not use it in this tutorial)
- Names are case sensitive ("myVar" and "myvar" are different variables)
- Reserved words (like Java keywords, such as
int
orboolean
) cannot be used as names
Comments
Post a Comment