Results 1 to 2 of 2

Thread: Literals in java program?

  1. #1
    Join Date
    May 2010
    Posts
    49

    Literals in java program?

    What are the Literals in java, what is the use of Literals.?
    web development
    Web Design New York
    NY Web design

  2. #2
    Join Date
    May 2010
    Location
    Riverside, Ca
    Posts
    241
    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

    Code:
    // 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.
    "The generation of random numbers is too important to be left to chance."

Similar Threads

  1. Help on HTML forms
    By chriscatling in forum General Questions
    Replies: 0
    Last Post: 11 May 2006, 09:27 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •