Reputation: 101
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?
Upvotes: 1
Views: 2237
Reputation: 421150
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 literaltrue
-- A boolean literal26
-- An integer literalAn initialization is an assignment, such as int i = ...
where ...
is the value to initialize i
with.
Upvotes: 5
Reputation: 58909
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.
Upvotes: 1
Reputation: 10662
int decVal = 26;
"int" is the datatype
"decVal " is the name of the variable
"26" is the literal
see also here
Upvotes: 3
Reputation: 393966
26
is a literal. true
is a literal. 54.4
is a literal.
int decVal = 26;
is a declaration + initialization of a variable.
Upvotes: 1