Java Reference
In-Depth Information
If you store the state of an object in an array instance variable, you should think carefully before returning the
reference of that array from any methods of your class. The caller of that method will get the handle of the array
instance variable and will be able to change the state of the objects of that class outside the class. This situation is
illustrated in following example:
public class MagicNumber {
// Magic numbers are not supposed to be changed It can be look up though
private int[] magicNumbers = {5, 11, 21, 51, 101};
// Other codes go here...
public int[] getMagicNumbers () {
/* Never do the following. If you do this, caller of this
method will be able to change the magic numbers.
*/
// return this.magicNumbers;
/* Do the following instead. In case of reference array, make a deep copy, and
return that copy. For primitive array you can use the clone() method */
return (int[])magicNumbers.clone();
}
}
You can also create an array and pass it to a method without storing the array reference in a variable. Suppose
there is a method named setNumbers(int[] nums) , which takes an int array as a parameter. You can call this method
as shown:
setNumbers(new int[]{10, 20, 30});
Command-Line Arguments
A Java application can be launched from a command prompt (a command prompt in Windows and a shell prompt
in UNIX). It can also be launched from within a Java development environment tool, such as NetBeans, JDeveloper, etc.
A Java application is run at the command line like so:
java <<options-list>> <<classname>>
<<options-list>>i s optional. You can also pass command-line arguments to a Java application by specifying
arguments after the class name.
java <<classname>> <<List of Command-line Arguments>>
Each argument in the argument list is separated by a space. For example, the following command runs the
com.jdojo.array.Test class and passes three names as the command-line arguments:
java com.jdojo.array.Test Cat Dog Rat
What happens to these three command-line arguments when the Test class is run? The operating system passes
the list of the arguments to the JVM. Sometimes the operating system may expand the list of arguments by interpreting
their meanings and may pass a modified arguments list to the JVM. The JVM parses the argument lists using a space
 
Search WWH ::




Custom Search