Java Variables | ninjasquad
this tutorial, You’ll learn about java variables. Also learn final variable, rules for identifiers in java
Types of Java Variables
Variables are a box or container in a memory of device to store some data values in it.
In java, we have different types of java variables for different types of data are follows:
- int – This stores integers without decimal points.
- float – This stores floating point numbers.
- char – This stores single character in it and characters are surrounded with single qoutes like ‘A’ or ‘b’.
- string – This stores sequence of character or we can say text and it surrounded with double qoutes like “codeamy” or “divya”.
- boolean – This stores only two values are true or false.
Declaring of Variables
To create a java variables, we have to follow a syntax in which we have to specify the type of container and assign it data or value.
Syntax for variables
type variable_name = value;
where type is one of the type as we learn above like int, float, char, etc. variable_name is a unique name of container such as x or divya. so, we can uniquely identify it. The equal sign(=) is used to assign the value to variable_name.
int divya = 10;
We can also declare variable without assigning value, and assigning later.
x = 10;
System.out.println(x); // output : 10
We can also overwrite the assigned value like
int x = 10;
x = 20;
System.out.println(x); // output : 20
To print or display the value of java variables. Java language provide us the method println().
int divya = 27;
System.out.println(“roll no.” + divya);
To combine the string with variables, we use + operator.
String lastName = “Soni”;
String firstName = “Divya”;
String Name = firstName + lastName;
we also use + to combine one or more variables.
but in case of numeric it will add the variables. let us see in below example.
int a = 10;
int b = 20;
System.out.println(a+b); // output will be 30 not 10 20
Declare many variables
We can declare many variables in single line but with same type with use of comma(,) in between.
int x = 10, y = 20, z = 30;
System.out.println(x + y + z);
final in Java
final is a keyword or reserved word in java. It is also denote as constant. If you don’t want to change your assign value to a variableName then put final keyword in front of declaration.
final int x = 01;
x = 02; // output : It will generates error that you can’t reassign the final variable.
All variables are identified with unique name. These unique names are known as Identifiers. There certain rules for defining a valid identifiers otherwise it generates compile-time error.
Rules for identifiers in Java
In above article, we learn abut Java Variables and also learn about Java Identifiers, I think the whole article clear your doubt. In upcoming tutorials, I will share details of Java Data Types.