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

What's hot

String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
Java string handling
Java string handlingJava string handling
Java string handling
Salman Khan
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
Vishnu Suresh
 
String in java
String in javaString in java
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Edureka!
 
Oops in java
Oops in javaOops in java
java token
java tokenjava token
java token
Jadavsejal
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java Ravi_Kant_Sahu
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
Java IO
Java IOJava IO
Java IO
UTSAB NEUPANE
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
Madishetty Prathibha
 
Java arrays
Java arraysJava arrays
Java arrays
Kuppusamy P
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
SIVASHANKARIRAJAN
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
yugandhar vadlamudi
 
Introduction to package in java
Introduction to package in javaIntroduction to package in java
Introduction to package in java
Prognoz Technologies Pvt. Ltd.
 

What's hot (20)

String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Java input
Java inputJava input
Java input
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
String in java
String in javaString in java
String in java
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Oops in java
Oops in javaOops in java
Oops in java
 
java token
java tokenjava token
java token
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Chap 6(decision making-looping)
Chap 6(decision making-looping)Chap 6(decision making-looping)
Chap 6(decision making-looping)
 
Java IO
Java IOJava IO
Java IO
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 
Java arrays
Java arraysJava arrays
Java arrays
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 
Introduction to package in java
Introduction to package in javaIntroduction to package in java
Introduction to package in java
 

Viewers also liked

The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1
İbrahim Kürce
 
Basic
BasicBasic
Meeting10 social class
Meeting10 social classMeeting10 social class
Meeting10 social class
School
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
javatrainingonline
 
Chapter 8
Chapter 8Chapter 8
Chapter 8MEEvans
 
Java se 8 fundamentals
Java se 8 fundamentalsJava se 8 fundamentals
Java se 8 fundamentals
megharajk
 
Race Class based on Chapter 8 of "Race and Racisms: A Critical Approach."
Race Class based on Chapter 8 of "Race and Racisms: A Critical Approach."Race Class based on Chapter 8 of "Race and Racisms: A Critical Approach."
Race Class based on Chapter 8 of "Race and Racisms: A Critical Approach."
Tanya Golash Boza
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
Ganesh Samarthyam
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
Pokequesthero
 
Notes On Software Development, Platform And Modernisation
Notes On Software Development, Platform And ModernisationNotes On Software Development, Platform And Modernisation
Notes On Software Development, Platform And ModernisationAlan McSweeney
 
Whitepaper Real Time Transaction Analysis And Fraudulent Transaction Detect...
Whitepaper   Real Time Transaction Analysis And Fraudulent Transaction Detect...Whitepaper   Real Time Transaction Analysis And Fraudulent Transaction Detect...
Whitepaper Real Time Transaction Analysis And Fraudulent Transaction Detect...Alan McSweeney
 
Comprehensive And Integrated Approach To Project Management And Solution Deli...
Comprehensive And Integrated Approach To Project Management And Solution Deli...Comprehensive And Integrated Approach To Project Management And Solution Deli...
Comprehensive And Integrated Approach To Project Management And Solution Deli...
Alan McSweeney
 
Sociolinguistics : Language Change
Sociolinguistics : Language ChangeSociolinguistics : Language Change
Sociolinguistics : Language ChangeAthira Uzir
 
Project Failure Reasons and Causes
Project Failure Reasons and CausesProject Failure Reasons and Causes
Project Failure Reasons and Causes
Alan McSweeney
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
Ganesh Samarthyam
 
Language and social class
Language and social classLanguage and social class
Language and social class
hulbert45
 
Consumer Behaviour -Family, social class & life cycle
Consumer Behaviour -Family, social class & life cycleConsumer Behaviour -Family, social class & life cycle
Consumer Behaviour -Family, social class & life cycle
rainbowlink
 
Forget Big Data. It's All About Smart Data
Forget Big Data. It's All About Smart DataForget Big Data. It's All About Smart Data
Forget Big Data. It's All About Smart Data
Alan McSweeney
 

Viewers also liked (19)

The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1
 
Basic
BasicBasic
Basic
 
Meeting10 social class
Meeting10 social classMeeting10 social class
Meeting10 social class
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Chapter 8
Chapter 8Chapter 8
Chapter 8
 
Java se 8 fundamentals
Java se 8 fundamentalsJava se 8 fundamentals
Java se 8 fundamentals
 
Race Class based on Chapter 8 of "Race and Racisms: A Critical Approach."
Race Class based on Chapter 8 of "Race and Racisms: A Critical Approach."Race Class based on Chapter 8 of "Race and Racisms: A Critical Approach."
Race Class based on Chapter 8 of "Race and Racisms: A Critical Approach."
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Chapter 8 socio
Chapter 8 socioChapter 8 socio
Chapter 8 socio
 
Notes On Software Development, Platform And Modernisation
Notes On Software Development, Platform And ModernisationNotes On Software Development, Platform And Modernisation
Notes On Software Development, Platform And Modernisation
 
Whitepaper Real Time Transaction Analysis And Fraudulent Transaction Detect...
Whitepaper   Real Time Transaction Analysis And Fraudulent Transaction Detect...Whitepaper   Real Time Transaction Analysis And Fraudulent Transaction Detect...
Whitepaper Real Time Transaction Analysis And Fraudulent Transaction Detect...
 
Comprehensive And Integrated Approach To Project Management And Solution Deli...
Comprehensive And Integrated Approach To Project Management And Solution Deli...Comprehensive And Integrated Approach To Project Management And Solution Deli...
Comprehensive And Integrated Approach To Project Management And Solution Deli...
 
Sociolinguistics : Language Change
Sociolinguistics : Language ChangeSociolinguistics : Language Change
Sociolinguistics : Language Change
 
Project Failure Reasons and Causes
Project Failure Reasons and CausesProject Failure Reasons and Causes
Project Failure Reasons and Causes
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
Language and social class
Language and social classLanguage and social class
Language and social class
 
Consumer Behaviour -Family, social class & life cycle
Consumer Behaviour -Family, social class & life cycleConsumer Behaviour -Family, social class & life cycle
Consumer Behaviour -Family, social class & life cycle
 
Forget Big Data. It's All About Smart Data
Forget Big Data. It's All About Smart DataForget Big Data. It's All About Smart Data
Forget Big Data. It's All About Smart Data
 

Similar to OCA Java SE 8 Exam Chapter 3 Core Java APIs

String handling
String handlingString handling
String handling
ssuser20c32b
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9Vince Vo
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
Eduardo Bergavera
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
fedcoordinator
 
Lecture 7
Lecture 7Lecture 7
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
Knoldus Inc.
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...
Indu32
 
Ppt chapter09
Ppt chapter09Ppt chapter09
Ppt chapter09
Richard Styner
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
package
packagepackage
package
sweetysweety8
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
smile790243
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Java for newcomers
Java for newcomersJava for newcomers
Java for newcomers
Amith jayasekara
 

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

String handling
String handlingString handling
String handling
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...
 
M C6java7
M C6java7M C6java7
M C6java7
 
Ppt chapter09
Ppt chapter09Ppt chapter09
Ppt chapter09
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
package
packagepackage
package
 
Java String
Java String Java String
Java String
 
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docxLab 1 Recursion  Introduction   Tracery (tracery.io.docx
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java for newcomers
Java for newcomersJava for newcomers
Java for newcomers
 

More from İbrahim Kürce

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

More from İbrahim Kürce (7)

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

Recently uploaded

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 

Recently uploaded (20)

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 

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.