4.8. Review notes

This section lists the main points covered in this chapter.

The class String:

  • The class String represents an immutable sequence of characters.
  • A String variable can be initialized by using the operator new or by using the assignment operator with String literal values.
  • String objects created using a String literal without the new operator are placed in a pool of String objects. Whenever the JRE receives a new request to initialize a String variable using the assignment operator, it checks whether a String object with the same value already exists in the pool. If one is found, it returns the object reference for the existing String object from the pool.
  • String objects created using the operator new are never placed in the pool of String objects.
  • The comparison operator (==) compares String references, whereas the equals method compares the String values.
  • None of the methods defined in the class String can modify its value.
  • The method charAt(int index) retrieves a character at a specified index of a String.
  • The method indexOf can be used to search a String for the occurrence of a char or a String, starting from the first position or a specified position.
  • The method substring can be used to retrieve a portion of a String object. The substring method doesn’t include the character at the end position.
  • The trim method will return a new String by removing all the leading and trailing white spaces from a String. This method doesn’t remove any white space within a String.
  • You can use the method length to retrieve the length of a String.
  • The method startsWith determines whether a String starts with a specified String.
  • The method endsWith determines whether a String ends with a specified String.
  • It’s a common practice to use multiple String methods in a single line of code. When chained, the methods are evaluated from left to right.
  • You can use the concatenation operators + and += and comparison operators != and == with String objects.
  • The Java language provides special support for concatenating String objects by using the operators + and +=.
  • The right technique for comparing two String values for equality is to use the method equals defined in the String class. This method returns a true value if the object being compared isn’t null and is a String object that represents the same sequence of characters as the object to which it’s being compared.
  • The comparison operator == determines whether both of the reference variables are referring to the same String objects. Hence, it’s not the right operator for comparing String values.

The class StringBuilder:

  • The class StringBuilder is defined in the package java.lang and represents a mutable sequence of characters.
  • The StringBuilder class is very efficient when a user needs to modify a sequence of characters often. Because it’s mutable, the value of a StringBuilder object can be modified without the need to create a new StringBuilder object.
  • A StringBuilder object can be created using its constructors, which can accept either a String object, another StringBuilder object, an int value to specify the capacity of StringBuilder, or nothing.
  • The methods charAt, indexOf, substring, and length defined in the class StringBuilder work in the same way as methods with the same names defined in the class String.
  • The append method adds the specified value at the end of the existing value of a StringBuilder object.
  • The insert method enables you to insert characters at a specified position in a StringBuilder object. The main difference between the append and insert methods is that the insert method enables you to insert the requested data at a particular position, whereas the append method allows you to add the requested data only at the end of the StringBuilder object.
  • The method delete removes the characters in a substring of the specified StringBuilder. The method deleteCharAt removes the char at the specified position.
  • Unlike the class String, the class StringBuilder doesn’t define the method trim.
  • The method reverse reverses the sequence of characters of a StringBuilder.
  • The replace method in the class StringBuilder replaces a sequence of characters, identified by their position, with another String.
  • In addition to using the method substring, you can also use the method subSequence to retrieve a subsequence of a StringBuilder object.

Arrays:

  • An array is an object that stores a collection of values.
  • An array itself is an object.
  • An array can store two types of data—a collection of primitive data types and a collection of objects.
  • You can define one-dimensional and multidimensional arrays.
  • A one-dimensional array is an object that refers to a collection of scalar values.
  • A two-dimensional (or more) array is referred to as a multidimensional array.
  • A two-dimensional array refers to a collection of objects, in which each of the objects is a one-dimensional array.
  • Similarly, a three-dimensional array refers to a collection of two-dimensional arrays, and so on.
  • Multidimensional arrays may or may not contain the same number of elements in each row or column.
  • The creation of an array involves three steps: declaration of an array, allocation of an array, and initialization of array elements.
  • An array declaration is composed of an array type, a variable name, and one or more occurrences of [].
  • Square brackets can follow either the variable name or its type. In the case of multidimensional arrays, it can follow both of them.
  • An array declaration creates a variable that refers to null.
  • Because no elements of an array are created when it’s declared, it’s invalid to define the size of an array with its declaration.
  • Array allocation allocates memory for the elements of an array. When you allocate memory for an array, you must specify its dimensions, such as the number of elements the array should store.
  • Because an array is an object, it’s allocated using the keyword new, followed by the type of value that it stores, and then its size.
  • Once allocated, all the array elements store their default values. Elements of an array that store objects refer to null. Elements of an array that store primitive data types store 0 for integer types (byte, short, int, long), 0.0 for decimal types (float and double), false for boolean, or /u0000 for char data.
  • To access an element in a two-dimensional array, use two array position values.
  • You can combine all the steps of array declaration, allocation, and initialization into a single step.
  • When you combine array declaration, allocation, and initialization in a single step, you can’t specify the size of the array. The size of the array is calculated by the number of values that are assigned to the array.
  • You can declare and allocate an array but choose not to initialize its elements (for example, int[] a = new int[5];).
  • The Java compiler doesn’t check the range of the index positions at which you try to access an array element. The code throws an ArrayIndexOutOfBounds-Exception exception if the requested index position doesn’t fall in the valid range at runtime.
  • A multidimensional array can be asymmetrical; it may or may not define the same number of columns for each of its rows.
  • The type of an array can also be an interface or abstract class. Such an array can be used to store objects of classes that inherit from the interface type or the abstract class type.
  • The type of an array can also be java.lang.Object. Because all classes extend the java.lang.Object class, elements of this array can refer to any object.
  • All the arrays are objects and can access the variable length, which specifies the number or components stored by the array.
  • Because all arrays are objects, they inherit and can access all methods from the class Object.

ArrayList:

  • ArrayList is one of the most widely used classes from the Collections framework. It offers the best combination of features offered by an array and the List data structure.
  • An ArrayList is like a resizable array.
  • Unlike arrays, you may not specify an initial size to create an ArrayList.
  • ArrayList implements the interface List and allows null values to be added to it.
  • ArrayList implements all list operations (add, modify, and delete values).
  • ArrayList allows duplicate values to be added to it and maintains its insertion order.
  • You can use either Iterator or ListIterator or an enhanced for loop to iterate over the items of an ArrayList.
  • ArrayList supports generics, making it type safe.
  • Internally, an array of type java.lang.Object is used to store the data in an ArrayList.
  • You can add a value to an ArrayList either at its end or at a specified position by using the method add.
  • An iterator (Iterator or ListIterator) lets you remove elements as you iterate through an ArrayList. It’s not possible to remove elements from an ArrayList while iterating through it using a for loop.
  • An ArrayList preserves the order of insertion of its elements. ListIterator and the enhanced for loop will return the elements in the order in which they were added to the ArrayList.
  • You can use the method set to modify an ArrayList by either replacing an existing element in ArrayList or modifying its existing values.
  • remove(int) removes the element at the specified position in the list.
  • remove(Object o) removes the first occurrence of the specified element from the list, if it’s present.
  • You can add multiple elements to an ArrayList from another ArrayList or any other class that’s a subclass of Collection by using the method addAll.
  • You can remove all the ArrayList elements by calling the method clear on it.
  • get(int index) returns the element at the specified position in the list.
  • size() returns the number of elements in the list.
  • contains(Object o) returns true if the list contains the specified element.
  • indexOf(Object o) returns the index of the first occurrence of the specified element in the list, or –1 if the list doesn’t contain the element.
  • lastIndexOf(Object o) returns the index of the last occurrence of the specified element in the list, or –1 if the list doesn’t contain the element.
  • The method clone defined in the class ArrayList returns a shallow copy of this ArrayList instance. Shallow copy means that the method creates a new instance of the ArrayList to be cloned, but the ArrayList elements aren’t copied.
  • You can use the method toArray to return an array containing all the elements in ArrayList in sequence from the first to the last element.

Comparing objects for equality:

  • Any Java class can define a set of rules to determine whether two objects should be considered equal.
  • The method equals is defined in the class java.lang.Object. All the Java classes directly or indirectly inherit this class.
  • The default implementation of the equals method only checks whether two object variables refer to the same object.
  • Because instance variables are used to store the state of an object, it’s common to compare the values of the instance variables to determine whether two objects should be considered equal.
  • When you override the equals method in your class, make sure that you use the correct method signature for the equals method.
  • The Java API defines a contract for the equals method, which should be taken care of when you implement the method in any of your classes.
  • According to the contract of the method equals, if a null value is passed to it, the method equals should return false.
  • If the equals method modifies the value of any of the instance variables of the method parameter passed to it, or of the object on which it is called, it will violate the contract.

LocalDate:

  • LocalDate can be used to store dates like 2015-12-27 without time or time zones.
  • LocalDate instances are immutable.
  • The LocalDate constructor is marked private.
  • Use LocalDate’s overloaded static method of() to instantiate it:

    • public static LocalDate of(int year, int month, int dayOfMonth)
    • public static LocalDate of(int year, Month month, int dayOfMonth)
  • The of() methods will throw a DateTimeException when values passed to it are out of range.
  • In date classes released with Java 8, the January month is represented by int value 1 and not 0. The date classes defined with or prior to Java 7 represent January using 0.
  • LocalDate’s static method now() returns the current date from the system clock as a LocalDate instance.
  • Use LocalDate’s static method parse() to parse a string in the format 2016-02-27 to instantiate LocalDate.
  • If you pass invalid values to parse() or of(), you’ll get a DateTimeParse-Exception. The format of the string passed to parse() must be exactly of the format 9999-99-99. The month and date values passed to parse() must be of two digits; a single digit is considered an invalid value. For days and months with a value 1–9, pass 01–09.
  • You can use LocalDate’s instance methods like getXX() to query LocalDate on its year, month, and date values:

    • getDayOfMonth()
    • getDayOfWeek()
    • getDayOfYear()
    • getMonth()
    • getMonthValue()
    • getYear()
  • LocalDate’s instance minusXX() methods return a copy of its value after subtracting the specified days, months, weeks, or years from it:

    • minusDays()
    • minusMonths()
    • minusWeeks()
    • minusYears()
  • LocalDate is immutable. All the methods that seem to manipulate its value return a copy of the LocalDate instance on which it’s called.
  • The plusXX() methods return a copy of LocalDate’s value after adding the specified days, months, or year to it:

    • plusDays()
    • plusMonths()
    • plusWeeks()
    • plusYears()
  • The withXX() methods return a copy of LocalDate’s value replacing the specified day, month, or year in it:

    • withDayOfMonth()
    • withDayOfYear()
    • withMonth()
    • withYear()
  • All additions, subtractions, or replacements to LocalDate consider leap years.
  • Despite the verbs used in the previous methods (add, subtract, replace), none of them actually modifies an existing LocalDate—all of them return a new instance with the requested changes applied.
  • The LocalDate class defines overloaded atTime() instance methods. These methods combine LocalDate with time to create and return LocalDateTime, which stores both the date and time.
  • Use the method toEpochDay() to convert LocalDate to the epoch date—the count of days from January 1, 1970.

LocalTime:

  • It stores time in the format hours-minutes-seconds (without a time zone).
  • It stores time to nanosecond precision.
  • LocalTime is immutable.
  • You can instantiate LocalTime using LocalTime’s static method of() that accepts hours, minutes, seconds, and nanoseconds.
  • The of() method uses a 24-hour clock to specify the hour value.
  • The of() method will throw a runtime exception, DateTimeException, if you pass an invalid range of values to it.
  • LocalTime doesn’t define a method to pass a.m. or p.m. Use values 0–23 to define hours. If you pass out-of-range values to either hours, minutes, or seconds, you’ll get a runtime exception.
  • To get the current time from the system clock, use the static method now().
  • You can parse a string to instantiate LocalTime by using its static method parse(). You can either pass a string in the format 15:08:23 (hours:minutes:seconds) or parse any text using DateTimeFormatter.
  • If you pass invalid string values to parse(), the code will compile but will throw a runtime exception. If you don’t pass a DateTimeFormatter, the format of the string passed to parse() must be exactly of the format 99:99:99. The hours and minutes values passed to parse() must be of two digits; a single digit is considered an invalid value. For hours and minutes with a value 0–9, pass 00–09.
  • You can use constants from the LocalTime class to work with predefined times:

    • LocalTime.MIN—Minimum supported time, that is, 00:00
    • LocalTime.MAX—Maximum supported time, that is, 23:59:59.999999999
    • LocalTime.MIDNIGHT—Time when day starts, that is, 00:00
    • LocalTime.NOON—Noontime, that is, 12:00
  • You can use instance methods like getXX() to query LocalTime on its hour, minutes, seconds, and nanoseconds. All these methods return an int value.
  • The correct method names to query LocalTime are getHour(), getMinute(), getSecond(), and getNano(). Watch out for exam questions that use invalid method names like getHours(), getMinutes(), getSeconds(), or getNanoSeconds().
  • You can use the instance methods isAfter() and isBefore() to check whether a time is after or before the specified time.
  • You can use the instance methods minusHours(), minusMinutes(), minusSeconds(), and minusNanos() to create and return a copy of LocalTime instances with the specified period subtracted.
  • Unlike the getXXX() methods, the minusXXX() methods use the plural form: getHour() versus minusHours(), getMinute() versus minusMinutes(), getSecond() versus minusSeconds(), and getNano() versus minusNanos().
  • The plusHours(), plusMinutes(), plusSeconds(), and plusNanos() methods accept long values and add the specified hours, minutes, seconds, or nanoseconds to time, returning its copy as LocalTime.
  • LocalTime is immutable. Calling any method on an instance won’t modify its value.
  • The withHour(), withMinute(), withSecond(), and withNano() methods accept an int value and return a copy of LocalTime with the specified value altered.
  • The class LocalTime defines the method atDate(), which can be passed a Local-Date instance to create a LocalDateTime instance.

LocalDateTime:

  • LocalDateTime stores a value like 2050-06-18T14:20:30:908765 (year-month-dayThours:minutes:seconds:nanoseconds).
  • The LocalDateTime class uses the letter T to separate date and time values in its printed value.
  • You can consider this class to offer the functionality of both the LocalDate and LocalTime classes. This class defines similar methods as those defined by the LocalDate and LocalTime classes.

Period:

  • The Period class represents a date-based amount in years, months, and days, like 2 years, 5 months, and 10 days. To work with time-based amounts in seconds and nanoseconds, you can use the Duration class.
  • You can add or subtract Period instances from LocalDate and LocalDateTime classes.
  • Period is an immutable class.
  • The Period class defines multiple factory methods to create its instances. The static methods of(), ofYears(), ofMonths(), ofWeeks(), and ofDays() accept int values to create periods of years, months, weeks, or days.
  • A Period of 35 days is not stored as 1 month and 5 days. Its individual elements, that is, days, months, and years, are stored the way it is initialized.
  • You can define positive or negative periods of time. You can define Period instances representing 15 or -15 days.
  • You can also parse a string to instantiate Period by using its static method parse. This method parses string values of the format PnYnMnD or PnW, where n represents a number and the letters (P, Y, M, D, and W) represent parse, year, month, day, and week. These letters can exist in lower- or uppercase. Each string must start with the letter p or P and must include at least one of the four sections, that is, year, month, week, or day.
  • If you pass invalid string values to parse(), the code will compile but will throw a runtime exception.
  • You can also use the static method between(LocalDate dateInclusive, LocalDate dateExclusive) to instantiate Period.
  • The static method between accepts two LocalDate instances and returns a Period instance representing number of years, days, and months between the two dates. The first date is included, but the second date is excluded in the returned Period.
  • The Period class implements the interface TemporalAmount, so it can be used with the methods plus() and minus() defined in the classes LocalDateTime and LocalDate.
  • Because Period instances can represent positive or negative periods (like 15 days or -15 days), you can subtract days from a LocalDate or LocalDateTime by calling the method plus.
  • Similarly, you can use the method minus() with classes LocalDate and LocalDateTime to subtract a period of years, months, weeks, or days.
  • You can use the instance methods getYears(), getMonths(), and getDays() to query a Period instance on its years, months, and days. All these methods return an int value.
  • When you initialize a Period instance with days more than 31 or months more than 12, it doesn’t recalculate its years, months, or days components.
  • You can query whether any of three units of a Period is negative using the methods isNegative and isZero. A Period instance is negative if all three of its units are zero.
  • You can use instance methods minus(TemporalAmount), minusDays(long), minus-Months(long), minusYears(long), and multipliedBy(int) to create and return a copy of Period instances with the specified period subtracted or modified.
  • In the class Period, both the getXXX() methods and minusXXX() methods use the plural form: getYears(), minusHours().
  • When you subtract a Period instance using the minusXXX() methods, its individual elements are subtracted. Subtracting P10D from P1M returns P1M-10D and not P20D.
  • The method multipliedBy(int) in the class Period is used to modify all elements of a Period instance. Period doesn’t define divideBy.
  • Adding a Period of 10 months to a Period of 5 months gives 15 months, not 1 year and 3 months.
  • The method toTotalMonths() returns the total number of months in the period by multiplying the number of years by 12 and adding the number of months.

DateTimeFormatter

  • Defined in the package java.time.format, the class DateTimeFormatter can be used to format and parse date and time objects.
  • A DateTimeFormatter can define rules to format or parse a date object, time object, or both.
  • You can instantiate or access a DateTimeFormatter object in multiple ways:

    • By calling a static ofXXX method, passing it a FormatStyle value
    • By accessing public static fields of DateTimeFormatter
    • By using a static method ofPattern and passing it a string value
  • To instantiate a DateTimeFormatter using ofXXX methods, pass it a FormatStyle value (FormatStyle.FULL, FormatStyle.LONG, FormatStyle.MEDIUM, or FormatStyle.SHORT).
  • You can access a DateTimeFormatter object by using the public and static fields of this class: BASIC_ISO_DATE, ISO_DATE, ISO_TIME, and ISO_DATE_TIME.
  • The method format in DateTimeFormatter formats a date or time object to a String using the rules of the formatter.
  • To parse a date or time object, you can use either the parse method in date/time objects or the parse method in the DateTimeFormatter class.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.138.195