Strings
String
objects are typically created with String
literals but can be constructed via constructors defined in the String
class.
String
objects are immutable; many methods on String
s produce new String
s that are related to the original (such as the original converted to all upper case) but the original String
cannot be changed.
String
objects can be concatenated using the +
or +=
operator, resulting in a new String
object. (The +=
operator changes the value of the variable it is applied to but doesn to change the String
that used to be the value of the variable.)
- Non-
String
values can also be concatenated with a String
object. This causes an implicit conversion of the values to String
objects. Primitive values and null
are converted to their standard literal form and all other reference types are converted using their toString
method.
- Escape sequences in Strings start with a
\
and allow us to write special characters in String
literals. Escape sequences used in this course include \"
, \\
, and \n
. The first two encode the escaped character which would otherwise have a special meaning in the string literal syntax and \n
encodes a newline character.
- A
String
has index values from 0 to length – 1. Attempting to access indices outside this range (i.e. less than 0 or greater than or equal to the length of the String) will result in an StringIndexOutOfBoundsException
.
- You can think of the index as the number that tells you how far from the front of the string a given character is. Thus the second character in a
String
has index 1 because there is one character ahead of it. And the first character has index 0 because there are zero characters ahead of it. The length of the string is not a valid index because there is no character in an \i{n}-character string that has \i{n} characters in front of it.
- The constructor
String(String str)
constructs a new String object that represents the same sequence of characters as str. There is almost no reason to ever use this constructor.
- The method
int length()
returns the number of characters in a String object
- The method
String substring(int from, int to)
returns the substring beginning at index from and ending at index to − 1.
- The method
String substring(int from)
is equivalent to substring(from, length())
.
- The method
int indexOf(String str)
returns the index of the first occurrence of str; returns -1 if not found.
- The method
boolean equals(Object other)
— returns true
if other is a String and its text is the same as the text of the String
equals
was called on. Otherwise returns false
.\note{In the [AP Java Quick Reference] they list this method as boolean equals(String other)
. That is not correct but the difference doesn’t matter for anything on the exam.}
- The method
int compareTo(String other)
returns a value < 0 if the String
is alphabetically less than other
; returns zero if it is equals
to other
; and returns a value > 0 if it is greater than other
.
- A one-character
String
at index i
in the String
s
can be obtained by calling s.substring(i, i + 1)
.
toString
- The
toString
method is inherited from java.lang.Object
and is frequently overridden to provide a concise, human-readable representation of an object.
- If
System.out.print
or System.out.println
is passed an object, that object’s toString
method is called, and the returned String
is printed.
toString
is also used when a reference type is included in a String
concatenation expression.
ArrayLists
- The
ArrayList
class is part of the java.util
package and needs to be imported to be used in a class.
- An
ArrayList
object is mutable and contains object references.
- The no-argument
ArrayList
constructor constructs an empty list.
- Indices for an
ArrayList
start at 0 and end at size() − 1
, inclusive.
- Trying to access an index outside the valid range (e.g. with the
get
, set
or remove
method) will cause an IndexOutOfBoundsException
to be thrown.
ArrayList
is a generic type which means we can write the type ArrayList<E>
to mean an ArrayList
that can only contain values of the type E
. E.g. ArrayList<String>
is a list of String
s.
E
is called a “type parameter” because it is filled in with a specific type like String
. Type parameters have to be reference types.
- When
ArrayList<E>
is specified, the types of the parameters in methods that accept elements, e.g. add
, and the return types of methods that return elements, e.g. get
, will be E
.
- The type
ArrayList<E>
is preferred over the so-called “raw” type ArrayList
because it allows the compiler to find errors that would otherwise be found at run-time.
- Typically you invoke the
ArrayList
constructor as ArrayList<>()
, i.e. with nothing between the <>
s as the Java compiler will infer the correct element type.
- Iteration statements can be used to access all the elements in an
ArrayList
. This is called traversing the ArrayList
.
ArrayList
s can be iterated over with an enhanced for loop.
- Changing the size of an
ArrayList
while traversing it using an enhanced for
loop will cause a ConcurrentModificationException
to be thrown. When using an enhanced for
loop to traverse an ArrayList, you should not add or remove elements.
- There are standard
ArrayList
algorithms that utilize traversals to insert and delete elements.
- Deleting elements during a traversal of an
ArrayList
requires using special techniques to avoid skipping elements.
- Most algorithms that work with arrays work equally well with
ArrayList
s after switching .length
to .size()
and array accesses and assignments to get
and set
calls.
- Some algorithms require multiple
String
, array, or ArrayList
objects to be traversed simultaneously.
- The method
int size()
returns the number of elements in the list
- The method
boolean add(E obj)
appends obj to end of list; returns true
- The method
void add(int index, E obj)
inserts obj at position index which must be a valid index or the current size of the list, increasing the size of the list by one.
- The method
E get(int index)
returns the element at position index in the list
- The method
E set(int index, E obj)
replaces the element at position index with obj; returns the element formerly at position index.
- The method
E remove(int index)
removes the element from position index, moving elements at position index + 1 and higher to the left, and decreases the size of the list by one. Returns the element formerly at position index.
Wrapper classes
- The College Board is weirdly obsessed with wrapper classes.
- The
Integer
, Double
, and Boolean
classes exist primarily because generic types like ArrayList
can only use reference types as their type parameters. The wrapper classes exist to “wrap” a primitive value in an object so it can be put into an ArrayList
or used with another generic class.
- In general you do not need to explicitly use wrapper classes because the Java compiler will automatically wrap a primitive type used in a context where its wrapper type is expected. This is called “autoboxing”. Conversely, if a wrapper type is used in a context where the corresponding primitive type is expected it will be automatically “unboxed” and converted to the primitive value.
- You will almost never write code where you declare the type of a variable, or parameter or the return type of a method to be one of the wrapper types; just use primitive types and let autoboxing take care of things.
- Then one place you will have to use
Integer
, Double
, and Boolean
is when you declare an ArrayList
: You have to write ArrayList<Integer>
rather than ArrayList<int>
, ArrayList<Double>
rather than ArrayList<double>
and ArrayList<Boolean>
rather than ArrayList<boolean>
.
- The constructor
Integer(int value)
constructs a new Integer
object that represents the specified int
value\note{The Integer
constructor has been deprecated since Java 9. According to the Javadocs “It is rarely appropriate to use this constructor. The static factory valueOf(int)
is generally a better choice, as it is likely to yield significantly better space and time performance.”}. This is roughly equivalent to what happens when an int is autoboxed.
- The method
int intValue()
returns the value of an Integer
as an int
. This is equivalent to what happens when an Integer
is unboxed. You should never need to use this method since auto unboxing should take care of it for you.
- The constant variable
Integer.MAX_VALUE
is maximum value that can be represented by an int
.
- The constant variable
Integer.MIN_VALUE
is the minimum value that can be represented by an int
.
- The following
Double
constructor and method—including what they do and when they are used—are part of the [AP Java Quick Reference]:
- The constructor
Double(double value)
constructs a new Double
object that represents the specified double
value\note{The Double
constructor has been deprecated since Java 9. According to the Javadocs: “It is rarely appropriate to use this constructor. The static factory valueOf(double)
is generally a better choice, as it is likely to yield significantly better space and time performance.”}. This is roughly equivalent to what happens when a double
is autoboxed.
- The method
double doubleValue()
— Returns the value of a Double
as a double
. This is equivalent to what happens when a Double is unboxed. You should never need to use this method since auto unboxing should take care of it for you.
- The College Board does not expect you to know about any methods from the
Boolean
class.
Math
- The
Math
class (java.lang.Math
) is a utility class that contains a ton of static
methods that provide various mathematical functions. If you are doing anything involving math more complicated than you can do on a four-function calculator you should look into this class.
- For the AP you should know about as
Math.abs
, Math.pow
, Math.sqrt
, and Math.random
.
- A few other useful
Math
methods are Math.min
, Math.max
, and Math.round
.