BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Variables in Java

By Chaitanya Singh | Filed Under: java

A variable is a name which is associated with a value that can be changed. For example when I write int i=10; here variable name is i which is associated with value 10, int is a data type that represents that this variable can hold integer values. We will cover the data types in the next tutorial. In this tutorial, we will discuss about variables.

How to Declare a variable in Java

To declare a variable follow this syntax:

data_type variable_name = value;

here value is optional because in java, you can declare the variable first and then later assign the value to it.

For example: Here num is a variable and int is a data type. We will discuss the data type in next tutorial so do not worry too much about it, just understand that int data type allows this num variable to hold integer values. You can read data types here but I would recommend you to finish reading this guide before proceeding to the next one.

int num;

Similarly we can assign the values to the variables while declaring them, like this:

char ch = 'A';
int number = 100;

or we can do it like this:

char ch;
int number;
...
ch = 'A';
number  = 100;

Variables naming convention in java

1) Variables naming cannot contain white spaces, for example: int num ber = 100; is invalid because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with a lower case letter, for example int number; For lengthy variables names that has more than one words do it like this: int smallNumber; int bigNumber; (start the second word with capital letter).
4) Variable names are case sensitive in Java.

Types of Variables in Java

There are three types of variables in Java.
1) Local variable 2) Static (or class) variable 3) Instance variable

Static (or class) Variable

Static variables are also known as class variable because they are associated with the class and common for all the instances of class. For example, If I create three objects of a class and access this static variable, it would be common for all, the changes made to the variable using one of the object would reflect when you access it through other objects.

Example of static variable

public class StaticVarExample {
   public static String myClassVar="class or static variable";
	
   public static void main(String args[]){
      StaticVarExample obj = new StaticVarExample();
      StaticVarExample obj2 = new StaticVarExample();
      StaticVarExample obj3 = new StaticVarExample();
      
      //All three will display "class or static variable"
      System.out.println(obj.myClassVar);
      System.out.println(obj2.myClassVar);
      System.out.println(obj3.myClassVar);

      //changing the value of static variable using obj2
      obj2.myClassVar = "Changed Text";

      //All three will display "Changed Text"
      System.out.println(obj.myClassVar);
      System.out.println(obj2.myClassVar);
      System.out.println(obj3.myClassVar);
   }
}

Output:

class or static variable
class or static variable
class or static variable
Changed Text
Changed Text
Changed Text

As you can see all three statements displayed the same output irrespective of the instance through which it is being accessed. That’s is why we can access the static variables without using the objects like this:

System.out.println(myClassVar);

Do note that only static variables can be accessed like this. This doesn’t apply for instance and local variables.

Instance variable

Each instance(objects) of class has its own copy of instance variable. Unlike static variable, instance variables have their own separate copy of instance variable. We have changed the instance variable value using object obj2 in the following program and when we displayed the variable using all three objects, only the obj2 value got changed, others remain unchanged. This shows that they have their own copy of instance variable.

Example of Instance variable

public class InstanceVarExample {
   String myInstanceVar="instance variable";
	
   public static void main(String args[]){
	InstanceVarExample obj = new InstanceVarExample();
	InstanceVarExample obj2 = new InstanceVarExample();
	InstanceVarExample obj3 = new InstanceVarExample();
		
	System.out.println(obj.myInstanceVar);
	System.out.println(obj2.myInstanceVar);
	System.out.println(obj3.myInstanceVar);

		
	obj2.myInstanceVar = "Changed Text";

		
	System.out.println(obj.myInstanceVar);
	System.out.println(obj2.myInstanceVar);
	System.out.println(obj3.myInstanceVar);
   }
}

Output:

instance variable
instance variable
instance variable
instance variable
Changed Text
instance variable

Local Variable

These variables are declared inside method of the class. Their scope is limited to the method which means that You can’t change their values and access them outside of the method.

In this example, I have declared the instance variable with the same name as local variable, this is to demonstrate the scope of local variables.

Example of Local variable

public class VariableExample {
   // instance variable
   public String myVar="instance variable";
    
   public void myMethod(){
    	// local variable
    	String myVar = "Inside Method";
    	System.out.println(myVar);
   }
   public static void main(String args[]){
      // Creating object
      VariableExample obj = new VariableExample();
    	
      /* We are calling the method, that changes the 
       * value of myVar. We are displaying myVar again after 
       * the method call, to demonstrate that the local 
       * variable scope is limited to the method itself.
       */
      System.out.println("Calling Method");
      obj.myMethod();
      System.out.println(obj.myVar);
   }
}

Output:

Calling Method
Inside Method
instance variable

If I hadn’t declared the instance variable and only declared the local variable inside method then the statement System.out.println(obj.myVar); would have thrown compilation error. As you cannot change and access local variables outside the method.

Check out these related java examples before proceeding to the next topic:

  1. Java Program to Find ASCII value of a Character
  2. Java Program to Multiply two Numbers
  3. Java Program to Calculate Area of Triangle
❮ PreviousNext ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap