Core classes in java chapter-5

Chapter 5
Core Classes
Before discussing other features of object-oriented programming (OOP), let's examine several important classes that are commonly used in Java. These classes are included in the Java core libraries that come with the JDK. Mastering them will help you understand the examples that accompany the next OOP lessons.
The most prominent class of all is definitely java.lang.Object. However, it is hard to talk about this class without first covering inheritance, which we will do in Chapter 6, “Inheritance.” Therefore, java.lang.Object is only discussed briefly in this chapter. Right now we will concentrate on classes that you can use in your programs. We'll start withjava.lang.String and other types of strings: java.lang.StringBuffer and java.lang.StringBuilder. Then, we'll discuss arrays and the java.lang.System class. The java.util.Scanner class is also included here because it provides a convenient way to take user input.
Boxing/unboxing and varargs are explained towards the end of this chapter.
Note
When describing a method in a Java class, presenting the method signature always helps. A method often takes as parameters objects whose classes belong to different packages than the method's class. Or, it may return a type from a different package than its class. For clarity, fully qualified names will be used for classes from different packages. For example, here is the signature of the toString method of java.lang.Object:
public String toString()
A fully qualified name for the return type is not necessary because the return type String is part of the same package as java.lang.Object. On the other hand, the signature of thetoString method in java.util.Scanner uses a fully qualified name because the Scanner class is part of a different package (java.util).
public java.lang.String toString()
java.lang.Object
The java.lang.Object class represents a Java object. In fact, all classes are direct or indirect descendants of this class. Since we have not learned inheritance (which is only given in Chapter 6, “Inheritance”), the word descendant probably makes no sense to you. Therefore, we will briefly discuss the method in this class and revisit this class in Chapter 6.
Here are the methods in the Object class.
protected Object clone()
Creates and returns a copy of this object. A class implements this method to support object cloning.
public boolean equals(Object obj)
Compares this object with the passed-in object. A class must implement this method to provide a means to compare the contents of its instances.
protected void finalize()
Called by the garbage collector on an object that is about to be garbage-collected. In theory a subclass can override this method to dispose of system resources or to perform other cleanup. However, performing the aforesaid operations should be done somewhere else and you should not touch this method.
public final Class getClass()
Returns a java.lang.Class object of this object. See the section “java.lang.Class” for more information on the Class class.
public int hashCode()
Returns a hash code value for this object.
public String toString()
Returns the description of this object.
In addition, there are also the waitnotify, and notifyAll methods that you use when writing multithreaded applications. These methods are discussed in Chapter 23, “Java Threads.”
java.lang.String
I have not seen a serious Java program that does not use the java.lang.String class. It is one of the most often used classes and definitely one of the most important.
String object represents a string, i.e. a piece of text. You can also think of a String as a sequence of Unicode characters. A String object can consists of any number of characters. AString that has zero character is called an empty StringString objects are constant. Once they are created, their values cannot be changed. Because of this, String instances are said to be immutable. And, because they are immutable, they can be safely shared.
You could construct a String object using the new keyword, but this is not a common way to create a String. Most often, you assign a string literal to a String reference variable. Here is an example:
String s = "Java is cool";
This produces a String object containing “Java is cool” and assigns a reference to it to s. It is the same as the following.
String message = new String("Java is cool");
However, assigning a string literal to a reference variable works differently from using the new keyword. If you use the new keyword, the JVM will always create a new instance of String. With a string literal, you get an identical String object, but the object is not always new. It may come from a pool if the string “Java is cool” has been created before.
Thus, using a string literal is better because the JVM can save some CPU cycles spent on constructing a new instance. Because of this, we seldom use the new keyword when creating aString object. The String class's constructors can be used if we have specific needs, such as converting a character array into a String.
Comparing Two Strings
String comparison is one of the most useful operations in Java programming. Consider the following code.
String s1 = "Java";
String s2 = "Java";
if (s1 == s2) {
    ...
}
Here, (s1 == s2) evaluates to true because s1 and s2 reference the same instance. On the other hand, in the following code (s1 == s2) evaluates to false because s1 and s2 reference different instances:
String s1 = new String("Java");
String s2 = new String("Java");
if (s1 == s2) {
    ...
}
This shows the difference between creating String objects by writing a string literal and by using the new keyword.
Comparing two String objects using the == operator is of little use because you are comparing the addresses referenced by two variables. Most of the time, when comparing two Stringobjects, you want to know whether the values of the two objects are the same. In this case, you need to use the String class's equals method.
String s1 = "Java";
if (s1.equals("Java")) // returns true.
And, sometimes you see this style.
if ("Java".equals(s1))
In (s1.equals(“Java”)), the equals method on s1 is called. If s1 is null, the expression will generate a runtime error. To be safe, you have to make sure that s1 is not null, by first checking if the reference variable is null.
if (s1 != null && s1.equals("Java"))
If s1 is null, the if statement will return false without evaluating the second expression because the AND operator && will not try to evaluate the right hand operand if the left hand operand evaluates to false.
In (“JavWa”.equals(s1)), the JVM creates or takes from the pool a String object containing “Java” and calls its equals method. No nullity checking is required here because “Java” is obviously not null. If s1 is null, the expression simply returns false. Therefore, these two lines of code have the same effect.
if (s1 != null && s1.equals("Java"))
if ("Java".equals(s1))
String Literals
Because you always work with String objects, it is important to understand the rules for working with string literals.
First of all, a string literal starts and ends with a double quote (“). Second, it is a compile error to change line before the closing ”. For example, this will raise a compile error.
String s2 = "This is an important
    point to note";
You can compose long string literals by using the plus sign to concatenate two string literals.
String s1 = "Java strings " + "are important";
String s2 = "This is an important " +
    "point to note";
You can concatenate a String with a primitive or another object. For instance, this line of code concatenates a String and an integer.
String s3 = "String number " + 3;
If an object is concatenated with a String, the toString method of the former will be called and the result used in the concatenation.
Escaping Certain Characters
You sometimes need to use special characters in your strings such as carriage return (CR) and linefeed (LF). In other occasions, you may want to have a double quote character in your string. In the case of CR and LF, it is not possible to input these characters because pressing Enter changes lines. A way to include special characters is to escape them, i.e. use the character replacement for them.
Here are some escape sequences:
\u            /* a Unicode character
\b            /* \u0008: backspace BS */
\t            /* \u0009: horizontal tab HT */
\n            /* \u000a: linefeed LF */
\f            /* \u000c: form feed FF */
\r            /* \u000d: carriage return CR */
\"            /* \u0022: double quote " */
\'            /* \u0027: single quote ' */
\\            /* \u005c: backslash \ */
For example, the following code includes the Unicode character 0122 at the end of the string.
String s = "Please type this character \u0122";
To obtain a String object whose value is John “The Great” Monroe, you escape the double quotes:
String s = "John \"The Great\" Monroe";
Switching on A String
Starting from Java 7 you can use the switch statement with a String. Recall the syntax of the switch statement given in Chapter 3, “Statements:”
switch(expression) {
case value_1 :
    statement(s);
    break;
case value_2 :
    statement(s);
    break;
  .
  .
  .
case value_n :
    statement(s);
    break;
default:
    statement(s);
}
Here is an example of using the switch statement on a String.
String input = ...;
switch (input) {
case "one" :
    System.out.println("You entered 1.");
    break;
case "two" :
    System.out.println("You entered 2.");
    break;
default:
    System.out.println("Invalid value.");
}
The String Class's Constructors
The String class provides a number of constructors. These constructors allow you to create an empty string, a copy of another string, and a String from an array of chars or bytes. Use the constructors with caution as they always create a new instance of String.
Note
Arrays are discussed in the section “Arrays.”
public String()
Creates an empty string.
public String(String original)
Creates a copy of the original string.
public String(char[] value)
Creates a String object from an array of chars.
public String(byte[] bytes)
Creates a String object by decoding the bytes in the array using the computer's default encoding.
public String(byte[] bytes, String encoding)
Creates a String object by decoding the bytes in the array using the specified encoding.
The String Class's Methods
The String class provides methods for manipulating the value of a String. However, since String objects are immutable, the result of the manipulation is always a new String object.
Here are some of the more useful methods.
public char charAt(int index)
Returns the char at the specified index. For example, the following code returns 'J'.
      "Java is cool".charAt(0)
public String concat(String s)
Concatenates the specified string to the end of this String and return the result. For example, “Java” .concat(“is cool”) returns “Java is cool”.
public boolean equals(String anotherString)
Compares the value of this String and anotherString and returns true if the values match.
public boolean endsWith(String suffix)
Tests if this String ends with the specified suffix.
public int indexOf(String substring)
Returns the index of the first occurrence of the specified substring. If no match is found, returns -1. For instance, the following code returns 8.
      "Java is cool".indexOf("cool")
public int indexOf(String substring, int fromIndex)
Returns the index of the first occurrence of the specified substring starting from the specified index. If no match is found, returns -1.
public int lastIndexOf(String substring)
Returns the index of the last occurrence of the specified substring. If no match is found, returns -1.
public int lastIndexOf(String substring, int fromIndex)
Returns the index of the last occurrence of the specified substring starting from the specified index. If no match is found, returns -1. For example, the following expression returns 3.
      "Java is cool".lastIndexOf("a")
