Wednesday, November 11, 2015

Chapter-8 Numbers and Dates

Chapter 8
Numbers and Dates
In Java numbers are represented by the primitives byteshortintlongfloatdouble, and their wrapper classes, which were explained in Chapter 5, “Core Classes.” Dates can be represented by different classes, most commonly by the java.util.Date class. There are three issues when working with numbers and dates: parsing, formatting, and manipulation.
Parsing deals with the conversion of a string into a number or a date. Parsing is commonplace because Java programs often require user input and user input is received as a String. If a program expects a number or a date but receives a String, then the String has to be converted into a number or a date. Conversion is not always straightforward. Before conversion can take place, you first need to read the String and check if it contains characters that make up a number or a date. For example, “123data” is not a number even though it starts with a number. “123.45” is a float, but not an integer. “12/25/2011” looks like a date, but this is only valid if the program is expecting a date in mm/dd/yyyy format. Converting a string to a number is called number parsing, and converting a string to a date is referred to as date parsing.
Once you have a number or a date, you may want to display it in a specific format. For instance, 1000000 may be displayed as 1,000,000 and 12/25/2011 as Dec 25, 2011. This is number formatting and date formatting, respectively.
This chapter discusses number and date parsing, as well as number and date formatting. These tasks are easily achieved in Java as it provides classes for this purpose. In addition, thejava.lang.Math class, which provides methods to perform mathematical operations, is also discussed. On top of that, there is a section on the java.util.Calendar class, a utility for manipulating dates.
Number Parsing
A Java program may require that the user input a number that will be processed or become an argument of a method. For example, a currency converter program would need the user to type in a value to be converted. You can use the java.util.Scanner class to receive user input. However, the input will be a String, even though it represents a number. Before you can work with the number, you need to parse the string. The outcome of a successful parsing is a number.
Therefore, the purpose of number parsing is to convert a string into a numeric primitive type. If parsing fails, for example because the string is not a number or a number outside the specified range, your program can throw an exception.
The wrappers of primitives—the ByteShortIntegerLongFloat, and Double classes—provide static methods for parsing strings. For example, Integer has a parseInteger method with the following signature.
public static int parseInt(String s) throws NumberFormatException
This method parses a String and returns an int. If the String does not contain a valid integer representation, a NumberFormatException is thrown.
For example, the following snippet uses parseInt to parse the string “123” to 123.
int x = Integer.parseInt("123");
Similarly, Byte provides a parseByte method, Long a parseLong method, Short a parseShort method, Float a parseFloat method, and Double a parseDouble method.
For example, the NumberTest class in Listing 8.1 takes user input and parses it. If the user types in an invalid number, an error message will be displayed.
Listing 8.1: Parsing numbers (NumberTest.java)
package app08;
import java.util.Scanner;
public class NumberTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String userInput = scanner.next();
        try {
            int i = Integer.parseInt(userInput);
            System.out.println("The number entered: " + i);
        } catch (NumberFormatException e) {
            System.out.println("Invalid user input");
        }
    }
}
Number Formatting
Number formatting helps make numbers more readable. For example, 1000000 is more readable if printed as 1,000,000 (or 1.000.000 if your locale uses . to separate the thousands). For number formatting Java offers the java.text.NumberFormat class, which is an abstract class. Since it is abstract, you cannot create an instance using the new keyword. Instead, you instantiate its subclass java.text.DecimalFormat, which is a concrete implementation of NumberFormat.
NumberFormat nf = new DecimalFormat();
However, you should not call the DecimalFormat class's constructor directly. Instead, use the the NumberFormat class's getInstance static method. This method may return an instance ofDecimalFormat but might also return an instance of a subclass other than DecimalFormat.
Now, how do you use NumberFormat to format numbers, such as 1234.56? Easy, simply pass the numbers to its format method and you'll get a String. However, should number 1234.56 be formatted as 1,234.56 or 1234,56? Well, it really depends in which side of the Atlantic you live. If you are in the US, you may want 1,234.56. If you live in Germany, however, 1234,56 makes more sense. Therefore, before you start using the format method, you want to make sure you get the correct instance of NumberFormat by telling it where you live, or, actually, in what locale you want it formatted. In Java, a locale is represented by the java.util.Locale class, which I'll explain in Chapter 19, “Internationalization.” For now, remember that the getInstance method of the NumberFormat class also has an overload that accepts a java.util.Locale.
public NumberFormat getInstance(java.util.Locale locale)
If you pass Locale.Germany to the method, you'll get a NumberFormat object that formats numbers according to the German locale. If you pass Locale.US, you'll obtain one for the US number format. The no-argument getInstance method returns a NumberFormat object with the user's computer locale.
Listing 8.2 shows the NumberFormatTest class that demonstrates how to use the NumberFormat class to format a number.
Listing 8.2: The NumberFormatTest class
package app08;
import java.text.NumberFormat;
import java.util.Locale;
public class NumberFormatTest {
    public static void main(String[] args) {
        NumberFormat nf = NumberFormat.getInstance(Locale.US);
        System.out.println(nf.getClass().getName());
        System.out.println(nf.format(123445));
    }
}
When run, the output of the execution is
java.text.DecimalFormat
123,445
The first output line shows that a java.text.DecimalFormat object was produced upon calling NumberFormat.getInstance. The second shows how the NumberFormat formats the number 123445 into a more readable form.
Number Parsing with java.text.NumberFormat
You can use the parse method of NumberFormat to parse numbers. One of this method's overloads has the following signature:
public java.lang.Number parse(java.lang.String source)
        throws ParseException
Note that parse returns an instance of java.lang.Number, the parent of such classes as IntegerLong, etc.
The java.lang.Math Class
The Math class is a utility class that provides static methods for mathematical operations. There are also two static final double fields: E and PIE represents the base of natural logarithms (e). Its value is close to 2.718. PI is the ratio of the circumference of a circle to its diameter (pi). Its value is 22/7 or approximately 3.1428.
Some of the methods in the Math class are given below.
public static double abs(double a)
Returns the absolute value of the specified double..
public static double acos(double a)
Returns the arc cosine of an angle, in the range of 0.0 through pi.
public static double asin(double a)
Returns the arc sine of an angle, in the range of −pi/2 through pi/2.
public static double atan(double a)
Returns the arc tangent of an angle, in the range of −pi/2 through pi/2.
public static double cos(double a)
Returns the cosine of an angle.
public static double exp(double a)
Returns Euler's number e raised to the power of the specified double.
public static double log(double a)
Returns the natural logarithm (base e) of the specified double.
public static double log10(double a)
Returns the base 10 logarithm of the specified double.
public static double max(double a, double b)
Returns the greater of the two specified double values.
public static double min(double a, double b)
Returns the smaller of the two specified double values.
The java.util.Date Class
There are at least two classes to use when working with dates and times. The first is java.util.Date, a class normally used to represent dates and times. The second is java.util.Calendar, often used for manipulating dates. In addition, times can also be represented as a long. See the discussion of the currentTimeMillis method of the java.lang.System class in Chapter 5, “Core Classes.”
Date has two constructors that you can safely use (the other constructors are deprecated):
public Date()
public Date(long time)
The no-arg constructor creates a Date representing the current date and time. The second constructor creates a Date that represents the specified number of milliseconds since January 1, 1970, 00:00:00 GMT.
The Date class features several useful methods, two of them are after and before.
public boolean after(Date when)
 
public boolean before(Date when)
The after method returns true if this date is a later time than the when argument. Otherwise, it returns false. The before method returns true if this date is before the specified date and returns false otherwise.
For example, the following code prints “date1 before date2” because the first date represents a time that is one millisecond earlier than the second.
Date date1 = new Date(1000);
Date date2 = new Date(1001);
if (date1.before(date2)) {
    System.out.println("date1 before date2");
} else {
    System.out.println("date1 not before date2");
}
Many of the methods in Date, such as getDategetMonthgetYear, are deprecated. You should not use these methods. Instead, use similar methods in the java.util.Calendar class.
The java.util.Calendar Class
The java.util.Date class has methods that allow you to construct a Date object from date components, such as the day, month, and year. However, these methods are deprecated. You should use java.util.Calendar instead.
To obtain a Calendar object, use one of the two static getInstance methods. Here are their signatures:
public static Calendar getInstance()
 
public static Calendar getInstance(Locale locale)
The first overload returns an instance that employs the computer's locale.
There's a lot you can do with a Calendar. For example, you can call its getTime method to obtain a Date object. Here is its signature:
public final Date getTime();
The resulting Date object, needless to say, contains components you initially passed to construct the Calendar object. In other words, if you construct a Calendar object that represents May 7, 2000 00:00:00, the Date object obtained from its getTime method will also represent May 7, 2000 00:00:00.
To obtain a date part, such as the hour, the month, or the year, use the get method. A first glance at its signature does not reveal much on how to use this method.
public int get(int field)
To use it, pass a valid field to the get method. A valid field is one of the following values: Calendar.YEARCalendar.MONTHCalendar.DATECalendar.HOUR,Calendar.MINUTECalendar.SECOND, and Calendar.MILLISECOND.
get(Calendar.YEAR) returns an int representing the year. If it is year 2010, you get 2010. get(Calendar.MONTH) returns a zero-based index of the month, with 0 representing January and 11 representing December. The others (get(Calendar.DATE)get(Calendar.HOUR), and so on) return a number representing the date/time unit.
The last thing worth mentioning: if you already have a Date object and want to make use of the methods in Calendar, you can construct a Calendar object by using the setTimemethod:
public void setTime(Date date)
Here is an example:
// myDate is a Date
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
To change a date/time component, call its set method:
public void set(int field, int value)
For example, to change the month component of a Calendar object to December, write this.
calendar.set(Calendar.MONTH, Calendar.DECEMBER)
There are also set method overloads for changing multiple components at the same time:
public void set(int year, int month, int date)
public void set(int year, int month, int date,
        int hour, int minute, int second)
Date Parsing and Formatting with DateFormat
Java's answer to date parsing and formatting is the java.text.DateFormat and java.text.SimpleDateFormat classes. DateFormat is an abstract class with static getInstance methods that allows you to obtain an instance of a subclass. SimpleDateFormat is a concrete implementation of DateFormat that is easier to use than its parent. This section covers both classes.
DateFormat
DateFormat supports styles and patterns. There are four styles for formatting a Date. Each style is represented by an int value. The four int fields that represent the styles are:
images DateFormat.SHORT. For example, 12/2/11
images DateFormat.MEDIUM. For example, Dec 2, 2011
images DateFormat.LONG. For example, December 2, 2011
images DateFormat.FULL. For example, Friday, December 2, 2011

When you create a DateFormat, you need to decide which style you will be using for parsing or formatting. You cannot change a DateFormat's style once you create it, but you can definitely have multiple instances of DateFormat that support different styles.
To obtain a DateFormat instance, call this static method.
public static DateFormat getDateInstance(int style)
where style is one of DateFormat.SHORTDateFormat.MEDIUMDateFormat.Long, or DateFormat.FULL. For example, the following code creates a DateFormat instance having the MEDIUM style.
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM)
To format a Date object, call its format method:
public final java.lang.String format(java.util.Date date)
To parse a string representation of a date, use the parse method. Here is the signature of parse.
public java.util.Date parse(java.lang.String date)
        throws ParseException
Note that you must compose your string according to the style of the DateFormat.
Listing 8.3 shows a class that parses and formats a date.
Listing 8.3: The DateFormatTest class
package app08;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
public class DateFormatTest {
    public static void main(String[] args) {
        DateFormat shortDf =
                DateFormat.getDateInstance(DateFormat.SHORT);
        DateFormat mediumDf =
                DateFormat.getDateInstance(DateFormat.MEDIUM);
        DateFormat longDf =
                DateFormat.getDateInstance(DateFormat.LONG);
        DateFormat fullDf =
                DateFormat.getDateInstance(DateFormat.FULL);
        System.out.println(shortDf.format(new Date()));
        System.out.println(mediumDf.format(new Date()));
        System.out.println(longDf.format(new Date()));
        ySstem.out.println(fullDf.format(new Date()));
 
        // parsing
        try {
            Date date = shortDf.parse("12/12/2006");
        } catch (ParseException e) {
        }
    }
}
Another point to note when working with DateFormat (and SimpleDateFormat) is leniency. Leniency refers to whether or not a strict rule will be applied at parsing. For example, if aDateFormat is lenient, it will accept this String: Jan 32, 2011, despite the fact that such a date does not exist. In fact, it will take the liberty of converting it to Feb 1, 2011. If a DateFormatis not lenient, it will not accept dates that do not exist. By default, a DateFormat object is lenient. The isLenient method and setLenient method allow you to check a DateFormat's leniency and change it.
public boolean isLenient()
 
public void setLenient(boolean value)
SimpleDateFormat
SimpleDateFormat is more powerful than DateFormat because you can use your own date patterns. For example, you can format and parse dates in dd/mm/yyyy, mm/dd/yyyy, yyyy-mm-dd, and so on. All you need to do is pass a pattern to a SimpleDateFormat constructor.
SimpleDateFormat is a better choice than DateFormat especially for parsing. Here is one of the constructors in SimpleDateFormat.
public SimpleDateFormat(java.lang.String pattern)
        throws java.lang.NullPointerException,
        java.lang.IllegalArgumentException
The complete rules for a valid pattern can be read in the Javadoc for the SimpleDateFormat class. The more commonly used patterns can be used by a combination of y (representing a year digit), M (representing a month digit) and d (representing a date digit). Examples of patterns are dd/MM/yyyy, dd-MM-yyyy, MM/dd/yyyy, yyyy-MM-dd.
Listing 8.4 shows a class that uses SimpleDateFormat for parsing and formatting.
Listing 8.4: The SimpleDateFormatTest class
package app08;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatTest {
    public static void main(String[] args) {
        String pattern = "MM/dd/yyyy";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            Date date = format.parse("12/31/2011");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // formatting
        System.out.println(format.format(new Date()));
    }
}
Summary
In Java you use primitives and wrapper classes to represent number and the java.util.Date class to represents dates. There are three types of operations that you frequently perform when dealing with number and dates: parsing, formatting and manipulation. This chapter showed how to perform them.
Number parsing is achieved through the use of the parseXXX methods in wrapper classes, such as parseInteger in java.lang.Integer and parseLong in java.lang.Long. Thejava.text.NumberFormat class can be used for number parsing and number formatting. For complex mathematical operations, use the static methods in java.lang.Math.
Date manipulation, on the other hand, is best done with the help of the java.util.Calendar class. Date parsing and formatting can be performed by using the java.text.DateFormat and the java.text.SimpleDateFormat classes.
Questions
1. What can you do with the java.lang.Math class's static methods?
2. What do you use to represents dates?

3. What class should you use if you want to define you own date pattern?

Error handling chapter-7

