PDA

View Full Version : Literals in java program?



johns123
25 Jun 2010, 08:57 AM
What are the Literals in java, what is the use of Literals.?

Asperon
27 Jun 2010, 04:51 AM
First of all this is a web development forum, so I am going to assume you mean Javascript (which is definitely not Java).

Since everything in JS is an object I'm going to refer to objects only here.

In JS an array is a new instance of the Array() object. a number is a new instance of a Number() object. a string is a new instance of a String() object. That is how JS works. These are all NON-LITERALS

A Literal is used when you don't need to make new instances of objects (the main reasons for using them is they take up less memory and resources and organizational preferences and purposes).

here are some examples

NOTE: I did not test this code, so there may/probably will be syntax errors, and got lazy in some places, so I may have made literal calls wrong etc etc etc good thing this world isn't perfect right =D



// Javascript code

var a = new Array('item0', 'item1', 2, 3, 4, 'etc...'); // Non-Literal Array
var b = ['item0', 'item1', 2, 3, 4, 'etc...']; // Literal array

// In the array case, there usually isn't too much difference

// Here is where it can matter.

function c(){ // This is basically an object
this.d = 100; // this can be called as c.d
}
c.prototype.setD = function(val){ // This changes d's value.
this.d = val;
}

// Now I make new instances of c
var e = new c();
var f = new c();

alert(e.d); // writes 100
alert(f.d); // writes 100

e.setD(34);
alert(e.d) // writes 34
alert(f.d) // still only writes 100

// Each instance is separate from the other instances
// This is a Non-Literal example

// For a Literal example you could do this

var g = {}; // this is a literal object
g.d = 100;
g.setD = function(val){
this.d = val;
}

// Now I make new instances of g
var h = g(); // You can't use the new keyword with literals
var i = g(); / / basically just copies it

alert(h.d); // writes 100
alert(i.d); // writes 100

h.setD(34);
alert(h.d) // writes 34
alert(i.d) // Also writes 34

// So really, with a literal, only one version of the object exists.