Java Reference
In-Depth Information
In some cases, you can even change the value of the property, like this:
myArray.length = 12;
However, unlike variables, some properties are read-only — you can get information from them, but
you can't change information inside them.
Calling an Object's Methods
Methods are very much like functions in that they can be used to perform useful tasks, such as getting
the hours from a particular date or generating a random number. Again like functions, some methods
return a value, such as a Date object's getHours() method, while others perform a task, but return no
data, such as an Array object's sort() method.
Using the methods of an object is very similar to using properties, in that you put the object's variable
name fi rst, then a dot, and then the name of the method. For example, to sort the elements of an Array
in the variable myArray, you may use the following code:
myArray.sort();
Just as with functions, you can pass parameters to some methods by placing the parameters between
the parentheses following the method's name. However, whether or not a method takes parameters,
you must still put parentheses after the method's name, just as you did with functions. As a general
rule, anywhere you can use a function, you can use a method of an object.
Primitives and Objects
You should now have a good idea about the difference between primitive data, such as numbers and
strings, and object data, such as Dates and Arrays. However, as was mentioned earlier, there is also a
String object. Where does this fi t in?
In fact there are String, Number, and Boolean objects corresponding to the string, number, and
Boolean primitive data types. For example, to create a String object containing the text “I'm a String
object” you can use the following code:
var myString = new String(“I'm a String object”);
String objects have the length property just as Array objects do. This returns the number of characters
in the String object. For example,
var lengthOfString = myString.length;
would store the value 19 in the variable lengthOfString (remember that spaces are referred to as
characters too).
But what if you had declared a primitive string called mySecondString holding the text “I'm a
primitive string” like this:
var mySecondString = “I'm a primitive string”;
and wanted to know how many characters could be found in this primitive string?
Search WWH ::




Custom Search