Chapter 7
Error Handling
Error handling is an important feature in any programming language. A good error handling mechanism makes it easier for programmers to write robust applications and to prevent bugs from creeping in. In some languages, programmers are forced to use multiple if statements to detect all possible conditions that might lead to an error. This could make code excessively complex. In a larger program, this practice could easily lead to spaghetti like code.
Java has a very nice approach to error handling by using the try statement. With this strategy, part of the code that could potentially lead to an error is isolated in a block. Should an error occur, this error is caught and resolved locally. This chapter teaches you how.
Catching Exceptions
You can isolate code that may cause a runtime error using the try statement, which normally is accompanied by the catch and finally statements. Such isolation typically occurs in a method body. If an error is encountered, Java stops the processing of the try block and jump to the catch block. Here you can gracefully handle the error or notify the user by ‘throwing’ ajava.lang.Exception object. Another scenario is to re-throw the exception or a new Exception object back to the code that called the method. It is then up to the client how he or she would handle the error. If a thrown exception is not caught, the application will stop abruptly.
This is the syntax of the try statement.
try {
    [code that may throw an exception]
} [catch (ExceptionType-1 e) {
    [code that is executed when ExceptionType-1 is thrown]
}] [catch (ExceptionType-2 e) {
    [code that is executed when ExceptionType-2 is thrown]
}]
  ...
} [catch (ExceptionType-n e) {
    [code that is executed when ExceptionType-n is thrown]
}]
[finally {
    [code that runs regardless of whether an exception was thrown]]
}]
The steps for error handling can be summarized as follows:
1. Isolate code that could lead to an error in the try block.
2. For each individual catch block, write code that is to be executed if an exception of that particular type occurs in the try block.
3. In the finally block, write code that will be run whether or not an error has occurred.

Note that the catch and finally blocks are optional, but one of them must exist. Therefore, you can have try with one or more catch blocks or try with finally.
The previous syntax shows that you can have more than one catch block. This is because the code can throw different types of exceptions. When an exception is thrown from a tryblock, control is passed to the first catch block. If the type of exception thrown matches or is a subclass of the exception in the first catch block, the code in the catch block is executed and then control goes to the finally block, if one exists.
If the type of the exception thrown does not match the exception type in the first catch block, the JVM goes to the next catch block and does the same thing until it finds a match. If no match is found, the exception object will be thrown to the method caller. If the caller does not put the offending code that calls the method in a try block, the program will crash.
To illustrate the use of this error handling, consider the NumberDoubler class in Listing 7.1. When the class is run, it will prompt you for input. You can type anything, including non-digits. If your input is successfully converted to a number, it will double it and print the result. If your input is invalid, the program will print an “Invalid input” message.
Listing 7.1: The NumberDoubler class
import java.util.Scanner;
public class NumberDoubler {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.next();
        try {
            double number = Double.parseDouble(input);
            System.out.printf("Result: %s", number);
        } catch (NumberFormatException e) {
            System.out.println("Invalid input.");
        }
    }
}
The NumberDoubler class uses the java.util.Scanner class to take user input (Scanner was discussed in Chapter 5, “Core Classes”).
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
It then uses the static parseDouble method of the java.lang.Double class to convert the string input to a double. Note that the code that calls parseDouble resides in a try block. This is necessary because the parseDouble method may throw a java.lang.NumberFormatException, as indicated by the signature of the parseDouble method.
public static double parseDouble(String s)
        throws NumberFormatExcpetion
The throws statement in the method signature tells you that it could throw a NumberFormatException and it is the responsibility of the method caller to catch it.
Without the try block, invalid input will give you this embarrassing error message before the system crashes:
Exception in thread "main" java.lang.NumberFormatException:
try without catch
A try statement can be used with finally without a catch block. You normally use this syntax to ensure that some code always gets executed whether or not an unexpected exception has been thrown in the try block. For example, after opening a database connection, you want to make sure its close method is called after you're done with the connection. To illustrate this scenario, consider the following pseudocode that opens a database connection.
Connection connection = null;
try {
 
    // open connection
    // do something with the connection and perform other tasks
 
} finally {
    if (connection != null) {
        // close connection
    }
}
If something unexpected occurs in the try block, the close method will always be called to release the resource.
Catching Multiple Exceptions
Java 7 and later allows you to catch multiple exceptions in a single catch block if the caught exceptions are to be handled by the same code. The syntax of the catch block is as follows, two exceptions being separated by the pipe character |.
catch(exception-1 | exception-2 ... e) {
 
    // handle exceptions
 
}
For example, the java.net.ServerSocket class's accept method can throw four exceptions: java.nio.channels.IllegalBlockingModeExceptionjava.net.SocketTimeoutException,java.lang.SecurityException, and java.io.Exception. If, say, the first three exceptions are to be handled by the same code, you can write your try block like this:
try {
    serverSocket.accept();
} catch (SocketTimeoutException | SecurityException |
        IllegalBlockingModeException e) {
 
    // handle exceptions
 
} catch (IOException e) {
 
    // handle IOException
 
}
The try-with-resources Statement
Many Java operations involve some kind of resource that has to be closed after use. Before JDK 7, you used finally to make sure a close method is guaranteed to be called:
try {
 
    // open resource
 
} catch (Exception e) {
 
} finally {
 
    // close resource
}
This syntax can be tedious especially if the close method can throw an exception and can be null. For example, here's a typical code fragment to open a database connection.
Connection connection = null;
try {
 
    // create connection and do something with it
 
} catch (SQLException e) {
 
} finally {
    if (connection != null) {
        try {
            connection.close();
        } catch (SQLException e) {
        }
    }
}
You see, you need quite a bit of code in the finally block just for one resource, and it's not uncommon to have to open multiple resources in a single try block. JDK 7 adds a new feature, the try-with-resource statement, to make resource closing automatic. Its syntax is as follows.
try ( resources ) {
 
    // do something with the resources
 
} catch (Exception e) {
    // do something with e
}
For example, here is opening a database connection would look like in Java 7.
Connection connection = null;
try (Connection connection = openConnection();
        // open other resources, if any) {
 
    // do something with connection
 
} catch (SQLException e) {
 
}
Not all resources can be automatically closed. Only resource classes that implement java.lang.AutoCloseable can be automatically closed. Fortunately, in JDK 7 many input/output and database resources have been modified to support this feature. You'll see more examples of try-with-resources in Chapter 13, “Input/Output” and Chapter 22, “Java Database Connectivity.”
The java.lang.Exception Class
Erroneous code can throw any type of exception. For example, an invalid argument may throw a java.lang.NumberFormatException, and calling a method on a null reference variable throws a java.lang.NullPointerException. All Java exception classes derive from the java.lang.Exception class. It is therefore worthwhile to spend some time examining this class.
Among others, the Exception class has the following methods:
public String toString()
Returns the description of the exception.
public void printStackTrace()
Prints the description of the exception followed by a stack trace for the Exception object. By analyzing the stack trace, you can find out which line is causing the problem. Here is an example of what printStackTrace may print on the console.
java.lang.NullPointerException
        at MathUtil.doubleNumber(MathUtil.java:45)
        at MyClass.performMath(MyClass.java: 18)
        at MyClass.main(MyClass.java: 90)
This tells you that a NullPointerException has been thrown. The line that throws the exception is Line 45 of the MathUtil.java class, inside the doubleNumber method. ThedoubleNumber method was called by MyClass.performMath, which in turns was called by MyClass.main.

Most of the time a try block is accompanied by a catch block that catches the java.lang.Exception in addition to other catch blocks. The catch block that catches Exception must appear last. If other catch blocks fail to catch the exception, the last catch will do that. Here is an example.
try {
    // code
} catch (NumberFormatException e) {
    // handle NumberFormatException
} catch (Exception e) {
    // handle other exceptions
}
You may want to use multiple catch blocks in the code above because the statements in the try block may throw a java.lang.NumberFormatException or other type of exception. If the latter is thrown, it will be caught by the last catch block.
Be warned, though: The order of the catch blocks is important. You cannot, for example, put a catch block for handling java.lang.Exception before any other catch block. This is because the JVM tries to match the thrown exception with the argument of the catch blocks in the order of appearance. java.lang.Exception catches everything; therefore, the catch blocks after it would never be executed.
If you have several catch blocks and the exception type of one of the catch blocks is derived from the type of another catch block, make sure the more specific exception type appears first. For example, when trying to open a file, you need to catch the java.io.FileNotFoundException just in case the file cannot be found. However, you may want to make sure that you also catch java.io.IOException so that other I/O-related exceptions are caught. Since FileNotFoundException is a child class of IOException, the catch block that handlesFileNotFoundException must appear before the catch block that handles IOException.
Throwing an Exception from a Method
When catching an exception in a method, you have two options to handle the error that occurs inside the method. You can either handle the error in the method, thus quietly catching the exception without notifying the caller (this has been demonstrated in the previous examples), or you can throw the exception back to the caller and let the caller handle it. If you choose the second option, the calling code must catch the exception that is thrown back by the method.
Listing 7.2 presents a capitalize method that changes the first letter of a String to upper case.
Listing 7.2: The capitalize method
public String capitalize(String s) throws NullPointerException {
    if (s == null) {
        throw new NullPointerException(
                "Your passed a null argument");
    }
    Character firstChar = s.charAt(0);
    String theRest = s.substring(1);
    return firstChar.toString().toUpperCase() + theRest;
}
If you pass a null to capitalize, it will throw a new NullPointerException. Pay attention to the code that instantiates the NullPointerException class and throws the instance:
throw new NullPointerException(
        "Your passed a null argument");
