What is the difference between data types and literals in Java?
Values like 1.5, 2, 3.13, “hello” that appear directly in a program are known as literals.
Int (Data type) x (Variable) = 100 (Literals) ;
Data type :- Data type means type of data ,it may be byte
, short
, int
, long
, float
, double
,char
boolean
and many other user defined type(Class) like Employee, Student etc...
Literals :- The value we assign to variable is called Literal .
e.g:- String str= "India";
Here "india" is string Literal .
Literals are fixed value for a variable until they are not assign by other variable.
true
, false
and null
are reserved word in java. Technically they are literals values and not keywords .However they can not be used as Identifier because they have specific meaning to the java Compiler.
Data Type: Are nothing but a reserved memory location to store values. meaning when you create a variable you reserve some space in memory.
Literal: Is the source code representation of a fixed value, a Given or Constant value. Ex: boolean result = true
, String s1 = "Hello World"
.
boolean - is data type, result - is variable, true - is literal
String - is Object data type, s1 - is variable, "Hello World" - is literal
I don't know that they have enough in common to be able to identify differences, but data types are things like int
, float[]
, Object
, and literals are something like 1
, { 1.0f, 2.0f}
, "abcdef"
.
String string = "Hello World";
< 1 > < 2 > < 3 >
1 is a data type, 2 a variable name, 3 a (String) literal
From the JLS:
A literal is the source code representation of a value of a primitive type [like
1
,true
,'t'
or1.2f
], the String type [like""
orSomething
], or the null type [null
]
A literal is a constant value which is compatible to a datatype, a literal is used to assign a value to variable, to compare values or define constants. See JLS 3.10.
e.g:
int varOfDataTypeInt = 123;
String s = "string literal";