SlideShare a Scribd company logo
OCA EXAM 8
CHAPTER 3 – Core Java APIs
By İbrahim Kürce
Brief of OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808
Jeanne Boyarsky, Scott Selikoff
Core Java APIs
 The OCA exam expects you to know the core data structures and classes
used in Java, and in this chapter readers will learn about the most common
methods available. For example, String and StringBuilder are used for text
data. An array and an ArrayList are used when you have multiple values. A
variety of classes are used for working with dates. In this chapter, you'll also
learn how to determine whether two objects are equal.
 API stands for application programming interface. In Java, an interface is
something special. In the context of an API, it can be a group of class or
interface definitions that gives you access to a service or functionality.
Strings
 A string is basically a sequence of characters; here's an example:
String Concatenation
 The OCA exam creators like string concatenation because the + operator
can be used in two ways within the same line of code. There aren't a lot of
rules to know for this, but you have to know them well:
 If both operands are numeric, + means numeric addition.
 If either operand is a String, + means concatenation.
 The expression is evaluated left to right.
String Concatenation
 There is only one more thing to know about concatenation, but it is an easy
one. In this example, you just have to remember what + = does. s + = "2"
means the same thing as s = s + “2".
 To review the rules one more time: use numeric addition if two numbers are
involved, use concatenation otherwise, and evaluate from left to right.
Immutability
 Once a String object is created, it is not allowed to change. It cannot be
made larger or smaller, one of the characters inside it. and you cannot
change
 Mutable is another word for changeable. Immutable is the opposite— an
object that can't be changed once it's created. On the OCA exam, you
need to know that String is immutable.
The String Pool
 Since strings are everywhere in Java, they use up a lot of memory. In some
production applications, they can use up 25– 40 percent of the memory in
the entire program. Java realizes that many strings repeat in the program
and solves this issue by reusing common ones. The string pool, also known
as the intern pool, is a location in the Java virtual machine (JVM) that
collects all these strings.
 The former says to use the string pool normally. The second says “No, JVM. I
really don't want you to use the string pool. Please create a new object for
me even though it is less efficient.”
Important String Methods
 The String class has dozens of methods. Luckily, you need to know only a
handful for the exam.
 length() The method length() returns the number of characters in the String. The
method signature is as follows: int length().
 charAt() The method charAt() lets you query the string to find out what
character is at a specific index. The method signature is as follows: char
charAt(int index).
 indexOf() The method indexOf() looks at the characters in the string and finds
the first index that matches the desired value. indexOf can work with an
individual character or a whole String as input. It can also start from a requested
position.
Important String Methods
Important String Methods
 substring() The method substring() also looks for characters in a string. It
returns parts of the string. The first parameter is the index to start with for the
returned string. As usual, this is a zero-based index.
 toLowerCase() and toUpperCase() After that mental exercise, it is nice to
have methods that do exactly what they sound like!
Important String Methods
 equals() and equalsIgnoreCase() The equals() method checks whether two
String objects contain exactly the same characters in the same order. The
equalsIgnoreCase() method checks whether two String objects contain the
same characters with the exception that it will convert the characters' case
if needed.
 startsWith() and endsWith() The startsWith() and endsWith() methods look at
whether the provided value matches part of the String.
 contains() The contains() method also looks for matches in the String.
 replace() The replace() method does a simple search and replace on the
string.
Important String Methods
 trim() The trim() method removes whitespace from the beginning and end
of a String.
 Method Chaining
Using the StringBuilder Class
 This sequence of events continues, and after 26 iterations through the loop,
a total of 27 objects are instantiated, most of which are immediately
eligible for garbage collection.
 This is very inefficient. The StringBuilder class creates a String without storing
all those interim String values. Unlike the String class, StringBuilder is not
immutable.
Mutability and Chaining
 When we chained String method calls, the result was a new String with the
answer. Chaining StringBuilder objects doesn't work this way. Instead, the
StringBuilder changes its own state and returns a reference to itself!
 Did you say both print "abcdefg"? Good. There's only one StringBuilder
object here.
Creating a StringBuilder
 Size vs. Capacity
 Size is the number of characters currently in the sequence, and capacity is
the number of characters the sequence can currently hold. Since a String is
immutable, the size and capacity are the same. The number of characters
appearing in the String is both the size and capacity.
Important StringBuilder Methods
 charAt(), indexOf(), length(), and substring() These four methods work
exactly the same as in the String class.
 append() It adds the parameter to the StringBuilder and returns a reference
to the current StringBuilder.
 StringBuilder append( String str)
 Notice that we said one of the method signatures. There are more than 10
method signatures.
 insert() The insert() method adds characters to the StringBuilder at the
requested index and returns a reference to the current StringBuilder.
Important StringBuilder Methods
 delete() and deleteCharAt() The delete() method is the opposite of the
insert() method. It removes characters from the sequence and returns a
reference to the current StringBuilder. The deleteCharAt() method is
convenient when you want to delete only one character.
 reverse() It reverses the characters in the sequences and returns a
reference to the current.
 toString() The last method converts a StringBuilder into a String.
StringBuilder vs. StringBuffer
 StringBuilder was added to Java in Java 5. If you come across older code,
you will see StringBuffer used for this purpose. StringBuffer does the same
thing but more slowly because it is thread safe.
 In theory, you don't need to know about StringBuffer on the exam at all.
Understanding Equality
Understanding Equality
 This works because the authors of the String class implemented a standard
method called equals to check the values inside the String rather than the
String itself. If a class doesn't have an equals method, Java determines
whether the references point to the same object— which is exactly what =
= does.
 In case you are wondering, the authors of StringBuilder did not implement
equals(). If you call equals() on two StringBuilder instances, it will check
reference equality.
Understanding Java Arrays
 An array is an area of memory on the heap with space for a designated
number of elements.
 A String is implemented as an array with some methods that you might
want to use when dealing with characters specifically.
 A StringBuilder is implemented as an array where the array object is
replaced with a new bigger array object when it runs out of space to store
all the characters.
 In other words, an array is an ordered list. It can contain duplicates. You will
learn about data structures that cannot contain duplicates for the OCP
exam.
Creating an Array of Primitives
 int[] numbers1 = new int[ 3];
Creating an Array of Primitives
 All four of these statements do the exact same thing:
 int[] ids, types; // two variables of type int[].
 int ids[], types; // This time we get one variable of type int[] and one
variable of type int. Be careful on exam.
Creating an Array with Reference
Variables
 You can choose any Java type to be the type of the array.
 We can call equals() because an array is an object. It returns true because
of reference equality.
 int is a primitive; int[] is an object.
 You don't have to know this for the exam, but [L means it is an array,
java.lang.String is the reference type, and 160bc7c0 is the hash code.
 Note:Since Java 5, Java has provided a method that prints an array nicely:
java.util.Arrays.toString( bugs) would print [cricket, beetle, ladybug]. Not on
exam.
Creating an Array with Reference
Variables
 You wanted to force a bigger type into a smaller type
 At line 7, at runtime, the code throws an ArrayStoreException. You don't
need to memorize the name of this exception, but you do need to know
that the code will throw an exception.
Using an Array
 The exam will test whether you are being observant by trying to access
elements that are not in the array. Can you tell why each of these throws
an ArrayIndexOutOfBoundsException for our array of size 10?
 The length is always one more than the maximum valid index. Finally, the for
loop incorrectly uses < = instead of <, which is also a way of referring to that
10th element.
Sorting
 You can pass almost any array to Arrays.sort().
 import java.util.* // import whole package including Arrays
 import java.util.Arrays; // import just Arrays
 This code outputs 10 100 9.
Searching
 Java also provides a convenient way to search— but only if the array is already
sorted.
 3 isn't in the list, it would need to be inserted at element 1 to preserve the sorted
order. We negate and subtract 1 for consistency, getting –1 –1, also known as –
2.
Multidimensional Arrays
 Arrays are objects, and of course array components can be objects.
 String [][] rectangle = new String[ 3][ 2];
Multidimensional Arrays
 While that array happens to be rectangular in shape, an array doesn't
need to be. Consider this one:
 int[][] differentSize = {{1, 4}, {3}, {9, 8, 7}};
 Another way to create an asymmetric array is to initialize just an array's first
dimension, and define the size of each array component in a separate
statement:
Multidimensional Arrays
 This entire exercise would be easier to read with the enhanced for loop.
Understanding an ArrayList
 An array has one glaring shortcoming: you have to know how many
elements will be in the array when you create it and then you are stuck
with that choice. Just like a StringBuilder, ArrayList can change size at
runtime as needed. Like an array, an ArrayList is an ordered sequence that
allows duplicates.
 import java.util.* // import whole package including ArrayList
 import java.util.ArrayList; // import just ArrayList
 Remember that if you are shown a code snippet with a line number that
doesn't begin with 1, you can assume the necessary imports are there.
ArrayList
 As with StringBuilder, there are three ways to create an ArrayList:
 The first says to create an ArrayList containing space for the default number
