• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reagrding literals

 
sumit bajaj
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Qn. Is the double and long primitive types are also known as literals.?

I feel the ans is yes. But one site say it is wrong.

please clarify.


Thanks in advance.
 
Vassili Vladimir
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Yes they are.

Regards ...
 
sumit bajaj
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

What a literal is, is when you write the actual value of the variable in the code.

There "Campbell" is a String literal, because I wrote the actual value of the String, and 123 is an int literal because I wrote the exact value of the int.
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I'd say double and int are primitive types that can be assigned a literal value, but I wouldn't say double and int are literals.

String s = "Cameron";

That would be assigning a literal value to the String s, because "Cameron" is hardcoded.

double d = 10.0;
int eresting = 50;

Both of those lines of code assign literal values to the variables d and eresting. You see, 10 and 50 are hardcoded into the program.

double trouble = d * eresting;

Well, trouble wouldn't really be assigned a literal value, because the value trouble takes on can vary depending upon how d and eresting are initialized.


From the Sun tutorials on what a litera is:


A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation. As shown below, it's possible to assign a literal to a variable of a primitive type:

boolean result = true;
char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;



Sun Tutorial on Primitive Types and the Definition of a Literal

One of the things that I found interesting is that true, false and null are actually considered literal values, and not necessarily keywords in Java. It's just that they're used so frequently, that most people consider them to be true Java keywords, but in fact, they're just literal values.

-Cameron McKenzie
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic