Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between Variable and Identifier

Tags:

java

I am new to programming and learning Java these Days. I have read that Identifiers are "names given to variables and many other things in java like classes etc". But I confused that if identifier is a name given to variable so how variable will have its own personality. For example, I have a Book in real world, which can be variable in programming and its name is Book so Book will be both Variable and Identifier. How are these two things distinguish and different.

like image 770
Syed Shaharyaar Hussain Avatar asked Dec 01 '22 15:12

Syed Shaharyaar Hussain


1 Answers

Every variable has a name, which is an identifier. Likewise every class has a name, which is also an identifier - as is a method name, and a package name. There are restrictions on what an identifier can look like - for example, it can't start with a number, or include whitespace.

So for example, in this program:

public class Test {
    public static void main(String[] args) {
        int x = 0;
        System.out.println(x);
    }
}

the identifiers used are:

  • Test
  • main
  • args
  • x
  • System
  • out
  • println

However, only args and x are variables declared within the code you've given. out is also a variable, but it's declared in the System type.

The same identifier can refer to different things in different contexts, even within the same program. For example:

public void method1() {
    String x = "";
    System.out.println(x);
}

public void method1() {
    int x = 0;
    System.out.println(x);
}

Here the identifier x is used in both methods - but each time it only refers to the variable declared within the method.

An identifier is just part of how you represent your program as text, whereas a variable is part of your logical program.

It's not entirely clear to me where your confusion stems from in the first place, but hopefully this can help you a little... you can probably just ignore the term identifier entirely for the most part. Just know that variables (and other things) have names.

like image 62
Jon Skeet Avatar answered Dec 17 '22 19:12

Jon Skeet