Section 1: Variables in Java

We know different Data Types in java, but where can we store values in java? To do the same we have different types of variables in java.

Variables in Java
Java variables are used to store values. To declare the variable user needs to specify type i.e. String, int, or float. Then the user can assign the value to the variable.

Example:
String user = “ugtworld”;
Here String is a type of variable, user is name of the variable and ugtworld is the value of that variable.
If we print this variable as System.out.println(user); we will get ugtworld as an output.


Making variable as final:
If the user adds the final keyword before the variable then the value of that variable can not be changed further. It means whatever value is given the first time will remain the same throughout the program until the program ends.

Example :
final String user = “ugtworld”;
If we try to change the user value we will get a compile-time error as shown in the below program.

Variables in Java

Types of Variables in Java

Variables in java are of 3 types
1.Static or class variables
2.Instance variables
3.Local variables

Static or class variables:

1.Static or class level variables are those variables that are declared within the class outside the method with keywords as static.

2.These variables are accessible throughout the class or outside the class if public.

3.Users don’t need to initialize the static variables its default value will be null (if a string) or 0 (if int). That default values we have already seen in Data Types.

4.Static variables are created at the start of the program execution and destroyed when the program is terminated.

5.We can access static variables within the class directly without creating any object.

6.Static variables outside the class can be directly accessed by class name without creating any object.

Following is the example for static variables within the same class, outside the class.

Variables in Java

Instance and local variables are available on page-2

-A blog by Shwetali Khambe

Related Posts