of elements but not to fill any slots yet. The second says to create an
ArrayList containing a specific number of slots, but again not to assign any.
The final example tells Java that we want to make a copy of another
ArrayList.
 Java 5 introduced generics,
ArrayList
 Starting in Java 7, you can even omit that type from the right side.
 ArrayList implements an interface called List. In other words, an ArrayList is a
List.
ArrayList Methods
 You are going to see something new in the method signatures: a “class”
named E. E is used by convention in generics to mean “any class that this
array can hold.” If you didn't specify a type when creating the ArrayList, E
means Object.
 add() The add() methods insert a new value in the ArrayList. The method
signatures are as follows:
 Don't worry about the boolean return value. It always returns true.
ArrayList Methods
 remove() The remove() methods remove the first matching value in the
ArrayList or remove the element at a specified index.
 Since calling remove() with an int uses the index, an index that doesn't exist
will throw an exception. For example, birds.remove( 100) throws an
IndexOutOfBoundsException.
ArrayList Methods
 set() The set() method changes one of the elements of the ArrayList without
changing the size.
 isEmpty() and size() The isEmpty() and size() methods look at how many of
the slots are in use.
 clear() The clear() method provides an easy way to discard all elements of
the ArrayList.
 contains() The contains() method checks whether a certain value is in the
ArrayList. This method calls equals() on each element of the ArrayList.
ArrayList Methods
 equals() Finally, ArrayList has a custom implementation of equals() so you
can compare two lists to see if they contain the same elements in the same
order.
Wrapper Classes
 Up to now, we've only put String objects in the ArrayList. What happens if
we want to put primitives in? Each primitive type has a wrapper class,
which is an object type that corresponds to the primitive.
Wrapper Classes
 The first line converts a String to an int primitive. The second converts a
String to an Integer wrapper class.
 The Character class doesn't participate in the parse/ valueOf methods.
Autoboxing
 Since Java 5, you can just type the primitive value and Java will convert it to the
relevant wrapper class for you. This is called autoboxing.
 It actually outputs 1.
 If you want to remove the 2, you can write numbers.remove( new Integer( 2)) to
force wrapper class use.
Converting Between array and List
 You should know how to convert between an array and an ArrayList.
 The advantage of specifying a size of 0 for the parameter is that Java will
create a new array of the proper size for the return value.
 The original array and created array backed List are linked. When a
change is made to one, it is available in the other. It is a fixed-size list and is
also known a backed List because the array changes with it.
Sorting
 Sorting an ArrayList is very similar to sorting an array. You just use a different
helper class:
Working with Dates and Times
 In Java 8, Oracle completely revamped how we work with dates and times.
Just know that the “old way” is not on the exam.
 You need an import statement to work with the date and time classes. Most of
them are in the java.time package. import java.time.*;
 The exam doesn't cover time zones.
 LocalDate Contains just a date— no time and no time zone. A good example of
LocalDate is your birthday this year. It is your birthday for a full day regardless of
what time it is.
 LocalTime Contains just a time— no date and no time zone. A good example of
LocalTime is midnight. It is midnight at the same time every day.
 LocalDateTime Contains both a date and time but no time zone. A good
example of LocalDateTime is “the stroke of midnight on New Year's.” Midnight
on January 2 isn't nearly as special, and clearly an hour after midnight isn't as
special either.
Dates and Times
 If you do need to communicate across time zones, ZonedDateTime handles
them.
 The first one contains only a date and no time. The second contains only a
time and no date. This time displays hours, minutes, seconds, and
nanoseconds. The third contains both date and time. Java uses T to
separate the date and time when converting LocalDateTime to a String.
Dates and Times
 It is good to use the Month constants (to make the code easier to read),
you can pass the int number of the month directly.
 For months in the new date and time methods, Java counts starting from 1
like we human beings do.
 You can specify just the hour and minute, or you can add the number of
seconds. You can even add nanoseconds if you want to be very precise.
 Finally, we can combine dates and times:
Dates and Times
 The date and time classes have private constructors to force you to use the
static methods. The exam creators may try to throw something like this at
you:
Manipulating Dates and Times
 The date and time classes are immutable, just like String was.
 There are also nice easy methods to go backward in time.
Manipulating Dates and Times
 It is common for date and time methods to be chained.
 The exam also may test to see if you remember what each of the date and
time objects includes.
Working with Periods
 Period period = Period.ofMonths( 1); // create a period
 Period annually = Period.ofYears( 1); // every 1 year
 Period quarterly = Period.ofMonths( 3); // every 3 months
 Period everyThreeWeeks = Period.ofWeeks( 3); // every 3 weeks
 You cannot chain methods when creating a Period.
 Period wrong = Period.ofYears( 1). ofWeeks( 1); // every week
 There is also Duration, which is intended for smaller units of time.
 Duration isn't on the exam since it roughly works the same way as Period.
Converting to a long
 LocalDate has toEpochDay(), which is the number of days since January 1,
1970.
 LocalDateTime has toEpochTime(), which is the number of seconds since
January 1, 1970.
 LocalTime does not have an epoch method.
Formatting Dates and Times
 The date and time classes support many methods to get data out of them:
 It would be more work than necessary. Java provides a class called
DateTimeFormatter to help us out.
Formatting Dates and Times
 Predefined formats
 There are two predefined formats that can show up on the exam: SHORT
and MEDIUM. The other predefined formats involve time zones, which are
not on the exam.
 If you don't want to use one of the predefined formats, you can create
your own.
Formatting Dates and Times
Parsing Dates and Times.
 Now that you know how to convert a date or time to a formatted String,
you'll find it easy to convert a String to a date or time. Just like the format()
method, the parse() method takes a formatter as well. If you don't specify
one, it uses the default for that type.
Exam Essentials
Review Questions
Answer
 G
Question
Answer
 F
Question
Answer
 B
Question
Answer
 A
Question
Answer
 A

More Related Content

PPTX
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
PPTX
OCA Java SE 8 Exam Chapter 5 Class Design
PPTX
VỢ NHẶT slide.pptx
PPTX
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
PDF
Resume of Civil Engineer - BoQ
PDF
Introduction to c++ ppt 1
PDF
Python final ppt
KEY
Introduction to Django
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
OCA Java SE 8 Exam Chapter 5 Class Design
VỢ NHẶT slide.pptx
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
Resume of Civil Engineer - BoQ
Introduction to c++ ppt 1
Python final ppt
Introduction to Django

What's hot (20)

PPTX
OCA Java SE 8 Exam Chapter 2 Operators & Statements
PDF
The Uniform Access Principle
PPTX
String, string builder, string buffer
PDF
Collections Api - Java
PPTX
OCA Java SE 8 Exam Chapter 6 Exceptions
PPTX
Java 8 - Features Overview
PDF
Java String
PDF
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
PPT
Generics in java
PDF
Java IO
PDF
Spring annotation
PPT
Java Basics
PPTX
Methods in java
PDF
Arrays in Java
PDF
Collections In Java
PDF
Operators in java
PDF
Polymorphism In Java
PPTX
Data types in java
PPT
Java operators
PPTX
Arrays in java
OCA Java SE 8 Exam Chapter 2 Operators & Statements
The Uniform Access Principle
String, string builder, string buffer
Collections Api - Java
OCA Java SE 8 Exam Chapter 6 Exceptions
Java 8 - Features Overview
Java String
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Generics in java
Java IO
Spring annotation
Java Basics
Methods in java
Arrays in Java
Collections In Java
Operators in java
Polymorphism In Java
Data types in java
Java operators
Arrays in java
Ad

Viewers also liked (20)

PDF
1z0-808-certification-questions-sample
PPTX
The Go Programing Language 1
PPTX
Meeting10 social class
PPTX
Introduction to JAVA
PPT
Chapter 8
DOCX
Java se 8 fundamentals
PPTX
Race Class based on Chapter 8 of "Race and Racisms: A Critical Approach."
PDF
Cracking OCA and OCP Java 8 Exams
PPTX
Introduction to Java Programming
PPT
Chapter 8 socio
PPT
Notes On Software Development, Platform And Modernisation
PDF
Whitepaper Real Time Transaction Analysis And Fraudulent Transaction Detect...
PPT
Comprehensive And Integrated Approach To Project Management And Solution Deli...
PPTX
Sociolinguistics : Language Change
PDF
Project Failure Reasons and Causes
PDF
Functional Thinking - Programming with Lambdas in Java 8
PPT
Language and social class
PPTX
Consumer Behaviour -Family, social class & life cycle
PDF
Forget Big Data. It's All About Smart Data
1z0-808-certification-questions-sample
The Go Programing Language 1
Meeting10 social class
Introduction to JAVA
Chapter 8
Java se 8 fundamentals
Race Class based on Chapter 8 of "Race and Racisms: A Critical Approach."
Cracking OCA and OCP Java 8 Exams
Introduction to Java Programming
Chapter 8 socio
Notes On Software Development, Platform And Modernisation
Whitepaper Real Time Transaction Analysis And Fraudulent Transaction Detect...
Comprehensive And Integrated Approach To Project Management And Solution Deli...
Sociolinguistics : Language Change
Project Failure Reasons and Causes
Functional Thinking - Programming with Lambdas in Java 8
Language and social class
Consumer Behaviour -Family, social class & life cycle
Forget Big Data. It's All About Smart Data
Ad

Similar to OCA Java SE 8 Exam Chapter 3 Core Java APIs (20)

PPTX
String handling
PPT
Java căn bản - Chapter9
PPT
Chapter 9 - Characters and Strings
PPTX
javastringexample problems using string class
PPTX
Java string handling
PDF
ODP
Pattern Matching - at a glance
PPT
Strings Arrays
PPTX
In the given example only one object will be created. Firstly JVM will not fi...
PPT
M C6java7
PPT
Ppt chapter09
PPTX
Java interview questions 2
PPTX
package
PPTX
Java String
DOCX
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
PPT
Md08 collection api
PPT
JAVA Tutorial- Do's and Don'ts of Java programming
PPT
JAVA Tutorial- Do's and Don'ts of Java programming
PPTX
Arrays in programming
ODP
Java for newcomers
String handling
Java căn bản - Chapter9
Chapter 9 - Characters and Strings
javastringexample problems using string class
Java string handling
Pattern Matching - at a glance
Strings Arrays
In the given example only one object will be created. Firstly JVM will not fi...
M C6java7
Ppt chapter09
Java interview questions 2
package
Java String
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Md08 collection api
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Arrays in programming
Java for newcomers

More from İbrahim Kürce (7)

PPTX
Java By Comparison
PPTX
Bir Alim - Fuat Sezgin
PPTX
Effective Java - Madde 2: Birçok parametreli yapılandırıcıyla karşılaşırsan k...
PPTX
Effective Java - Madde 1: Yapılandırıcılar yerine statik fabrika(factory) met...
PPTX
Effective Java - Chapter 4: Classes and Interfaces
PPTX
Effective Java - Chapter 3: Methods Common to All Objects
PPTX
Effective Java - Chapter 2: Creating and Destroying Objects
Java By Comparison
Bir Alim - Fuat Sezgin
Effective Java - Madde 2: Birçok parametreli yapılandırıcıyla karşılaşırsan k...
Effective Java - Madde 1: Yapılandırıcılar yerine statik fabrika(factory) met...
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 2: Creating and Destroying Objects

Recently uploaded (20)

PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
history of c programming in notes for students .pptx
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
System and Network Administration Chapter 2
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Nekopoi APK 2025 free lastest update
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
medical staffing services at VALiNTRY
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
System and Network Administraation Chapter 3
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
history of c programming in notes for students .pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Operating system designcfffgfgggggggvggggggggg
System and Network Administration Chapter 2
Reimagine Home Health with the Power of Agentic AI​
PTS Company Brochure 2025 (1).pdf.......
How to Migrate SBCGlobal Email to Yahoo Easily
Nekopoi APK 2025 free lastest update
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Odoo POS Development Services by CandidRoot Solutions
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Softaken Excel to vCard Converter Software.pdf
How Creative Agencies Leverage Project Management Software.pdf
medical staffing services at VALiNTRY
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Navsoft: AI-Powered Business Solutions & Custom Software Development
System and Network Administraation Chapter 3
Odoo Companies in India – Driving Business Transformation.pdf
VVF-Customer-Presentation2025-Ver1.9.pptx

OCA Java SE 8 Exam Chapter 3 Core Java APIs

  • 1. OCA EXAM 8 CHAPTER 3 – Core Java APIs By İbrahim Kürce Brief of OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808 Jeanne Boyarsky, Scott Selikoff
  • 2. Core Java APIs  The OCA exam expects you to know the core data structures and classes used in Java, and in this chapter readers will learn about the most common methods available. For example, String and StringBuilder are used for text data. An array and an ArrayList are used when you have multiple values. A variety of classes are used for working with dates. In this chapter, you'll also learn how to determine whether two objects are equal.  API stands for application programming interface. In Java, an interface is something special. In the context of an API, it can be a group of class or interface definitions that gives you access to a service or functionality.
  • 3. Strings  A string is basically a sequence of characters; here's an example:
  • 4. String Concatenation  The OCA exam creators like string concatenation because the + operator can be used in two ways within the same line of code. There aren't a lot of rules to know for this, but you have to know them well:  If both operands are numeric, + means numeric addition.  If either operand is a String, + means concatenation.  The expression is evaluated left to right.
  • 5. String Concatenation  There is only one more thing to know about concatenation, but it is an easy one. In this example, you just have to remember what + = does. s + = "2" means the same thing as s = s + “2".  To review the rules one more time: use numeric addition if two numbers are involved, use concatenation otherwise, and evaluate from left to right.
  • 6. Immutability  Once a String object is created, it is not allowed to change. It cannot be made larger or smaller, one of the characters inside it. and you cannot change  Mutable is another word for changeable. Immutable is the opposite— an object that can't be changed once it's created. On the OCA exam, you need to know that String is immutable.
  • 7. The String Pool  Since strings are everywhere in Java, they use up a lot of memory. In some production applications, they can use up 25– 40 percent of the memory in the entire program. Java realizes that many strings repeat in the program and solves this issue by reusing common ones. The string pool, also known as the intern pool, is a location in the Java virtual machine (JVM) that collects all these strings.  The former says to use the string pool normally. The second says “No, JVM. I really don't want you to use the string pool. Please create a new object for me even though it is less efficient.”
  • 8. Important String Methods  The String class has dozens of methods. Luckily, you need to know only a handful for the exam.  length() The method length() returns the number of characters in the String. The method signature is as follows: int length().  charAt() The method charAt() lets you query the string to find out what character is at a specific index. The method signature is as follows: char charAt(int index).  indexOf() The method indexOf() looks at the characters in the string and finds the first index that matches the desired value. indexOf can work with an individual character or a whole String as input. It can also start from a requested position.
  • 10. Important String Methods  substring() The method substring() also looks for characters in a string. It returns parts of the string. The first parameter is the index to start with for the returned string. As usual, this is a zero-based index.  toLowerCase() and toUpperCase() After that mental exercise, it is nice to have methods that do exactly what they sound like!
  • 11. Important String Methods  equals() and equalsIgnoreCase() The equals() method checks whether two String objects contain exactly the same characters in the same order. The equalsIgnoreCase() method checks whether two String objects contain the same characters with the exception that it will convert the characters' case if needed.  startsWith() and endsWith() The startsWith() and endsWith() methods look at whether the provided value matches part of the String.  contains() The contains() method also looks for matches in the String.  replace() The replace() method does a simple search and replace on the string.
  • 12. Important String Methods  trim() The trim() method removes whitespace from the beginning and end of a String.  Method Chaining
  • 13. Using the StringBuilder Class  This sequence of events continues, and after 26 iterations through the loop, a total of 27 objects are instantiated, most of which are immediately eligible for garbage collection.  This is very inefficient. The StringBuilder class creates a String without storing all those interim String values. Unlike the String class, StringBuilder is not immutable.
  • 14. Mutability and Chaining  When we chained String method calls, the result was a new String with the answer. Chaining StringBuilder objects doesn't work this way. Instead, the StringBuilder changes its own state and returns a reference to itself!  Did you say both print "abcdefg"? Good. There's only one StringBuilder object here.
  • 15. Creating a StringBuilder  Size vs. Capacity  Size is the number of characters currently in the sequence, and capacity is the number of characters the sequence can currently hold. Since a String is immutable, the size and capacity are the same. The number of characters appearing in the String is both the size and capacity.
  • 16. Important StringBuilder Methods  charAt(), indexOf(), length(), and substring() These four methods work exactly the same as in the String class.  append() It adds the parameter to the StringBuilder and returns a reference to the current StringBuilder.  StringBuilder append( String str)  Notice that we said one of the method signatures. There are more than 10 method signatures.  insert() The insert() method adds characters to the StringBuilder at the requested index and returns a reference to the current StringBuilder.
  • 17. Important StringBuilder Methods  delete() and deleteCharAt() The delete() method is the opposite of the insert() method. It removes characters from the sequence and returns a reference to the current StringBuilder. The deleteCharAt() method is convenient when you want to delete only one character.  reverse() It reverses the characters in the sequences and returns a reference to the current.  toString() The last method converts a StringBuilder into a String.
  • 18. StringBuilder vs. StringBuffer  StringBuilder was added to Java in Java 5. If you come across older code, you will see StringBuffer used for this purpose. StringBuffer does the same thing but more slowly because it is thread safe.  In theory, you don't need to know about StringBuffer on the exam at all.
  • 20. Understanding Equality  This works because the authors of the String class implemented a standard method called equals to check the values inside the String rather than the String itself. If a class doesn't have an equals method, Java determines whether the references point to the same object— which is exactly what = = does.  In case you are wondering, the authors of StringBuilder did not implement equals(). If you call equals() on two StringBuilder instances, it will check reference equality.
  • 21. Understanding Java Arrays  An array is an area of memory on the heap with space for a designated number of elements.  A String is implemented as an array with some methods that you might want to use when dealing with characters specifically.  A StringBuilder is implemented as an array where the array object is replaced with a new bigger array object when it runs out of space to store all the characters.  In other words, an array is an ordered list. It can contain duplicates. You will learn about data structures that cannot contain duplicates for the OCP exam.
  • 22. Creating an Array of Primitives  int[] numbers1 = new int[ 3];
  • 23. Creating an Array of Primitives  All four of these statements do the exact same thing:  int[] ids, types; // two variables of type int[].  int ids[], types; // This time we get one variable of type int[] and one variable of type int. Be careful on exam.
  • 24. Creating an Array with Reference Variables  You can choose any Java type to be the type of the array.  We can call equals() because an array is an object. It returns true because of reference equality.  int is a primitive; int[] is an object.  You don't have to know this for the exam, but [L means it is an array, java.lang.String is the reference type, and 160bc7c0 is the hash code.  Note:Since Java 5, Java has provided a method that prints an array nicely: java.util.Arrays.toString( bugs) would print [cricket, beetle, ladybug]. Not on exam.
  • 25. Creating an Array with Reference Variables  You wanted to force a bigger type into a smaller type  At line 7, at runtime, the code throws an ArrayStoreException. You don't need to memorize the name of this exception, but you do need to know that the code will throw an exception.
  • 26. Using an Array  The exam will test whether you are being observant by trying to access elements that are not in the array. Can you tell why each of these throws an ArrayIndexOutOfBoundsException for our array of size 10?  The length is always one more than the maximum valid index. Finally, the for loop incorrectly uses < = instead of <, which is also a way of referring to that 10th element.
  • 27. Sorting  You can pass almost any array to Arrays.sort().  import java.util.* // import whole package including Arrays  import java.util.Arrays; // import just Arrays  This code outputs 10 100 9.
  • 28. Searching  Java also provides a convenient way to search— but only if the array is already sorted.  3 isn't in the list, it would need to be inserted at element 1 to preserve the sorted order. We negate and subtract 1 for consistency, getting –1 –1, also known as – 2.
  • 29. Multidimensional Arrays  Arrays are objects, and of course array components can be objects.  String [][] rectangle = new String[ 3][ 2];
  • 30. Multidimensional Arrays  While that array happens to be rectangular in shape, an array doesn't need to be. Consider this one:  int[][] differentSize = {{1, 4}, {3}, {9, 8, 7}};  Another way to create an asymmetric array is to initialize just an array's first dimension, and define the size of each array component in a separate statement:
  • 31. Multidimensional Arrays  This entire exercise would be easier to read with the enhanced for loop.
  • 32. Understanding an ArrayList  An array has one glaring shortcoming: you have to know how many elements will be in the array when you create it and then you are stuck with that choice. Just like a StringBuilder, ArrayList can change size at runtime as needed. Like an array, an ArrayList is an ordered sequence that allows duplicates.  import java.util.* // import whole package including ArrayList  import java.util.ArrayList; // import just ArrayList  Remember that if you are shown a code snippet with a line number that doesn't begin with 1, you can assume the necessary imports are there.
  • 33. ArrayList  As with StringBuilder, there are three ways to create an ArrayList:  The first says to create an ArrayList containing space for the default number of elements but not to fill any slots yet. The second says to create an ArrayList containing a specific number of slots, but again not to assign any. The final example tells Java that we want to make a copy of another ArrayList.  Java 5 introduced generics,
  • 34. ArrayList  Starting in Java 7, you can even omit that type from the right side.  ArrayList implements an interface called List. In other words, an ArrayList is a List.
  • 35. ArrayList Methods  You are going to see something new in the method signatures: a “class” named E. E is used by convention in generics to mean “any class that this array can hold.” If you didn't specify a type when creating the ArrayList, E means Object.  add() The add() methods insert a new value in the ArrayList. The method signatures are as follows:  Don't worry about the boolean return value. It always returns true.
  • 36. ArrayList Methods  remove() The remove() methods remove the first matching value in the ArrayList or remove the element at a specified index.  Since calling remove() with an int uses the index, an index that doesn't exist will throw an exception. For example, birds.remove( 100) throws an IndexOutOfBoundsException.
  • 37. ArrayList Methods  set() The set() method changes one of the elements of the ArrayList without changing the size.  isEmpty() and size() The isEmpty() and size() methods look at how many of the slots are in use.  clear() The clear() method provides an easy way to discard all elements of the ArrayList.  contains() The contains() method checks whether a certain value is in the ArrayList. This method calls equals() on each element of the ArrayList.
  • 38. ArrayList Methods  equals() Finally, ArrayList has a custom implementation of equals() so you can compare two lists to see if they contain the same elements in the same order.
  • 39. Wrapper Classes  Up to now, we've only put String objects in the ArrayList. What happens if we want to put primitives in? Each primitive type has a wrapper class, which is an object type that corresponds to the primitive.
  • 40. Wrapper Classes  The first line converts a String to an int primitive. The second converts a String to an Integer wrapper class.  The Character class doesn't participate in the parse/ valueOf methods.
  • 41. Autoboxing  Since Java 5, you can just type the primitive value and Java will convert it to the relevant wrapper class for you. This is called autoboxing.  It actually outputs 1.  If you want to remove the 2, you can write numbers.remove( new Integer( 2)) to force wrapper class use.
  • 42. Converting Between array and List  You should know how to convert between an array and an ArrayList.  The advantage of specifying a size of 0 for the parameter is that Java will create a new array of the proper size for the return value.  The original array and created array backed List are linked. When a change is made to one, it is available in the other. It is a fixed-size list and is also known a backed List because the array changes with it.
  • 43. Sorting  Sorting an ArrayList is very similar to sorting an array. You just use a different helper class:
  • 44. Working with Dates and Times  In Java 8, Oracle completely revamped how we work with dates and times. Just know that the “old way” is not on the exam.  You need an import statement to work with the date and time classes. Most of them are in the java.time package. import java.time.*;  The exam doesn't cover time zones.  LocalDate Contains just a date— no time and no time zone. A good example of LocalDate is your birthday this year. It is your birthday for a full day regardless of what time it is.  LocalTime Contains just a time— no date and no time zone. A good example of LocalTime is midnight. It is midnight at the same time every day.  LocalDateTime Contains both a date and time but no time zone. A good example of LocalDateTime is “the stroke of midnight on New Year's.” Midnight on January 2 isn't nearly as special, and clearly an hour after midnight isn't as special either.
  • 45. Dates and Times  If you do need to communicate across time zones, ZonedDateTime handles them.  The first one contains only a date and no time. The second contains only a time and no date. This time displays hours, minutes, seconds, and nanoseconds. The third contains both date and time. Java uses T to separate the date and time when converting LocalDateTime to a String.
  • 46. Dates and Times  It is good to use the Month constants (to make the code easier to read), you can pass the int number of the month directly.  For months in the new date and time methods, Java counts starting from 1 like we human beings do.  You can specify just the hour and minute, or you can add the number of seconds. You can even add nanoseconds if you want to be very precise.  Finally, we can combine dates and times:
  • 47. Dates and Times  The date and time classes have private constructors to force you to use the static methods. The exam creators may try to throw something like this at you:
  • 48. Manipulating Dates and Times  The date and time classes are immutable, just like String was.  There are also nice easy methods to go backward in time.
  • 49. Manipulating Dates and Times  It is common for date and time methods to be chained.  The exam also may test to see if you remember what each of the date and time objects includes.
  • 50. Working with Periods  Period period = Period.ofMonths( 1); // create a period  Period annually = Period.ofYears( 1); // every 1 year  Period quarterly = Period.ofMonths( 3); // every 3 months  Period everyThreeWeeks = Period.ofWeeks( 3); // every 3 weeks  You cannot chain methods when creating a Period.  Period wrong = Period.ofYears( 1). ofWeeks( 1); // every week  There is also Duration, which is intended for smaller units of time.  Duration isn't on the exam since it roughly works the same way as Period.
  • 51. Converting to a long  LocalDate has toEpochDay(), which is the number of days since January 1, 1970.  LocalDateTime has toEpochTime(), which is the number of seconds since January 1, 1970.  LocalTime does not have an epoch method.
  • 52. Formatting Dates and Times  The date and time classes support many methods to get data out of them:  It would be more work than necessary. Java provides a class called DateTimeFormatter to help us out.
  • 53. Formatting Dates and Times  Predefined formats  There are two predefined formats that can show up on the exam: SHORT and MEDIUM. The other predefined formats involve time zones, which are not on the exam.  If you don't want to use one of the predefined formats, you can create your own.
  • 55. Parsing Dates and Times.  Now that you know how to convert a date or time to a formatted String, you'll find it easy to convert a String to a date or time. Just like the format() method, the parse() method takes a formatter as well. If you don't specify one, it uses the default for that type.