{"id":76179,"date":"2020-02-06T11:22:22","date_gmt":"2020-02-06T05:52:22","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=76179"},"modified":"2020-02-06T11:22:22","modified_gmt":"2020-02-06T05:52:22","slug":"variables-in-java","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/","title":{"rendered":"Variables in Java &#8211; Explore its Types with Syntax and Examples!"},"content":{"rendered":"<p>Today, in this tutorial we will get to know about the role of Variables in Java and also we will have a look at the types of Java Variables along with some examples that will further help you to write your programs easily. So let&#8217;s start with what Java Variables are all about.<\/p>\n<h3>Variables in Java<\/h3>\n<p>A variable is a <strong>named memory location<\/strong> that holds the data value of a particular data type. A variable in Java is a kind of <strong>container<\/strong> that contains the value during program execution.<\/p>\n<p>Variable is a basic unit of storage in a program that represents reserved storage locations, whose values can be manipulated during the execution of a program. We assign a variable with a datatype.<\/p>\n<p>As the name itself suggests, the word <strong>variable<\/strong> can be broken down into 2 words- <strong>\u201cvary\u201d + \u201cable\u201d<\/strong>, which means the value of variables can change.<\/p>\n<ul>\n<li>Variables are also called <strong>symbolic variables<\/strong> because they are named.<\/li>\n<li>A variable is a memory area, and this memory location gets affected when any manipulation or operation is done on the variables.<\/li>\n<li>In Java, we should declare all the variables before using them.<\/li>\n<li>Each variable has a specific data type, which determines its memory and the type of data that it can store.<\/li>\n<li>Variables are typically used to store information ranging from text, codes <em>(e.g. state code, city code, etc.<\/em>) to numbers, temporary results of complex calculations, etc.<\/li>\n<\/ul>\n<p><strong>Example:<\/strong><\/p>\n<p>For instance, the following statement declares a variable country_code of type int-<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">int country_code ;<\/pre>\n<p><em><strong>Hold On! Before learning further, it is necessary for you to first learn about <a href=\"https:\/\/techvidvan.com\/tutorials\/data-types-in-java\/\">Data types in Java.<\/a><\/strong><\/em><\/p>\n<h4>Declaration of a Variable<\/h4>\n<p>To declare the variable, we must specify the data type followed by the unique name of the variable.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>The declaration of a variable generally takes the following syntax:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">dataType variableName ;<\/pre>\n<p>Where dataType is a type-specifier which is any Java data type and <em>variableName<\/em> is the unique name of a variable. A variable name is an<strong> identifier<\/strong>, thus all the naming conventions\/rules of an identifier must be applied for naming a variable.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">double payRate ;<\/pre>\n<p>Here, payRate is a variable of double data type.<\/p>\n<p>Some other variable declarations are &#8211;<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">float area ;\nchar grade ;\nString sentence ;<\/pre>\n<p>When more than one variable of the same data type needs to be defined, we use a type specifier followed by a comma-separated list of variables.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">double salary, wage, portNumber ;\nint month, day, year ;\nlong length, radius ;<\/pre>\n<p><em><strong>Note: While naming the variables, make sure to follow the naming conventions and rules of identifiers which are as follows:<\/strong><\/em><\/p>\n<p>1. The variable names cannot contain white spaces, for example, <strong>long dist ance = 1000<\/strong>; is invalid because the variable name has a space in it.<\/p>\n<p>2. A variable name can begin with a special character dollar <strong>($)<\/strong> and underscore <strong>( _ )<\/strong>.<\/p>\n<p>3. The first letter of a variable cannot be a digit.<\/p>\n<p>4. A variable name should begin with a lowercase letter, for example, int number. For lengthy variable names having more than one word, we can use<strong> camelCase<\/strong>, <em>for example, int salaryPerDay;<\/em> <em>float rateOfInterest; ,etc.<\/em> are valid.<\/p>\n<p>5. We cannot use keywords like <em>int, for, while, class, etc<\/em> as a variable name.<\/p>\n<p>6. Variable names are case-sensitive in Java.<\/p>\n<h3>Initialization of a Variable<\/h3>\n<p>We have already discussed how to declare a variable. But this does not provide the initial value to the variable that is, the variable remains uninitialized. Now we will discuss how to initialize a variable that is providing a value to a variable.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<p>We can assign a value to a variable by the following syntax:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">variableName = value ;<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">payRate = 2500;<\/pre>\n<p>Combining the declaration and initialization, we can write-<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">dataType variableName = value ;<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">double area = 378.87 ;<\/pre>\n<p>The following diagram illustrates the variable declaration and its memory allocation:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/java-variable-declaration-its-memory-allocation.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76232\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/java-variable-declaration-its-memory-allocation.jpg\" alt=\"java-variable-declaration-&amp;-its-memory-allocation\" width=\"648\" height=\"348\" \/><\/a><\/p>\n<p><strong>Code Snippet:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class VariableTutorial\n{\n  public static void main(String args[])\n  {\n    \/\/ Declaring and initializing the variables\n    long hoursWorked = 50;\n    double payRate = 40.0, taxRate = 0.10, taxPayable;\n    System.out.println(\"Hours Worked: \" +hoursWorked);\n    \/\/ Performing operations on variables\n    System.out.println(\"Payment Amount: \" + (hoursWorked * payRate));\n    taxPayable = hoursWorked * payRate * taxRate;\n    System.out.println(\"Tax Payable: \" +taxPayable);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Hours Worked: 50<br \/>\nPayment Amount: 2000.0<br \/>\nTax Payable: 200.0<\/div>\n<h4>Initial Values of Variables<\/h4>\n<p>There is <strong>no default value for local variables<\/strong>, so we have to assign a value to a local variable before its first use. However, each class variable, instance variable or array component is initialized with a <strong>default<\/strong> value when it is created:<\/p>\n<table class=\"tv-table-center\">\n<tbody>\n<tr>\n<td><b><i>Type<\/i><\/b><\/td>\n<td><b><i>Initial\/Default value<\/i><\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">byte<\/span><\/td>\n<td><span style=\"font-weight: 400\">0(Zero) of byte type<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">short<\/span><\/td>\n<td><span style=\"font-weight: 400\">0(Zero) of byte type<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">int<\/span><\/td>\n<td><span style=\"font-weight: 400\">0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">long<\/span><\/td>\n<td><span style=\"font-weight: 400\">0L<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">float<\/span><\/td>\n<td><span style=\"font-weight: 400\">0.0F<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">double<\/span><\/td>\n<td><span style=\"font-weight: 400\">0.0D<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">char<\/span><\/td>\n<td><span style=\"font-weight: 400\">null character i.e., \u2018\\u0000\u2019<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">boolean<\/span><\/td>\n<td><span style=\"font-weight: 400\">false<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">All reference types<\/span><\/td>\n<td><span style=\"font-weight: 400\">null<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p style=\"text-align: left\">Code to understand the concept of default values of class or instance variables:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class DefaultValues\n{\n  \/\/declaring Primitive types\n  byte byteNum;\n  short shortNum;\n  int intNum;\n  long longNum;\n  float floatNum;\n  double doubleNum;\n  char charValue;\n  boolean flag;\n  DefaultValues object1;\n  \/\/declaring Reference types\n  String mySentence;\n  public void getDefaultValues()\n  {\n    System.out.println(\"The Default value of byte is: \" +byteNum);\n    System.out.println(\"The Default value of short is: \" +shortNum);\n    System.out.println(\"The Default value of Int is: \" +intNum);\n    System.out.println(\"The Default value of long is: \" +longNum);\n    System.out.println(\"The Default value of float is: \" +floatNum);\n    System.out.println(\"The Default value of double is: \" +doubleNum);\n    System.out.println(\"The Default value of char is: \" +charValue);\n    System.out.println(\"The Default value of boolean is: \" +flag);\n    System.out.println(\"The Default value of String is: \" +mySentence);\n    System.out.println(\"The Default value of Object is: \" +object1);\n\n  }\n  public static void main(String args[])\n  {\n    DefaultValues object = new DefaultValues();\n    object.getDefaultValues();\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">The Default value of byte is: 0<br \/>\nThe Default value of short is: 0<br \/>\nThe Default value of Int is: 0<br \/>\nThe Default value of long is: 0<br \/>\nThe Default value of float is: 0.0<br \/>\nThe Default value of double is: 0.0<br \/>\nThe Default value of char is:<br \/>\nThe Default value of boolean is: false<br \/>\nThe Default value of String is: null<br \/>\nThe Default value of Object is: null<\/div>\n<h3>Types of Java Variables<\/h3>\n<p>Java allows the variables to be declared at any place or within any block. That is, in Java, we can declare the variables at many places, we can declare them either at the start of the program or inside any classes, method\/functions or inside the main method.<\/p>\n<p>Scope determines which variables are visible to other parts of your program and also what is the lifetime of those variables. Depending upon the scope, visibility, and access to the variables, they can be classified under 3 categories.<\/p>\n<p>The 3 types of variables in Java are &#8211;<\/p>\n<ol>\n<li>Local Variables<\/li>\n<li>Instance Variables<\/li>\n<li>Static Variables<\/li>\n<\/ol>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/types-of-variables-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-76233\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/02\/types-of-variables-in-java.jpg\" alt=\"types-of-variables-in-java\" width=\"802\" height=\"420\" \/><\/a><\/p>\n<h4>1. Local Variables in Java<\/h4>\n<p>A local variable in Java is a variable that we declare inside a body of a method, block or a constructor. We can use the local variable only within that method and the other methods of the class are unaware of the existence of this variable.<\/p>\n<p>A block starts with an opening curly brace and ends with a closing curly brace. The scope of a local variable is restricted to a particular block. Its lifetime is within the parenthesis in which it is declared.<\/p>\n<p>That is, it is created when a function is called or a block is entered and gets destroyed once it exits that method, block or constructor.<\/p>\n<ul>\n<li>We cannot define the local variables as static&#8221;. We can use the <em>\u201cfinal\u201d<\/em> keyword before a local variable.<\/li>\n<li>The scope and access of these variables exist only inside the block in which we declare them.<\/li>\n<li>We cannot use access modifiers for the local variables.<\/li>\n<li>Internally, a stack implementation is used to implement the local variables.<\/li>\n<li>Initialization of Local Variable is necessary &#8211; there is no default value for local variables, so we should declare a local variable and assign it with an initial value before its first use.<\/li>\n<li>If we do not initialize the value of a local variable, then we will get a Compile Time Error.<\/li>\n<\/ul>\n<h4>Declaration of a Local Variable<\/h4>\n<p>Every local variable is declared within a block { \u2026 }. We can also declare local variables in the header of a \u201cfor\u201d statement.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">for(int i = 10 ;i &gt;= 1; i--)\n        {\n                  \/\/ Body of for loop\n        }<\/pre>\n<p>In the above example, int i = 10 is a declaration of a local variable i. Its scope is only limited to the \u201cfor\u201d loop.<\/p>\n<p><strong>Syntax of a Local Variable:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">class ClassName\n{\n       methodName(){\n             &lt;DataType&gt; localVariableName;\n             localVariableName = value;\n             }\n}<\/pre>\n<p>Here, methodname is the name of the method, DataType refers to the data type of local variables like<em> int, float, long, double, etc<\/em> and localVariableName is the name of the local variable and value is the initial value of the local variable.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">double area()\n    {\n   \tint length=10; \/\/local variable\n   \tint breadth = 5; \/\/local variable\n   \tdouble areaOfRectangle = length * breadth; \/\/local variable\n   \treturn areaOfRectangle;\n    } \/\/ scope of all local variables ends here.<\/pre>\n<p><strong>Code Snippet 1:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class EmployeeSalary\n{\n  public void getSalary()\n  {\n      long salary = 30000; \/\/declaring a local variable\n  }\n  public static void main(String args[])\n  {\n      System.out.println(\"Salary of the Employee is: \" +salary);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Exception in thread &#8220;main&#8221; java.lang.Error: Unresolved compilation problem:<br \/>\nsalary cannot be resolved to a variable<br \/>\nat EmployeeSalary.main(EmployeeSalary.java:10)<\/div>\n<p><strong>Reason for error:<\/strong> Accessing local variable \u201csalary\u201d outside its scope(function getSalary()) gives an error.<\/p>\n<p><strong>Code Snippet 2:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class EmployeeSalary\n{\n  public void getSalary()\n  {\n    \/\/declaring a local variable\n    long salary;\n    \/\/declaring and initializing local variables\n    int workingDaysInAMonth = 25, salaryPerDay = 1000; salary = workingDaysInAMonth * salaryPerDay ;\n    System.out.println(\"Salary of the Employee is: \" +salary);\n  }\n  public static void main(String args[])\n  {\n      EmployeeSalary employee = new EmployeeSalary();\n      \/\/accessing local variable by calling method in which it is present\n      employee.getSalary();\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Salary of the Employee is: 25000<\/div>\n<h4>2. Instance Variables in Java<\/h4>\n<p>A variable that is declared inside the class but outside any method, constructor or block body is called an instance variable. An instance variable is a non-static variable that is, we can not declare it as static.<\/p>\n<p>It is called an instance variable because its value is instance-specific (related to objects) and is not shared with other instances\/objects as each object of the class has its own set of values for these non-static variables.<\/p>\n<ul>\n<li>As we declare an instance variable in a class, these variables are created when an object of the class is created with the use of a \u201cnew\u201d keyword and destroyed when the object is destroyed.<\/li>\n<li>We can access instance variables only by creating objects. Also, we can use these variables using the <strong>\u201cthis\u201d<\/strong> pointer inside the same class.<\/li>\n<li>We can also declare instance variables with access specifiers (private, public or default). If we do not explicitly set any access specifier for the instance variables then Java assumes them as default access specifiers.<\/li>\n<li>It is not necessary to initialize an instance variable. If we do not initialize it with a value, it gets a default value. We have already discussed the list of the default values of instance variables in the introductory part of the variables, in this article.<\/li>\n<li>Heap Allocation is used to store the instance variables and a slot of memory is created for each instance variable value. Each object has its own copy of the instance variables that is, these variables cannot be shared among objects.<\/li>\n<li>The instance variables are visible to all methods, constructors, and blocks in the class. Normally, it is recommended that we should declare the instance with a \u201cprivate\u201d access specifier.<\/li>\n<\/ul>\n<h4>Declaration of an instance variable<\/h4>\n<p>We can declare instance variables inside a class. We can also declare them outside a method, block or constructor.<\/p>\n<p><strong>Syntax of an Instance Variable:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">class ClassName\n{\n       &lt;DataType&gt; instanceVariableName;\n       instanceVariableName = value;\n       \/\/ class body\n}<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">Class AreaofShapes\n{\n  \/\/These are instance variables, present inside the class\n   \t\tdouble rectangleArea;\n   \t\tdouble squareArea;\n   \t\tdouble circleArea;\n}<\/pre>\n<p><strong>Code Snippet:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class AreaOfShapes\n{\n  \/\/Declaring instance variables\n  double breadth;\n  double length;\n  double areaOfRectangle;\n  double areaOfSquare;\n\n  public static void main(String args[])\n  {\n      \/\/Creating First Object area1\n      AreaOfShapes area1 = new AreaOfShapes();\n      \/\/Accessing instance variables through the first object\n      area1.length = 50;\n      area1.breadth = 25;\n      area1.areaOfRectangle= area1.length * area1.breadth;\n\n      \/\/Displaying details for first object\n      System.out.println(\"Details from the first object-\");\n      System.out.println(\"Length of Rectangle: \" +area1.length);\n      System.out.println(\"Breadth of Rectangle: \" +area1.breadth);\n      System.out.println(\"Area of Rectangle: \" +area1.areaOfRectangle);\n\n      \/\/Creating second Object area2\n      AreaOfShapes area2 = new AreaOfShapes();\n      \/\/Accessing instance variables through the second object\n      area2.length = 75.5;\n      area2.breadth = 68;\n      area2.areaOfRectangle= area2.length * area2.breadth;\n\n      \/\/Displaying details for the second object\n      System.out.println(\"\\nDetails from the second object-\");\n      System.out.println(\"Length of Rectangle: \" +area2.length);\n      System.out.println(\"Breadth of Rectangle: \" +area2.breadth);\n      System.out.println(\"Area of Rectangle: \" +area2.areaOfRectangle);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Details from the first object-<br \/>\nLength of Rectangle: 50.0<br \/>\nBreadth of Rectangle: 25.0<br \/>\nArea of Rectangle: 1250.0Details from the second object-<br \/>\nLength of Rectangle: 75.5<br \/>\nBreadth of Rectangle: 68.0<br \/>\nArea of Rectangle: 5134.0<\/div>\n<p>From the above program, it is clear that each instance (object) of the class has its own copy of the instance variable.<\/p>\n<p>We changed the value of instance variables using the object \u201carea2\u201d in the program but there was no effect or change in the values of the other object \u201carea1\u201d. This shows that objects have their own (separate) copy of the instance variable.<\/p>\n<h4>3. Static Variables in Java<\/h4>\n<p>A variable that is declared inside a class but not inside the method, constructor or a block, with the <strong>static keyword<\/strong> is called <strong>static or class variable<\/strong>.<\/p>\n<p>Static variables are also called class variables because they are associated with the class and are common for all the instances of the class. That is, one copy of the static variable is shared among all objects of the class.<\/p>\n<p>For example, if we create multiple objects of a class and access the static variable using objects, it will be common for all, that is, the changes made to the variable using one of the objects would reflect when we access it through the other objects of the class.<\/p>\n<ul>\n<li>Static variables are created at the start of program execution and get destroyed automatically after the execution of the program.<\/li>\n<li>Unlike instance variables, there is only one copy of a static variable per class, irrespective of the number of objects we create from the class.<\/li>\n<li>The initialization of static variables is not mandatory. If we do not initialize it with a value, it gets a default value similar to the instance variables.<\/li>\n<li>Static variables can be declared as public\/private, final, and static. These variables are the constant variables that never change from their initial values.<\/li>\n<li>Static memory allocation is very helpful to store the static\/class variables.<\/li>\n<li>We can access the static variables by calling it with the class name, that is <strong>ClassName.variableName<\/strong>. We can also directly access the static variables inside static methods and static blocks.<\/li>\n<li>The visibility of the static variable is similar to instance variables. However, we mostly declare the static variables as public, since they must be available for all objects of the class.<\/li>\n<li>The values of static variables can also be assigned during the declaration or within the constructor. Also, we can assign the values in special static initializer blocks.<\/li>\n<\/ul>\n<p><strong>Note:<\/strong><\/p>\n<ul>\n<li>If we try to access the static variable through an object, the compiler will show the warning message but will not halt the program. The compiler will automatically replace the object name with the class name.<\/li>\n<li>If we access the static variable without the class name, the compiler will automatically add the class name.<\/li>\n<\/ul>\n<p><strong>Syntax of a Static Variable:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">class ClassName{\nstatic &lt;DataType&gt; &lt;variable_name&gt;;\n}<\/pre>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">class MyClass{\nstatic int number; \/\/number is a static variable\n}<\/pre>\n<p><strong>Code Snippet:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\">public class Student\n{\n  \/\/Declaring static variables inside the class\n  public static int marks;\n  public static String studentName = \"John\";\n\n  public static void main(String args[])\n  {\n    \/\/accessing static variable without creating object\n    Student.marks = 80;\n    System.out.println(\"The marks of student \"+Student.studentName +\"are:     \"+Student.marks);\n\n    \/\/creating 3 objects of the class\n    Student student1 = new Student();\n    Student student2 = new Student();\n    Student student3 = new Student();\n\n    \/\/Accessing the statc variable through objects\n    System.out.println(student1.studentName);\n    System.out.println(student2.studentName);\n    System.out.println(student3.studentName);\n\n    \/\/We can directly access the static variable like this\n    System.out.println(marks);\n\n    \/\/changing the value of the static variable by 1 object\n    student1.studentName= \"Sam\";\n\n    \/\/ change made by one object is reflected to all other objects\n    System.out.println(student1.studentName);\n    System.out.println(student2.studentName);\n    System.out.println(student3.studentName);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">The marks of student John are: 80<br \/>\nJohn<br \/>\nJohn<br \/>\nJohn<br \/>\n80<br \/>\nSam<br \/>\nSam<br \/>\nSam<\/div>\n<p>As we can see, all three objects (student1, student2, student3) displays the same output irrespective of the object (student1) through which it has been accessed. This is the reason why we can access the static variables directly without using objects like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">System.out.println(static_Variable_Name);<\/pre>\n<blockquote><p><strong><em>Do note that only static variables can be accessed like this. We cannot access the instance and local variables like this!!<\/em><\/strong><\/p><\/blockquote>\n<h3>Summary<\/h3>\n<p>Here we came to the end of our blog on Java Variables. Now you know that variables in Java play an extremely important role in programming. They are very useful for writing programs.<\/p>\n<p>In this article, we have discussed the Java variables and their types in detail along with their respective examples, syntax and logical codes so that you can easily understand them. Now, you can use these Java variables in your programs flexibly.<\/p>\n<p>If you have any queries, do let us know with the help of the comment section below.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Today, in this tutorial we will get to know about the role of Variables in Java and also we will have a look at the types of Java Variables along with some examples that&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":76233,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[1596,1597,1598,1599,1600,1601,1602],"class_list":["post-76179","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-instance-variable-in-java","tag-java-variables","tag-local-variables-in-java","tag-static-variable-in-java","tag-types-of-java-variables","tag-variables-in-java","tag-what-are-java-variables"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Variables in Java - Explore its Types with Syntax and Examples! - TechVidvan<\/title>\n<meta name=\"description\" content=\"Java Variables are the storage unit that contains the value during a program execution. Learn about types of variables in Java with the help of syntax &amp; examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Variables in Java - Explore its Types with Syntax and Examples! - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Java Variables are the storage unit that contains the value during a program execution. Learn about types of variables in Java with the help of syntax &amp; examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-02-06T05:52:22+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/types-of-variables-in-java.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"13 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Variables in Java - Explore its Types with Syntax and Examples! - TechVidvan","description":"Java Variables are the storage unit that contains the value during a program execution. Learn about types of variables in Java with the help of syntax & examples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/","og_locale":"en_US","og_type":"article","og_title":"Variables in Java - Explore its Types with Syntax and Examples! - TechVidvan","og_description":"Java Variables are the storage unit that contains the value during a program execution. Learn about types of variables in Java with the help of syntax & examples.","og_url":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-02-06T05:52:22+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/types-of-variables-in-java.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"13 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Variables in Java &#8211; Explore its Types with Syntax and Examples!","datePublished":"2020-02-06T05:52:22+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/"},"wordCount":2192,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/types-of-variables-in-java.jpg","keywords":["Instance Variable in Java","Java Variables","local variables in java","Static Variable in Java","Types of Java Variables","variables in java","what are Java variables"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/variables-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/","url":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/","name":"Variables in Java - Explore its Types with Syntax and Examples! - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/types-of-variables-in-java.jpg","datePublished":"2020-02-06T05:52:22+00:00","description":"Java Variables are the storage unit that contains the value during a program execution. Learn about types of variables in Java with the help of syntax & examples.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/variables-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/types-of-variables-in-java.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/02\/types-of-variables-in-java.jpg","width":802,"height":420,"caption":"types-of-variables-in-java"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Variables in Java &#8211; Explore its Types with Syntax and Examples!"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/76179","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=76179"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/76179\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/76233"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=76179"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=76179"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=76179"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}