The throw keyword is used to throw an exception. Don't confuse it with the throws statement which is used at the end of a method signature to indicate that an exception of a given type may be thrown from the method.
The following example shows code that calls capitalize.
String input = null;
try {
    String capitalized = util.capitalize(input);
    System.out.println(capitalized);
} catch (NullPointerException e) {
    System.out.println(e.toString());
}
Note
A constructor can also throw an exception.
User-Defined Exceptions
You can create a user-defined exception by subclassing java.lang.Exception. There are several reasons for having a user-defined exception. One of them is to create a customized error message.
For example, Listing 7.3 shows the AlreadyCapitalizedException class that derives from java.lang.Exception.
Listing 7.3: The AlreadyCapitalizedException class
package app07;
public class AlreadyCapitalizedException extends Exception {
    public String toString() {
        return "Input has already been capitalized";
    }
}
You can throw an AlreadyCapitalizedException from the capitalize method in Listing 7.2. The modified capitalize method is given in Listing 7.4.
Listing 7.4: The modified capitalize method
public String capitalize(String s)
        throws NullPointerException, AlreadyCapitalizedException {
    if (s == null) {
        throw new NullPointerException(
                "Your passed a null argument");
    }
    Character firstChar = s.charAt(0);
    if (Character.isUpperCase(firstChar)) {
        throw new AlreadyCapitalizedException();
    }
    String theRest = s.substring(1);
    return firstChar.toString().toUpperCase() + theRest;
}
Now, the capitalize method may throw one of two exceptions. You comma-delimit multiple exceptions in a method signature.
Clients that call capitalize must now catch both exceptions. This code shows a call to capitalize.
StringUtil util = new StringUtil();
String input = "Capitalize";
try {
    String capitalized = util.capitalize(input);
    System.out.println(capitalized);
} catch (NullPointerException e) {
    System.out.println(e.toString());
} catch (AlreadyCapitalizedException e) {
    e.printStackTrace();
}
Since NullPointerException and AlreadyCapitalizedException do not have a parent-child relationship, the order of the catch blocks above is not important.
When a method throws multiple exceptions, rather than catch all the exceptions, you can simply write a catch block that handles java.lang.Exception. Rewriting the code above:
StringUtil util = new StringUtil();
String input = "Capitalize";
try {
    String capitalized = util.capitalize(input);
    System.out.println(capitalized);
} catch (Exception e) {
    System.out.println(e.toString());
}
While it's more concise, the latter lacks specifics and does not allow you to handle each exception separately.
Final Words on Exception Handling
The try statement imposes some performance penalty. Therefore, do not use it over-generously. If it is not hard to test for a condition, then you should do the testing rather than depending on the try statement. For example, calling a method on a null object throws a NullPointerException. Therefore, you could always surround a method call with a try block:
try {
    ref.method();
...
However, it is not hard at all to check if ref is null prior to calling methodA. Therefore, the following code is better because it eliminates the try block.
if (ref != null) {
    ref.methodA();
}
Summary
This chapter discussed the use of structured error handling and presented examples for each case. You have also been introduced to the java.lang.Exception class and its properties and methods. The chapter concluded with a discussion of user-defined exceptions.
Question
1. What is the advantage of the try statement?





2. Can a try statement be used with finally and without catch?







3. What is try-with-resources?

Inheritance chapter-6

Chapter 6
Inheritance
Inheritance is a very important feature of object-oriented programming (OOP). It is what makes code extensible in any OOP language. Extending a class is also called inheriting or subclassing. In Java, by default all classes are extendible, but you can use the final keyword to prevent classes from being subclassed. This chapter explains inheritance in Java.
An Overview of Inheritance
You extend a class by creating a new class. The former and the latter will then have a parent-child relationship. The original class is the parent class or the base class or the superclass. The new class is the child class or the subclass or the derived class of the parent. The process of extending a class in OOP is called inheritance. In a subclass you can add new methods and new fields as well as override existing methods to change their behaviors.
Figure 6.1 presents a UML class diagram that depicts a parent-child relationship between a class and a child class.

Figure 6.1: The UML class diagram for a parent class and a child class
Note that a line with an arrow is used to depict generalization, e.g. the parent-child relationship.
A child class in turn can be extended, unless you specifically make it inextensible by declaring it final. Final classes are discussed in the section “Final Classes” later in this chapter.
The benefits of inheritance are obvious. Inheritance gives you the opportunity to add some functionality that does not exist in the original class. It also gives you the chance to change the behaviors of the existing class to better suit your needs.
The extends Keyword
You extend a class by using the extends keyword in a class declaration, after the class name and before the parent class. Listing 6.1 presents a class named Parent and Listing 6.2 a class named Child that extends Parent.
Listing 6.1: The Parent class
public class Parent {
}
Listing 6.2: The Child class
public class Child extends Parent {
}
Extending a class is as simple as that.
Note
All Java classes automatically extend the java.lang.Object class. Object is the ultimate superclass in Java. Parent in Listing 6.1 by default is a subclass of Object.
Note
In Java a class can only extend one class. This is unlike C++ where multiple inheritance is allowed. However, the notion of multiple inheritance can be achieved by using interfaces in Java, as discussed in Chapter 9, “Interfaces and Abstract Classes.”
The is-a Relationship
There is a special relationship that is formed when you create a new class by inheritance. The subclass and the superclass has an “is-a” relationship.
For example, Animal is a class that represents animals. There are many types of animals, including birds, fish, and dogs, so you can create subclasses of Animal that represent specific types of animals. Figure 6.2 features the Animal class with three subclasses, BirdFish, and Dog.

Listing 6.3: Animal and its subclasses
package app06;
class Animal {
    public float weight;
    public void eat() {
    }
}
 
class Bird extends Animal {
    public int numberOfWings = 2;
    public void fly() {
    }
}
 
class Fish extends Animal {
    public int numberOfFins = 2;
    public void swim() {
    }
}
 
class Dog extends Animal {
    public int numberOfLegs = 4;
    public void walk() {
    }
}
In this example, the Animal class defines a weight field that applies to all animals. It also declares an eat method because animals eat.
The Bird class is a special type of Animal, it inherits the eat method and the weight field. Bird also adds a numberOfWings field and a fly method. This shows that the more specificBird class extends the functionality and behavior of the more generic Animal class.
A subclass inherits all public methods and fields of its superclass. For example, you can create a Dog object and call its eat method:
Dog dog = new Dog();
dog.eat();
The eat method is declared in the Animal class; the Dog class simply inherits it.
A consequence of the is-a relationship is that it is legal to assign an instance of a subclass to a reference variable of the parent type. For example, the following code is valid becauseBird is a subclass of Animal, and a Bird is always an Animal.
Animal animal = new Bird();
However, the following is illegal because there is no guarantee that an Animal is a Dog.:
Dog dog = new Animal();
Accessibility
From within a subclass you can access its superclass's public and protected methods and fields, but not the superclass's private methods. If the subclass and the superclass are in the same package, you can also access the superclass's default methods and fields.
Consider the P and C classes in Listing 6.4.
Listing 6.4: Showing accessibility
package app06;
public class P {
    public void publicMethod() {
    }
    protected void protectedMethod() {
    }
    void defaultMethod() {
    }
}
class C extends P {
    public void testMethods() {
        publicMethod();
        protectedMethod();
        defaultMethod();
    }
}
P has three methods, one public, one protected, and one with the default access level. C is a subclass of P. As you can see in the C class's testMethods method, C can access its parent's public and protected method. In addition, because C and P are in the same package, C can also access P's default method.
However, it does not mean you can expose P's non-public methods through its subclass. For example, the following code will not compile:
package test;
import app06.C;
public class AccessibilityTest {
    public static void main(String[] args) {
        C c = new C();
        c.protectedMethod();
    }
}
images
protectedMethod is P's protected method. It is not accessible from outside P, except from a subclass. Since AccessibilityTest is not a subclass of P, you cannot access P's protected method through its subclass C.
Method Overriding
When you extends a class, you can change the behavior of a method in the parent class. This is called method overriding, and this happens when you write in a subclass a method that has the same signature as a method in the parent class. If only the name is the same but the list of arguments is not, then it is method overloading. (See Chapter 4, “Objects and Classes”)
You override a method to change its behavior. To override a method, you simply have to write the new method in the subclass, without having to change anything in the parent class. You can override the superclass's public and protected methods. If the subclass and superclass are in the same package, you can also override a method with the default access level.
An example of method overriding is demonstrated by the Box class in Listing 6.5.
Listing 6.5: The Box class
package app06;
public class Box {
    public int length;
    public int width;
    public int height;
 
    public Box(int length, int width, int height) {
        this.length = length;
        this.width = width;
        this.height = height;
    }
 
    public String toString() {
        return "I am a Box.";
    }
 
    public Object clone() {
        return new Box(1, 1, 1);
    }
}
The Box class extends the java.lang.Object class. It is an implicit extension since the extends keyword is not used. Box overrides the public toString method and the protected clonemethod. Note that the clone method in Box is public whereas in Object it is protected. Increasing the visibility of a method defined in a superclass from protected to public is allowed. However, reducing visibility is illegal.
What if you create a method that has the same signature as a private method in the superclass? It is not method overriding, since private methods are not visible from outside the class.
Note
You cannot override a final method. To make a method final, use the final keyword in the method declaration. For example:
public final java.lang.String toUpperCase(java.lang.String s)
Calling the Superclass's Constructors
A subclass is just like an ordinary class, you use the new keyword to create an instance of it. If you do not explicitly write a constructor in your subclass, the compiler will implicitly add a no-argument (no-arg) constructor.
When you instantiate a child class by invoking one of its constructors, the first thing the constructor does is call the no-argument constructor of the direct parent class. In the parent class, the constructor also calls the constructor of its direct parent class. This process repeats itself until the constructor of the java.lang.Object class is reached. In other words, when you create a child object, all its parent classes are also instantiated.
This process is illustrated in the Base and Sub classes in Listing 6.6.
Listing 6.6: Calling a superclass's no-arg constructor
package app06;
class Base {
    public Base() {
        System.out.println("Base");
    }
    public Base(String s) {
        System.out.println("Base." + s);
    }
}
public class Sub extends Base {
    public Sub(String s) {
        System.out.println(s);
    }
    public static void main(String[] args) {
        Sub sub = new Sub("Start");
    }
}
If you run the Sub class, you'll see this on the console:
Base
Start
This proves that the first thing that the Sub class's constructor does is invoke the Base class's no-arg constructor. The Java compiler has quietly changed Sub's constructor to the following without saving the modification to the source file.
public Sub(String s) {
    super();
    System.out.println(s);
}
The keyword super represents an instance of the direct superclass of the current object. Since super is called from an instance of Subsuper represents an instance of Base, its direct superclass.
You can explicitly call the parent's constructor from a subclass's constructor by using the super keyword, but super must be the first statement in the constructor. Using the superkeyword is handy if you want another constructor in the superclass to be invoked. For example, you can modify the constructor in Sub to the following.
public Sub(String s) {
    super(s);
    System.out.println(s);
}
This constructor calls the single argument constructor of the parent class, by using super(s). As a result, if you run the class you will see the following on the console.
Base.Start
Start
Now, what if the superclass does not have a no-arg constructor and you do not make an explicit call to another constructor from a subclass? This is illustrated in the Parent and Childclasses in Listing 6.7.
Listing 6.7: Implicit calling to the parent's constructor that does not exist
package app06;
class Parent {
    public Parent(String s) {
        System.out.println("Parent(String)");
    }
}
 
public class Child extends Parent {
    public Child() {
    }
}
This will generate a compile error because the compiler adds an implicit call to the no-argument constructor in Parent, while the Parent class has only one constructor, the one that accepts a String. You can remedy this situation by explicitly calling the parent's constructor from the Child class's constructor:
public Child() {
    super(null);
}
Note
It actually makes sense for a child class to call its parent's constructor from its own constructor because an instance of a subclass must always be accompanied by an instance of each of its parents. This way, calls to a method that is not overridden in a child class will be passed to its parent until the first in the hierarchy is found.
Calling the Superclass's Hidden Members
The super keyword has another purpose in life. It can be used to call a hidden member or an overridden method in a superclass. Since super represents an instance of the direct parent, super.memberName returns the specified member in the parent class. You can access any member in the superclass that is visible from the subclass. For example, Listing 6.8 shows two classes that have a parent-child relationship: Tool and Pencil.
Listing 6.8: Using super to access a hidden member
package app06;
class Tool {
    public String toString() {
        return "Generic tool";
    }
}
 
public class Pencil extends Tool {
    public String toString() {
        return "I am a Pencil";
    }
 
    public void write() {
        System.out.println(super.toString());
        System.out.println(toString());
    }
 
    public static void main(String[] args) {
        Pencil pencil = new Pencil();
        pencil.write();
    }
}
The Pencil class overrides the toString method in Tool. If you run the Pencil class, you will see the following on the console.
Generic tool
I am a Pencil
Unlike calling a parent's constructor, invoking a parent's member does not have to be the first statement in the caller method.
Type Casting
You can cast an object to another type. The rule is, you can only cast an instance of a subclass to its parent class. Casting an object to a parent class is called upcasting. Here is an example, assuming that Child is a subclass of Parent.
Child child = new Child();
Parent parent = child;
To upcast a Child object, all you need to do is assign the object to a reference variable of type Parent. Note that the parent reference variable cannot access the members that are only available in Child.
Because parent in the snippet above references an object of type Child, you can cast it back to Child. This time, it is called downcasting because you are casting an object to a class down the inheritance hierarchy. Downcasting requires that you write the child type in brackets. For example:
Child child = new Child();
Parent parent = child;// parent pointing to an instance of Child
Child child2 = (Child) parent; // downcasting
Downcasting to a subclass is only allowed if the parent class reference is already pointing to an instance of the subclass. The following will generate a compile error.
Object parent = new Object();
Child child = (Child) parent; // illegal downcasting, compile error
Final Classes
You can prevent others from extending your class by making it final using the keyword final in the class declaration. final may appear after or before the access modifier. For example:
public final class Pencil
final public class Pen
The first form is more common.
Even though making a class final makes your code slightly faster, the difference is too insignificant to notice. Design consideration, and not speed, should be the reason you make a class final. For example, the java.lang.String class is final because the designer of the class did not want us to change the behavior of the String class.
The instanceof Keyword
The instanceof keyword can be used to test if an object is of a specified type. It is normally used in an if statement and its syntax is.
if (objectReference instanceof type)
where objectReference references an object being investigated. For example, the following if statement returns true.
String s = "Hello";
if (s instanceof java.lang.String)
However, applying instanceof on a null reference variable returns false. For example, the following if statement returns false.
String s = null;
if (s instanceof java.lang.String)
Also, since a subclass “is a” type of its superclass, the following if statement, where Child is a subclass of Parent, returns true.
Child child = new Child();
if (child instanceof Parent)    // evaluates to true
Summary
Inheritance is one of the fundamental principles in object-oriented programming. Inheritance makes code extensible. In Java all classes by default extend the java.lang.Object class. To extend a class, use the extends keyword. Method overriding is another OOP feature directly related to inheritance. It enables you to change the behavior of a method in the parent class. You can prevent your class from being subclassed by making it final.
Questions

1. Does a subclass inherit its superclass's constructors?





2. Why is it legal to assign an instance of a subclass to a superclass variable?





3. What is the difference between method overridi
ng a
n




d method overloading?

4. Why is it necessary for an instance of a subclass to be accompanied by an instance of each parent?