{"id":2669,"date":"2017-05-25T00:13:48","date_gmt":"2017-05-24T18:43:48","guid":{"rendered":"http:\/\/www.java2blog.com\/?p=2669"},"modified":"2023-11-09T22:44:47","modified_gmt":"2023-11-09T17:14:47","slug":"variables-in-java","status":"publish","type":"post","link":"https:\/\/java2blog.com\/variables-in-java\/","title":{"rendered":"Variables In Java Programming"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#Introduction\">Introduction<\/a><\/li><li><a href=\"#What_are_variables_in_java\">What are variables in java?<\/a><\/li><li><a href=\"#How_to_Initialize_Variables\">How to Initialize Variables?<\/a><\/li><li><a href=\"#What_are_the_different_types_of_variables_in_java\">What are the different types of variables in java?<\/a><ul><li><a href=\"#Local_variable\">Local variable<\/a><\/li><li><a href=\"#Instance_variable\">Instance variable<\/a><\/li><li><a href=\"#Static_variable\">Static variable<\/a><\/li><\/ul><\/li><li><a href=\"#Use_Cases_for_different_Variables_in_Java\">Use Cases for different Variables in Java<\/a><\/li><\/ul><\/div>\n\n<h2><span id=\"Introduction\">Introduction<\/span><\/h2>\n<p><span data-preserver-spaces=\"true\">In this post, we will look at Variables in Java Programming. It is an essential topic that will provide an insight into how a user stores and handles the data in the computer&#8217;s memory to use it efficiently.<\/span><\/p>\n<p><span data-preserver-spaces=\"true\">So, we will cover everything from the definition to the declaration and the different types of variables in java.<\/span><\/p>\n<h2><span id=\"What_are_variables_in_java\">What are variables in java?<\/span><\/h2>\n<p><span data-preserver-spaces=\"true\">In Java, variables are nothing but a named memory location. Variables in java stores values of elements while the program executes. All operations done on the variable affects the memory location.<\/span><\/p>\n<p><span data-preserver-spaces=\"true\">Simply put, Variables are helpful to programmers to handle data that can be manipulated by the program during execution as well. Variables in java are\u00a0<\/span><strong><span data-preserver-spaces=\"true\">Strongly typed<\/span><\/strong><span data-preserver-spaces=\"true\">; hence they all must have a datatype followed by an identifier.<\/span><\/p>\n<p><span data-preserver-spaces=\"true\">Each variable has a specific\u00a0<\/span><a class=\"editor-rtfLink\" href=\"https:\/\/java2blog.com\/data-types-in-java\/\" target=\"_blank\" rel=\"noopener\"><span data-preserver-spaces=\"true\">Data Type<\/span><\/a><span data-preserver-spaces=\"true\">\u00a0that defines the size and layout of the variable&#8217;s memory.<\/span><\/p>\n<p><b>How to Declare a Variable?<\/b><\/p>\n<p>We can declare a variable as below:<\/p>\n<pre class=\"lang:java decode:true\">data_type variable_name = value;<\/pre>\n<p>Here is the example:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"aligncenter size-full wp-image-9053\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/variable.jpg\" alt=\"variable declaration\" width=\"311\" height=\"192\" srcset=\"https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/variable.jpg 311w, https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/variable-300x185.jpg 300w\" sizes=\"(max-width: 311px) 100vw, 311px\" \/><\/p>\n<blockquote><p><span style=\"font-size: 1.2em;\">&#x1f4a1; <strong>Did you know?<\/strong><\/span><\/p>\n<p>Assigning value is optional while declaring variables. You can declare variable and assign value to it later in program.<\/p><\/blockquote>\n<p>Variable has a name that is used to identify it. The name of the variable is known as the variable&#8217;s identifier.<\/p>\n<p>There are some naming conventions that you need to follow while declaring a variable.<\/p>\n<ul>\n<li>You can use <code>A to Z<\/code> or <code>a to z<\/code>.<\/li>\n<li>You can use <code>0 to 9.<\/code><\/li>\n<li>You can use special symbol<code>$<\/code> and <code>_<\/code> to declare a variable.<\/li>\n<li>You can not start a variable name with number.<\/li>\n<li>You can not have spaces in variable name.<\/li>\n<li>You can not use reserved keywords in variable name.<\/li>\n<li>Variables names are case sensitive.<\/li>\n<\/ul>\n<p><strong>Examples:<\/strong><\/p>\n<pre class=\"lang:java decode:1 \">int age;\r\nString person_name;\r\n<\/pre>\n<p>You can declare variables in groups as well like this:<\/p>\n<pre class=\"lang:java decode:1 \">int age,weight;\r\nString person_name,gender;<\/pre>\n<h2><span id=\"How_to_Initialize_Variables\">How to Initialize Variables?<\/span><\/h2>\n<p>Each variable holds some data which it describes. We use <code>=<\/code> operator to assign value to a variable.<\/p>\n<pre class=\"lang:java decode:1 \">int age=30,weight=60;\r\nString person_name = \"John\";\r\n<\/pre>\n<p>Compiler will give compile time error if value does not match with the datatype of the variable.<br \/>\n<strong>For example:<\/strong><br \/>\nYou can not assign String literal to int data type.<\/p>\n<pre class=\"lang:java decode:1 \">\/\/ Compilation error\r\nint age= \"NA\"\r\n<\/pre>\n<p>Let&#8217;s understand it with the help of simple program:<\/p>\n<pre class=\"java\" name=\"code\">package org.arpit.java2blog;\r\n\r\npublic class VariableDemo {\r\n    int a;  \/\/ Instance variable\r\n    static int b=20; \/\/ static variable\r\n\r\n    public void print()\r\n    {\r\n        int c=10; \/\/ local variable\r\n        System.out.println(\"Method local variable: \"+c);\r\n    }\r\n\r\n    public static void main(String args[])\r\n    {\r\n        VariableDemo demo=new VariableDemo();\r\n        System.out.println(\"Instance variable: \"+demo.a); \/\/ Printing Instance variable\r\n        System.out.println(\"Static variable: \"+b);   \/\/ Printing static variable\r\n        demo.print();  \/\/Printing local variable using print method.\r\n    }\r\n}\r\n<\/pre>\n<p>When you run above program, you will get the below <strong>Output:<\/strong><\/p>\n<pre class=\"content-box-green\">Instance variable: 0\r\nStatic variable: 20\r\nMethod local variable: 10<\/pre>\n<h2><span id=\"What_are_the_different_types_of_variables_in_java\"><b>What are the different types of variables in java?<\/b><\/span><\/h2>\n<p>There are majorly three <code>Types of Variables<\/code> in use in Java Programming.<\/p>\n<ol>\n<li><strong>Local Variable<\/strong><\/li>\n<li><strong>Instance Variable<\/strong><\/li>\n<li><strong>Static Variable<\/strong><\/li>\n<\/ol>\n<p>Let&#8217;s have a look at each type in detail with some examples.<\/p>\n<h3><span id=\"Local_variable\">Local variable<\/span><\/h3>\n<p><span data-preserver-spaces=\"true\">A variable declared inside a\u00a0<\/span><strong><span data-preserver-spaces=\"true\">method<\/span><\/strong><span data-preserver-spaces=\"true\">\u00a0or a\u00a0<\/span><strong><span data-preserver-spaces=\"true\">block<\/span><\/strong><span data-preserver-spaces=\"true\">\u00a0is termed a Local Variable. In Java, Local Variables can also be declared in a block within a method surrounded by curly braces; such variables are known as\u00a0<\/span><strong><span data-preserver-spaces=\"true\">Block Level Local Variables<\/span><\/strong><span data-preserver-spaces=\"true\">.<\/span><\/p>\n<p><span data-preserver-spaces=\"true\">In such a case, the scope of the variable, both in terms of its access and the presence of the variable in the memory, will be valid throughout the block only and not through the entire program. We will understand this with an example.<\/span><\/p>\n<p><strong><span data-preserver-spaces=\"true\"><code>Note:<\/code><\/span><\/strong><span data-preserver-spaces=\"true\"> It is mandatory to initialize the local variables; otherwise, the compiler will throw an error about it. Moreover, we cannot have <code>Keywords<\/code> like public, private, static associated with Local Variables.<\/span><\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"lang:default decode:true\">public class LocalVariablesDemo {\r\npublic static void main(String args[]) {\r\n\r\nint x = 10; \/\/ Method Level Local Variable\r\n{\r\nint y = 20; \/\/ Block Level Local Variable\r\nSystem.out.println(\"Block Level Local Varibale y: \"+y);\r\n}\r\n\r\nSystem.out.println(\"Method Level Local Variable x: \"+x);\r\n}\r\n}\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"wp-image-17829 aligncenter\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-239-300x50.png\" alt=\"\" width=\"612\" height=\"102\" srcset=\"https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-239-300x50.png 300w, https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-239-800x134.png 800w, https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-239-768x128.png 768w, https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-239.png 814w\" sizes=\"(max-width: 612px) 100vw, 612px\" \/><\/p>\n<h3><span id=\"Instance_variable\">Instance variable<\/span><\/h3>\n<p><span data-preserver-spaces=\"true\">A variable declared at the class level but outside a method or a block is an Instance variable. It is not mandatory to initialize instance variables. Instead, an Instance variable in Java is initialized when an instance of the class or an\u00a0<\/span><a class=\"editor-rtfLink\" href=\"https:\/\/java2blog.com\/object-class-java\/\" target=\"_blank\" rel=\"noopener\"><span data-preserver-spaces=\"true\">object<\/span><\/a><span data-preserver-spaces=\"true\">\u00a0is created.<\/span><\/p>\n<p><span data-preserver-spaces=\"true\">All instance variables will be, by default, initialized by JVM. While allocating space for an object, a slot for each Instance Variable is also created. Thus, we can say Instance Variables are present in memory until the object&#8217;s lifetime and are visible to all methods and blocks in the class.<\/span><\/p>\n<p><span data-preserver-spaces=\"true\">We can use Keywords and Access Modifiers with Instance Variables to restrict the visibility of the variables. Let us understand the use of instance variable with example.<\/span><\/p>\n<pre class=\"\">public class InstanceDemo \r\n{\r\nint g; \/\/ Instance Variable with Default Value 0\r\npublic static void main(String args[]) \r\n{\r\nInstanceDemo obj=new InstanceDemo();\r\nSystem.out.println(\"Instance variable g: \"+obj.g);\r\n}\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"wp-image-17859 alignleft\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-240-300x76.png\" alt=\"\" width=\"391\" height=\"99\" srcset=\"https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-240-300x76.png 300w, https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-240.png 484w\" sizes=\"(max-width: 391px) 100vw, 391px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>To access the value in the main method, we had to create the object or instance of the Class InstanceDemo; then, we used the dot operator with the object name to access the variable.<\/p>\n<p>If we had accessed it directly without creating the object, the compiler would throw an error: <code>non-static variable g cannot be referenced from a static context<\/code>. This error means that the main method is static, and we cannot access a non-static variable from a static method. It is mandatory to instantiate the class in this case.<\/p>\n<h3><span id=\"Static_variable\">Static variable<\/span><\/h3>\n<p><span data-preserver-spaces=\"true\">A variable that is declared as static and refers to shared property for all class objects is known as a Static variable. Static variables are also class-level variables that can be declared in a method but only in a\u00a0<\/span><strong><span data-preserver-spaces=\"true\">Static Method<\/span><\/strong><span data-preserver-spaces=\"true\">. We cannot declare static variables inside a Static Block.<\/span><\/p>\n<p><span data-preserver-spaces=\"true\">Static Variables in Java make the program memory efficient as static variables get memory allocation only once during class loading. In simple words, all objects of a class will share the same static variable or properties.<\/span><\/p>\n<p><span data-preserver-spaces=\"true\">Even if we create multiple objects or instances, static members are created only once. The static keyword denotes that a property belongs to the whole class rather than a method. Like Instance variables, Static members are also by default initialized by JVM. Let us understand the use of static variables with an example.<\/span><\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"lang:java decode:true \">public class StaticDemo \r\n{\r\nstatic int g; \/\/ Static Variable with Default Value 0\r\n\r\npublic static void main(String args[]) \r\n{\r\nSystem.out.println(\"Static Variable g: \"+g);\r\n\r\n\/\/Accesing static variable of another class using Class Name\r\nSystem.out.println(\"Static Variable of Class Demo: \"+ Demo.f);\r\n}\r\n}\r\nclass Demo\r\n{\r\n   static  int f; \/\/ static variable in another class.\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\" wp-image-17867 aligncenter\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-242-1-300x50.png\" alt=\"\" width=\"594\" height=\"99\" srcset=\"https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-242-1-300x50.png 300w, https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-242-1-800x133.png 800w, https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-242-1-768x128.png 768w, https:\/\/java2blog.com\/wp-content\/uploads\/2017\/05\/Screenshot-242-1.png 978w\" sizes=\"(max-width: 594px) 100vw, 594px\" \/><\/p>\n<p>Here, we print the values of static variables of class: StaticDemo and Demo. Interesting thing we see that, there is no need to instantiate the class Demo to access its static variable we can access it just using the Class name and dot operator with the variable name.<\/p>\n<h2><span id=\"Use_Cases_for_different_Variables_in_Java\">Use Cases for different Variables in Java<\/span><\/h2>\n<p><span data-preserver-spaces=\"true\">Let&#8217;s assume we are trying to store information related to a Student object. Now, we know that each Student&#8217;s names and roll number are unique to them and are different, so we can use\u00a0<\/span><strong><span data-preserver-spaces=\"true\">Instance Variables<\/span><\/strong><span data-preserver-spaces=\"true\">\u00a0to store that kind of information.<\/span><\/p>\n<p><span data-preserver-spaces=\"true\">Suppose we want to store information that will be the same for all Student Objects like their School Name, so in that case, we can use a\u00a0<\/span><strong><span data-preserver-spaces=\"true\">Static variable<\/span><\/strong><span data-preserver-spaces=\"true\">\u00a0so that every object shares the same variable. If we want to temporarily store any value related to the object for any operations, we can use\u00a0<\/span><strong><span data-preserver-spaces=\"true\">Local Variables<\/span><\/strong><span data-preserver-spaces=\"true\">.<\/span><\/p>\n<p>That&#8217;s all about Variables in Java Programming, you can try the above examples in your compiler to have a better understanding.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsIntroductionWhat are variables in java?How to Initialize Variables?What are the different types of variables in java?Local variableInstance variableStatic variableUse Cases for different Variables in Java Introduction In this post, we will look at Variables in Java Programming. It is an essential topic that will provide an insight into how a user stores and [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[180],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/2669"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=2669"}],"version-history":[{"count":1,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/2669\/revisions"}],"predecessor-version":[{"id":25352,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/2669\/revisions\/25352"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=2669"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=2669"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=2669"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}