Literal (computer programming)

From Wikipedia, the free encyclopedia

In computer science, a literal is a notation for representing a fixed value in source code. Almost all programming languages have notations for atomic values such as integers, floating-point numbers, and strings, and usually for booleans and characters; some also have notations for elements of enumerated types and compound values such as arrays, records, and objects.

In contrast to literals, variables or constants are symbols that can take on one of a class of fixed values, the constant being constrained not to change. Literals are often used to initialize variables, for example, in the following, 1 is a literal and the three letter string in "cat" is a literal:

 int a = 1;
 String s = "cat";

In some object-oriented languages (like ECMAScript), objects can also be represented by literals. Methods of this object can be specified in the object literal using function literals. The brace notation below, which is also used for array literals, is typical for object literals:

 {"cat","dog"}
 {name:"cat",length:57}

Literals of objects

In ECMAScript (as well as its derivatives JavaScript and ActionScript), an object with methods can be written using the object literal like this:

var newobj = {
  var1: true,
  var2: "very interesting",
  method1: function () {
    alert(this.var1)
  },
  method2: function () {
    alert(this.var2)
  }
};
newobj.method1();
newobj.method2();

To briefly state the difference from normal class definition syntax, the keyword "class" is absent and the semicolon is replaced by the comma.

These object literals are similar to anonymous classes in other languages like Java.

See also

This article is issued from Wikipedia. The text is available under the Creative Commons Attribution/Share Alike; additional terms may apply for the media files.