public String substring(int beginIndex)
Returns a substring of the current string starting from the specified index. For instance, “Java is cool”.substring(8) returns “cool”.
public String substring(int beginIndex, int endIndex)
Returns a substring of the current string starting from beginIndex to endIndex. For example, the following code returns “is”:
      "Java is cool".substring(5, 7)
public String replace(char oldChar, char newChar)
Replaces every occurrence of oldChar with newChar in the current string and returns the new String“dingdong”.replace('d', 'k') returns “kingkong”.
public int length()
Returns the number of characters in this String. For example, “Java is cool”.length() returns 12. Prior to Java 6, this method was often used to test if a String was empty. However, the isEmpty method is preferred because it's more descriptive.
public boolean isEmpty()
Returns true is the string is empty (contains no characters).
public String[] split(String regEx)
Splits this String around matches of the specified regular expression. For example, “Java is cool”.split(“ ”) returns an array of three Strings. The first array element is “Java”, the second “is”, and the third “cool”.
public boolean startsWith(String prefix)
Tests if the current string starts with the specified prefix.
public char[] toCharArray()
Converts this string to an array of chars.
public String toLowerCase()
Converts all the characters in the current string to lower case. For instance, “Java is cool”.toLowerCase() returns “java is cool”.
public String toUpperCase()
Converts all the characters in the current string to upper case. For instance, “Java is cool”.toUpperCase() returns “JAVA IS COOL”.
public String trim()
Trims the trailing and leading white spaces and returns a new string. For example, “ Java ”.trim() returns “Java”.
In addition, there are two static methods, valueOf and format. The valueOf method converts a primitive, a char array, or an instance of Object into a string representation and there are nine overloads of this method.
public static String valueOf(boolean value)
public static String valueOf(char value)
public static String valueOf(char[] value)
public static String valueOf(char[] value, int offset, int length)
public static String valueOf(double value)
public static String valueOf(float value)
public static String valueOf(int value)
public static String valueOf(long value)
public static String valueOf(Object value)
For example, the following code returns the string “23”
String.valueOf(23);
The format method allows you to pass an arbitrary number of parameters. Here is its signature.
public static String format(String format, Object... args)
However, I will hold off discussing the format method here because to understand it, you need to understand arrays and variable arguments. It will be explained in the section “Varargs” later in this chapter.
java.lang.StringBuffer and java.lang.StringBuilder
String objects are immutable and are not suitable to use if you need to append or insert characters into them because string operations on String always create a new String object. For append and insert, you'd be better off using the java.lang.StringBuffer or java.lang.StringBuilder class. Once you're finished manipulating the string, you can convert a StringBuffer orStringBuilder object to a String.
Until JDK 1.4, the StringBuffer class was solely used for mutable strings. Methods in StringBuffer are synchronized, making StringBuffer suitable for use in multithreaded environments. However, the price for synchronization is performance. JDK 5 added the StringBuilder class, which is the unsynchronized version of StringBufferStringBuilder should be chosen over StringBuffer if you do not need synchronization.
Note
Synchronization and thread safety are discussed in Chapter 23, “Java Threads.”
The rest of this section will use StringBuilder. However, the discussion is also applicable to StringBuffer as both StringBuilder and StringBuffer shares similar constructors and methods.
StringBuilder Class's Constructors
The StringBuilder class has four constructors. You can pass a java.lang.CharSequence, a String, or an int.
public StringBuilder()
public StringBuilder(CharSequence seq)
public StringBuilder(int capacity)
public StringBuilder(String string)
If you create a StringBuilder object without specifying the capacity, the object will have a capacity of 16 characters. If its content exceeds 16 characters, it will grow automatically. If you know that your string will be longer than 16 characters, it is a good idea to allocate enough capacity as it takes time to increase a StringBuilder's capacity.
StringBuilder Class's Methods
The StringBuilder class has several methods. The main ones are capacitylengthappend, and insert.
public int capacity()
Returns the capacity of the StringBuilder object.
public int length()
Returns the length of the string the StringBuilder object stores. The value is less than or equal to the capacity of the StringBuilder.
public StringBuilder append(String string)
Appends the specified String to the end of the contained string. In addition, append has various overloads that allow you to pass a primitive, a char array, and an java.lang.Objectinstance.
For example, examine the following code.
StringBuilder sb = new StringBuilder(100);
sb.append("Matrix ");
sb.append(2);
After the last line, the content of sb is “Matrix 2”.
An important point to note is that the append methods return the StringBuilder object itself, the same object on which append is invoked. As a result, you can chain calls toappend.
      sb.append("Matrix ").append(2);
public StringBuilder insert(int offset, String string)
Inserts the specified string at the position indicated by offset. In addition, insert has various overloads that allow you to pass primitives and a java.lang.Object instance. For example,
StringBuilder sb2 = new StringBuilder(100);
sb2.append("night");
sb2.insert(0, 'k'); // value = "knight
Like appendinsert also returns the current StringBuilder object, so chaining insert is also permitted.
public String toString()
Returns a String object representing the value of the StringBuilder.
Primitive Wrappers
For the sake of performance, not everything in Java is an object. There are also primitives, such as intlongfloatdouble, etc. When working with both primitives and objects, there are often circumstances that necessitate primitive to object conversions and vice versa. For example, a java.util.Collection object (discussed in Chapter 11, “The Collections Framework”) can be used to store objects, not primitives. If you want to store primitive values in a Collection, they must be converted to objects first.
The java.lang package has several classes that function as primitive wrappers. They are BooleanCharacterByteDoubleFloatIntegerLong, and ShortByteDoubleFloat,IntegerLong, and Short share similar methods, therefore only Integer will be discussed here. You should consult the Javadoc for information on the others.
Note
Conversions from primitives to objects and vice versa are easy thanks to the boxing and unboxing mechanisms. Boxing and unboxing are discussed in the section “Boxing and Unboxing” later in this chapter.
The following sections discuss the wrapper classes in detail.
java.lang.Integer
The java.lang.Integer class wraps an int. The Integer class has two static final fields of type intMIN_VALUE and MAX_VALUEMIN_VALUE contains the minimum possible value for an int (-231) and MAX_VALUE the maximum possible value for an int (231 - 1).
The Integer class has two constructors:
public Integer(int value)
public Integer(String value)
For example, this code constructs two Integer objects.
Integer i1 = new Integer(12);
Integer i2 = new Integer("123");
Integer has the no-arg byteValuedoubleValuefloatValueintValuelongValue, and shortValue methods that convert the wrapped value to a bytedoublefloatintlong, and short, respectively. In addition, the toString method converts the value to a String.
There are also static methods that you can use to parse a String to an int (parseInt) and convert an int to a String (toString). The signatures of the methods are as follows.
public static int parsetInt(String string)
public static String toString(int i)
java.lang.Boolean
The java.lang.Boolean class wraps a boolean. Its static final fields FALSE and TRUE represents a Boolean object that wraps the primitive value false and a Boolean object wrapping the primitive value true, respectively.
You can construct a Boolean object from a boolean or a String, using one of these constructors.
public Boolean(boolean value)
public Boolean(String value)
For example:
Boolean b1 = new Boolean(false);
Boolean b2 = new Boolean("true");
To convert a Boolean to a boolean, use its booleanValue method:
public boolean booleanValue()
In addition, the static method valueOf parses a String to a Boolean object.
public static Boolean valueOf(String string)
And, the static method toString returns the string representation of a boolean.
public static String toString(boolean boolean)
java.lang.Character
The Character class wraps a char. There is only one constructor in this class:
public Character(char value)
To convert a Character object to a char, use its charValue method.
public char charValue()
There are also a number of static methods that can be used to manipulate characters.
public static boolean isDigit(char ch)
Determines if the specified argument is one of these: ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘0’.
public static char toLowerCase(char ch)
Converts the specified char argument to its lower case.
public static char toUpperCase(char ch)
Converts the specified char argument to its upper case.
Arrays
In Java you can use arrays to group primitives or objects of the same type. The entities belonging to an array is called the components of the array. In the background, every time you create an array, the compiler creates an object which allows you to:

images get the number of components in the array through the length field. The length of an array is the number of components in it.
images access each component by specifying an index. This indexing is zero-based. Index 0 refers to the first component, 1 to the second component, etc.

All the components of an array have the same type, called the component type of the array. An array is not resizable and an array with zero component is called an empty array.
An array is a Java object. Therefore, you treat a variable that refers to an array like other reference variables. For one, you can compare it with null.
String[] names;
if (names == null) // evaluates to true
If an array is a Java object, shouldn't there be a class that gets instantiated when you create an array? May be something like java.lang.Array? The truth is, no. Arrays are indeed special Java objects whose class is never documented and is not meant to be extended.
Note
An array can also contain other arrays, creating an array of arrays.
To use an array, first you need to declare one. You can use this syntax to declare an array:
type[] arrayName;
or
type arrayName[]
For example, the following declares an array of longs named numbers:
long[] numbers;
Declaring an array does not create an array or allocate space for its components, the compiler simply creates an object reference. One way to create an array is by using the new keyword. You must specify the size of the array you are creating.
new type[size]
As an example, the following code creates an array of four ints:
new int[4]
Alternatively, you can declare and create an array in the same line.
int[] ints = new int[4];
To reference the components of an array, use an index after the variable name. For example, the following snippet creates an array of four String objects and initializes its first member.
String[] names = new String[4];
names[0] = "Hello World";
Note
Referencing an out of bound member will raise a runtime error. To be precise, a java.lang.ArrayIndexOutOfBoundsException will be thrown. See Chapter 7, “Error Handling” for information about exceptions.
Note
When an array is created, its components are either null (if the component type is an object type) or the default value of the component type (if the array contains primitives). For example, an array of ints contain zeros by default.
You can also create and initialize an array without using the new keyword. Java allows you to create an array by grouping values within a pair of braces. For example, the following code creates an array of three String objects.
String[] names = { "John", "Mary", "Paul" };
The following code creates an array of four ints and assign the array to the variable matrix.
int[] matrix = { 1, 2, 3, 10 };
Be careful when passing an array to a method because the following is illegal even though the average method below take an array of ints.
int avg = average( { 1, 2, 3, 10 } ); // illegal
Instead, you have to instantiate the array separately.
int[] numbers = { 1, 2, 3, 10 };
int avg = average(numbers);
or this
int avg = average(new int[] { 1, 2, 3, 10 });
Iterating over an Array
Prior to Java 5, the only way to iterate the members of an array was to use a for loop and the array's indices. For example, the following code iterates over a String array referenced by the variable names:
for (int i = 0; i < 3; i++) {
    System.out.println("\t- " + names[i]);
}
Java 5 has enhanced the for statement. You can now use it to iterate over an array or a collection without the index. Use this syntax to iterate over an array:
for (componentType variable : arrayName)
Where arrayName is the reference to the array, componentType is the component type of the array, and variable is a variable that references each component of the array.
For example, the following code iterates over an array of Strings.
String[] names = { "John", "Mary", "Paul"
for (String name : names) {
    System.out.println(name);
}
The code prints this on the console.
John
Mary
Paul
Changing an Array Size
Once an array is created, its size cannot be changed. If you want to change the size, you must create a new array and populates it using the values of the old array. For instance, the following code increases the size of numbers, an array of three ints, to 4.
int[] numbers = { 1, 2, 3 };
int[] temp = new int[4];
int length = numbers.length;
for (int j = 0; j < length; j++) {
    temp[j] = numbers[j];
}
numbers = temp;
A shorter way of doing this is by using the copyOf method of the java.util.Arrays class. For instance, this code creates a four-element array and copies the content of numbers to its first three elements.
int[] numbers = { 1, 2, 3 };
int[] newArray = Arrays.copyOf(numbers, 4);
And, of course you can reassign the new array to the original variable:
numbers = Arrays.copyOf(numbers, 4);
The copyOf method comes with ten overloads, eight for each type of Java primitives and two for objects. Here are their signatures:
public static boolean[] copyOf(boolean[] original, int newLength)
public static byte[] copyOf(byte[] original, int newLength)
public static char[] copyOf(char[] original, int newLength)
public static double[] copyOf(double[] original, int newLength)
public static float[] copyOf(float[] original, int newLength)
public static int[] copyOf(int[] original, int newLength)
public static long[] copyOf(long[] original, int newLength)
public static short[] copyOf(short[] original, int newLength)
public static <T> T[] copyOf(T[] original, int newLength)
public static <T,U> T[] copyOf(U[] original, int newLength,
        java.lang.Class<? extends T[]> newType)
Each of these overloads can throw a java.lang.NullPointerException if original is null and a java.lang.NegativeArraySizeException if newLength is negative.
The newLength argument can be smaller, equal to, or larger than the length of the original array. If it is smaller, then only the first newLength elements will be included in the copy. If it is larger, the last few elements will have default values, i.e. 0 if it is an array of integers or null if it is an array of objects.
Another method similar to copyOf is copyOfRangecopyOfRange copies a range of elements to a new array. Like copyOfcopyOfRange also provides overrides for each Java data type. Here are their signatures:
public static boolean[] copyOfRange(boolean[] original,
        int from, int to)
public static byte[] copyOfRange(byte[] original,
        int from, int to)
public static char[] copyOfRange(char[] original,
        int from, int to)
public static double[] copyOfRange(double[] original,
        int from, int to)
public static float[] copyOfRange(float[] original,
        int from, int to)
public static int[] copyOfRange(int[] original,
        int from, int to)
public static long[] copyOfRange(long[] original,
        int from, int to)
public static short[] copyOfRange(short[] original,
        int from, int to)
public static <T> T[] copyOfRange(T[] original,
        int from, int to)
public static <T,U> T[] copyOfRange(U[] original, int from,
        int to, java.lang.Class<? extends T[]> newType)
Passing a String Array to main
You invoke the static void method main to run a Java class. Here is the signature of the main method:
public static void main(String[] args)
You can pass arguments to the main method by feeding them to the java program. The arguments should appear after the class name and two arguments are separated by a space. To be precise, you should use the following syntax:
java className arg1 arg2 arg3 ... arg-n
Listing 5.1 shows a class that iterates over the main method's String array argument.
Listing 5.1: Accessing the main method's arguments
package app05;
public class MainMethodTest {
    public static void main(String[] args) {
        for (String arg : args) {
            System.out.println(arg);
        }
    }
}
The following command invokes the class and passes two arguments to the main method.
java app05/MainMethodTest john mary
The main method will then print the arguments to the console.
john
mary
java.lang.Class
One of the members of the java.lang package is a class named Class. Every time the JVM creates an object, it also creates a java.lang.Class object that describes the type of the object. All instances of the same class share the same Class object. You can obtain the Class object by calling the getClass method of the object. This method is inherited from java.lang.Object.
For example, the following code creates a String object, invokes the getClass method on the String instance, and then invokes the getName method on the Class object.
String country = "Fiji";
Class myClass = country.getClass();
System.out.println(myClass.getName()); // prints java.lang.String
As it turns out, the getName method returns the fully qualified name of the class represented by a Class object.
The Class class also brings the possibility of creating an object without using the new keyword. You achieve this by using the two methods of the Class class, forName andnewInstance.
public static Class forName(String className)
public Object newInstance()
The static forName method creates a Class object of the given class name. The newInstance method creates a new instance of a class.
The following example uses forName to create a Class object of the app05.Test class and create an instance of the Test class. Since newInstance returns a java.lang.Object object, you need to downcast it to its original type.
Class klass = null;
try {
    klass = Class.forName("app05.Test");
} catch (ClassNotFoundException e) {
}
 
if (klass != null) {
try {
    // create an instance of the Test class
    Test test = (Test) klass.newInstance();
 
} catch (IllegalAccessException e) {
} catch (InstantiationException e) {
}
Do not worry about the try…catch blocks as they will be explained in Chapter 7, “Error Handling.”
You might want to ask this question, though. Why would you want to create an instance of a class using forName and newInstance, when using the new keyword is shorter and easier? The answer is because there are circumstances whereby the name of the class is not known when you are writing the program.
java.lang.System
The System class is a final class that exposes useful static fields and static methods that can help you with common tasks.
The three fields of the System class are outin, and err:
public static final java.io.PrintStream out;
public static final java.io.InputStream in;
public static final java.io.PrintStream err;
The out field represents the standard output stream which by default is the same console used to run the running Java application. You will learn more about PrintStream in Chapter 13, “Input Output,” but for now know that you can use the out field to write messages to the console. You will often write the following line of code:
System.out.print(message);
where message is a String object. However, PrintStream has many print method overloads that accept different types, so you can pass any primitive type to the print method:
System.out.print(12);
System.out.print('g');
In addition, there are println methods that are equivalent to print, except that println adds a line terminator at the end of the argument.
Note also that because out is static, you can access it by using this notation: System.out, which returns a java.io.PrintStream object. You can then access the many methods on thePrintStream object as you would methods of other objects: System.out.printSystem.out.format, etc.
The err field also represents a PrintStream object, and by default the output is channeled to the console from where the current Java program was invoked. However, its purpose is to display error messages that should get immediate attention of the user.
For example, here is how you can use err:
System.err.println("You have a runtime error.");
The in field represents the standard input stream. You can use it to accept keyboard input. For example, the getUserInput method in Listing 5.2 accepts the user input and returns it as a String:
Listing 5.2: The getUserInput method
public String getUserInput() {
    StringBuilder sb = new StringBuilder();
    try {
        char c = (char) System.in.read();
        while (c != '\r') {
            sb.append(c);
            c = (char) System.in.read();
        }
    } catch (IOException e) {
    }
    return sb.toString();
}
However, an easier way to receive keyboard input is to use the java.util.Scanner class, discussed in the section “java.util.Scanner” later in this chapter.
The System class has many useful methods, all of which are static. Some of the more important ones are listed here.
public static void arraycopy(Object source, int sourcePos,
        Object destination, int destPos, int length)
This method copies the content of an array (source) to another array (destination), beginning at the specified position, to the specified position of the destination array. For example, the following code uses arraycopy to copy the contents of array1 to array2.
      int[] array1 = {1, 2, 3, 4};
      int[] array2 = new int[array1.length];
      System.arraycopy(array1, 0, array2, 0, array1.length);
 
public static void exit(int status)
Terminates the running program and the current JVM. You normally pass 0 to indicate that a normal exit and a nonzero to indicate there has been an error in the program prior to calling this method.
public static long currentTimeMillis()
Returns the computer time in milliseconds. The value represents the number of milliseconds that has elapsed since January 1, 1970 UTC. To get the string representation of the current computer time, use this:
System.out.println(new java.util.Date());
The Date class is discussed in Chapter 8, Numbers and Date.”
However, currentTimeMillis is useful if you want to time an operation. For instance, the following code measure the time it takes to perform a block of code:
long start = System.currentTimeMillis();
// block of code to time
long end = System.currentTimeMillis();
System.out.println("It took " + (end - start) +
        " milliseconds");
public static long nanoTime()
This method is similar to currentTimeMillis, but provide more precision, i.e. in nanoseconds.
long start = System.nanoTime();
// block of code to time
long end = System.nanoTime();
System.out.println("It took " + (end - start) +
        " nanoseconds");
public static String getProperty(String key)
This method returns the value of the specified property. It returns null if the specified property does not exist. There are system properties and there are user-defined properties. When a Java program runs, the JVM provides values that may be used by the program as properties.
Each property comes as a key/value pair. For example, the os.name system property provides the name of the operating system running the JVM. Also, the directory name from which the application was invoked is provided by the JVM as a property named user.dir. To get the value of the user.dir property, you use:
System.getProperty("user.dir");

  Table 5.1 lists the system properties.

System propertyDescription
java.versionJava Runtime Environment version
java.vendorJava Runtime Environment vendor
java.vendor.urlJava vendor URL
java.homeJava installation directory
java.vm.specification.versionJava Virtual Machine specification version
java.vm.specification.vendorJava Virtual Machine specification vendor
java.vm.specification.nameJava Virtual Machine specification name
java.vm.versionJava Virtual Machine implementation version
java.vm.vendorJava Virtual Machine implementation vendor
java.vm.nameJava Virtual Machine implementation name
java.specification.versionJava Runtime Environment specification version
java.specification.vendorJava Runtime Environment specification vendor
java.specification.nameJava Runtime Environment specification name
java.class.versionJava class format version number
java.class.pathJava class path
java.library.pathList of paths to search when loading libraries
java.io.tmpdirDefault temp file path
java.compilerName of JIT compiler to use
java.ext.dirsPath of extension directory or directories
os.nameOperating system name
os.archOperating system architecture
os.versionOperating system version
file.separatorFile separator (“/” on UNIX)
path.separatorPath separator (“:” on UNIX)
line.separatorLine separator (“\n” on UNIX)
user.nameUser's account name
user.homeUser's home directory
user.dirUser's current working directory
Table 5.1: Java system properties
public static void setProperty(String property, String newValue)
You use setProperty to create a user-defined property or change the value of the current property. For instance, you can use this code to create a property named password:
System.setProperty("password", "tarzan");
And, you can retrieve it by using getProperty:
System.getProperty("password")
For instance, here is how you change the user.name property.
System.setProperty("user.name", "tarzan");
Note
A Java program can be run with a security manager, in order to restrict the running program. If this is the case, you may not be able to read the system properties or some of them. For more information, see Chapter 24, “Security.”
public static String getProperty(String key, String default)
This method is similar to the single argument getProperty method, but returns a default value if the specified property does not exist.
public static java.util.Properties getProperties()
This method returns all system properties. The return value is a java.util.Properties object. The Properties class is a subclass of java.util.Hashtable (discussed in Chapter 11, “The Collections Framework”).
For example, the following code uses the list method of the Properties class to iterate and display all system properties on the console.
java.util.Properties properties = System.getProperties();
properties.list(System.out);
java.util.Scanner
You use a Scanner object to scan a piece of text. In this chapter, we will only concentrate on its use to receive keyboard input.
Receiving keyboard input with Scanner is easy. All you need to do is instantiate the Scanner class by passing System.in. Then, to receive user input, call the next method on the instance. The next method buffers the characters the user input from the keyboard or other devices until the user presses Enter. It then returns a String containing the characters the user entered excluding the carriage-return character sequence. Listing 5.3 demonstrates the use of Scanner to receive user input.
Listing 5.3: Using Scanner to receive user input
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
Compared to the code in Listing 5.2, using Scanner is much simpler.
Boxing and Unboxing
Conversion from primitive types to corresponding wrapper objects and vice versa can happen automatically. Boxing refers to the conversion of a primitive to a corresponding wrapper instance, such as an int to a java.lang.Integer. Unboxing is the conversion of a wrapper instance to a primitive type, such as Byte to byte.
Here is an example of boxing.
Integer number = 3; // assign an int to Integer
Here is an example of unboxing.
Integer number = new Integer(100);
int[] ints = new int[2];
ints[0] = number;
ints is an int array and in the last line you assign an Integer object to its first member. The compiler unboxes number before assigning it to the first member of ints.
Varargs
Varargs is a Java feature that allows methods to have a variable length of argument list.
In Chapter 4, you learned that every method has a signature. For example, here is the signature of the getInteger method of the java.lang.Integer class.
public static Integer getInteger(String nm, Integer val)
There are two parameters in the argument list, indicating that you must pass two arguments when invoking the method.
Without varargs, if you want the flexibility of passing a variable number of arguments to a method, you had to wrap the arguments in an array. The main method is a good example of this technique, and this was discussed in the section “Arrays” earlier in this chapter. The signature of the main method is reprinted here.
public static void main(String[] args)
If you understand arrays well, varargs is also easy to comprehend. Basically, instead of an array, you use a type with ellipses in the signature. Therefore, using the varargs version, the mainmethod can be written this way.
public static void main(String... args)
The ellipsis says that there is zero or more arguments of this type.
If an argument list contains both fixed arguments (arguments that must exist) and variable arguments, the variable arguments must come last.
In the background, the variable arguments are still passed in as an array, therefore the type of each variable argument must be the same. Also, since varargs are passed as an array, inside your method you will get an array. The code in Listing 5.4 is a rewrite of the code in Listing 5.3.
Listing 5.4: Using varargs
package app05;
public class MainMethodTest {
    public static void main(String... args) {
        for (String arg : args) {
            System.out.println(arg);
        }
    }
}
Note that if the user passes no argument, you get an array with a size of zero. There is no need to check if the array is null. Therefore, the following two methods are different.
public void doIt1(String... args)
 
public void doIt2(String[] args)
doIt1 allows you to pass no argument or any number of String arguments whereas doIt2 demands an array of Strings or null.
For users of your class, using varargs is easier because they can simply list the arguments, there is no need to create an array and populate it with the arguments.
Read also the section “The format and printf Methods” that illustrates some practical uses of varargs.
The format and printf Methods
A popular example of varargs can be found in the format method of the java.lang.String and java.io.PrintStream classes. Here is its signature.
public static String format(String formatString, Object... args)
This method returns a String formatted using the specified format string and arguments. The format pattern must follow the rules specified in the java.util.Formatter class and you can read them in the JavaDoc for the Formatter class. A brief description of these rules are as follows.
To specify an argument, use the notation %s, which denotes the next argument in the array. For example, the following is a method call to the printf method.
String firstName = "John";
String lastName = "Adams";
System.out.format("First name: %s. Last name: %s",
        firstName, lastName);
This prints the following string to the console:
First name: John. Last name: Adams
Without varargs, you have to do it in a more cumbersome way.
String firstName = "John";
String lastName = "Adams";
System.out.println("First name: " + firstName +
        ". Last name: " + lastName);
Note
The printf method in java.io.PrintStream is an alias for format.
The formatting example described here is only the tip of the iceberg. The formatting feature is much more powerful than that and you are encourage to explore it by reading the Javadoc for the Formatter class.
Summary
In this chapter you have examined several important classes such as java.lang.String, arrays, java.lang.System, and java.util.Scanner. You have also learned two concepts: boxing/unboxing and variable arguments. The last section covered the implementation of varargs in java.lang.String and java.io.PrintStream.
Questions
1. What does it mean when we say that Strings are immutable objects?
2. How did you receive user input without Scanner? And, how would you do it with Scanner?
3. Are wrapper classes still useful boxing and unboxing happens automatically in Java?
4. How do you resize an array?

5. What is varargs?

Comments

Popular posts from this blog

My Response is on my own Website : Best Quality Backlink Strategy

Why is Digital Marketing Important? What are the Advantages of Digital Marketing?

Hottest Snapchat girls usernames online