简体   繁体   中英

What is difference between initialized variable and a literal in java?

I am learning java, while studying literals in java I found that literals can be of any datatype (int,boolean,char,etc.) and declared as

int decVal = 26;   //Am I declaring literal correctly?

As far as I know, a literal is fixed value and above declaration is very similar to initialization of a variable of 'int' type. To confirm, I tried following code.

public class LiteralChecking {

    public static void main(String[] args) {
        int i=2;

        for(i=2;i<5;i++)
        {
            System.out.println("i= "+i);
        }
    }
}

Where, i got output as:

i=2
i=3
i=4

now I am confused between the literal and initialization, are both same? Can some one explain me the difference?

Am I declaring literal correctly?

No, you're not declaring a literal. You're declaring and initializing a variable called decVal . 26 is an integer literal.

I am confused between the literal and initialization

  • A literal is a value in the program code. Examples of literals include

    • "Hello" -- A string literal
    • true -- A boolean literal
    • 26 -- An integer literal
  • An initialization is an assignment, such as int i = ... where ... is the value to initialize i with.

int decVal = 26;

"int" is the datatype

"decVal " is the name of the variable

"26" is the literal

see also here

26 is a literal. true is a literal. 54.4 is a literal.

int decVal = 26; is a declaration + initialization of a variable.

A literal is a number/string/boolean that appears in your source code. 5 is an integer literal. "Hello" is a string literal. It literally means the string "Hello" - it doesn't, for example, access a variable called Hello.

int decVal = 26; is a declaration and initialisation of the variable decVal , which happens to use a literal ( 26 ) as the initial value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM