Thursday, May 5, 2011

What Is a Literal in Computer Programming?

In computer programming languages, a literal refers to a piece of information (such as a word, digit) that is written exactly as it is meant to be interpreted.

Below are some statements followed by comments (text starting with //). In Java a statement is a text ending with a ";". A statement is a complete sentence that provides a command (or instruction) to be executed by a computer. Comments is any text not interpreted nor executed by a computer. It is there solely for readability purposes. The computer skips everything that starts with "//" until the end of the line.

int x;
// int is a type
// x is a variable

x = 1; 
// 1 is an integer literal

String text = "abc";
// text is a variable
// = is an operator
// "abc" is a literal

Long nr = null;
// nr is a variable
// null is a literal

boolean var = true; 
// boolean is a type
// var is variable
// = is an operator
// true is a literal

As you can see, "1" is a integer number whose value is also 1. Therefore, 1 is a literal. "null" is a special kind of literal that has a value of 0 (zero). In the case above, assigning "null" literal to the variable "nr" implies that the computer should use the corresponding value of null (most of the times 0) and assign it to the variable. Other types of literal in java is true or false. In the case above the computer will assign "true" to the boolean typed variable called "var".

Rubens Gomes