Java Variables - The Coding Shala

Home >> Learn Java >> Java Vaiables

Variables

In Java, Variables are the basic unit of storage. In every program we use data and for further uses, we store that data into variables. Variables must be declared before going to use. 
Java Variables - The Coding Shala


Declaring a Variable

The basic syntax to declare variables in Java is shown below - 

type identifier = value;

or
 
type identifier = value, identifier = value,...;

Here type is Java's primitive data type or can be the name of class or interface. Type is used to declare the data type of a variable like whether a variable is an int, float or a char, etc. The identifier is the name of the variable. We can also initialize the variable at the time of declaration or later. to declare a variable we use equal sign and the value. Here literals(value of a variable) must be the compatible type. We can also declare more than one variable with a comma-separated list. For example - 

int a;  // declares integer variable a
int b = 23; //declares integer variable b with value 23

int c,d,e;  //declares integers variables c,d and e

char ch = 'X';
double pi = 3.14;

double p = 3.0, q = 4.0;
double r = Math.sqrt(p*p + q*q); //r is dynamically initialized


Scope of Variables


In Java, Variables can be declared within any block and that block defines the scope of those variables. The scope of variables means, variables are visible and can be used within the declared block of code and we can't use that outside of that block. There are two general categories of scopes are the global scope and local scope.



In Java, we see the scope of variables as variables defined by a class and those defined by a method. The scope defined by a method has inside its code of blocks means between its opening curly brace and closing curly brace. The following Java program explains the scope of variables - 

class ScopeExample {
    public static void main(String[] args){ //starts main's scope (scope 1)
    int x;  //within main's scope
    x = 10;
    if(x<=12){  //start new scope for example conside scope 2
        int y = 10; //within scope 2;
        System.out.println("In this scope X and Y both are visible");
    }//end of scope 2
    System.out.println("Here X is visible but not Y");
    }//end of scope 1
}



Output>>>>>>>
In this scope X and Y both are visible
Here X is visible but not Y



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

InterviewBit - Colorful Number Solution - The Coding Shala