Core API Java 8 Certification

Core API Java 8 Certification(or in short we can call it: Core Java API)is another important chapter for when appearing for OCA (Oracle Certified Associate Exam 1Z0-808), (or for Java 8 Certification).The OCA exam expects you to know the core data structuresand classes used in Java, and in this section you will learnabout the most common methods available. For example,String and StringBuilder are used for text data. An array and an ArrayList are usedwhen you have multiple values. A variety of classes are used for working with dates. I will also guide you, how to determine whether two objects are equal or not.API stands for application programming interface. In Java, an interface is somethingspecial. In the context of an API, it can be a group of class or interface definitions that givesyou access to a service or functionality. You will learn about the most common APIs for each of the classes covered in this chapter.

Before we deep dive on detailed syllabus, I would like to list down the exam syllabus which I am going to cover it here

Using Operators and Decision Constructs

  1. Test equality between Strings and other objects using == and equals()

Creating and Using Arrays

  1. Declare, instantiate, initialize and use a one-dimensional array
  2. Declare, instantiate, initialize and use a multi-dimensional array

Working with Selected classes from the Java API

  1. Creating and manipulating Strings
  2. Manipulate data using the StringBuilder class and its methods
  3. Declare and use an ArrayList of a given type
  4. Create and manipulate calendar data using classes from java.
  5. time.LocalDateTime, java.time.LocalDate, java.time.Local-Time, java.time.format.DateTimeFormatter, java.time.Period

Working with Java Data Types

  1. Develop code that uses wrapper classes such as Boolean,Double, and Integer.

Read the full java certification syllabus article by clicking here.

Java-Core-API

Creating and Manipulating Strings

The String class is such a fundamental class that youd be hard-pressed to write code withoutit. After all, you cant even write a main() method without using the String class. Astring is basically a sequence of characters; heres an example:

String name = "Fluffy";

As you learned in my other blog, Java Building Blocks, this is an example of a referencetype. You also learned that reference types are created using the new keyword. Wait a minute, something is missing from the previous example: it doesnt have new in it! In Java, these twosnippets both create a String:

String name = "Fluffy";
String name = new String("Fluffy");

Both give you a reference variable of type name pointing to the String object “Fluffy”. Theyare subtly different, as youll see in the section String Pool, later in this chapter. For now, justremember that the String class is special and doesnt need to be instantiated with new.In this section, well look at concatenation, immutability, the string pool, common methods,and method chaining.

Concatenation In Operators and Statements blog, you learned how to add numbers. 1 + 2 is clearly3. But what is “1” + “2”? Its actually “12” because Java combines the two String objects.Placing one String before the other String and combining them together is called stringconcatenation. The OCA exam creators like string concatenation because the + operatorcan be used in two ways within the same line of code. There arent a lot of rules to know forthis, but you have to know them well:

  1. If both operands are numeric, + means numeric addition.
  2. If either operand is a String, + means concatenation.
  3. The expression is evaluated left to right.

Now lets look at some examples:

System.out.println(1 + 2); // 3
System.out.println("a" + "b"); // ab
System.out.println("a" + "b" + 3); // ab3
System.out.println(1 + 2 + "c"); // 3c

The first example uses the fi rst rule. Both operands are numbers, so we use normal addition.The second example is simple string concatenation, described in the second rule. The quotes forthe String are only used in codethey dont get output.The third example combines both the second and third rules. Since we start on the left,Java fi gures out what “a” + “b” evaluates to. You already know that one: its “ab”. ThenJava looks at the remaining expression of “ab” + 3. The second rule tells us to concatenatesince one of the operands is a String.In the fourth example, we start with the third rule, which tells us to consider 1 + 2.Both operands are numeric, so the fi rst rule tells us the answer is 3. Then we have 3 + “c”,which uses the second rule to give us “3c”. Notice all three rules get used in one line? Theexam takes this a step further and will try to trick you with something like this:

int three = 3;
String four = "4";
System.out.println(1 + 2 + three + four);

When you see this, just take it slow and remember the three rulesand be sure to checkthe variable types. In this example, we start with the third rule, which tells us to consider1 + 2. The fi rst rule gives us 3. Next we have 3 + three. Since three is of type int, we still use the fi rst rule, giving us 6. Next we have 6 + four. Since four is of type String, weswitch to the second rule and get a fi nal answer of “64”. When you see questions like this,just take your time and check the types. Being methodical pays off. There is only one more thing to know about concatenation, but it is an easy one. In thisexample, you just have to remember what += does. s += “2” means the same thing as s =s + “2”.

4: String s = "1"; // s currently holds "1"
5: s += "2"; // s currently holds "12"
6: s += 3; // s currently holds "123"
7: System.out.println(s); // 123

Immutability

Once a String object is created, it is not allowed to change. It cannot be made larger orsmaller, and you cannot change one of the characters inside it.You can think of a string as a storage box you have perfectly full and whose sides cantbulge. Theres no way to add objects, nor can you replace objects without disturbing theentire arrangement. The trade-off for the optimal packing is zero flexibility.Mutable is another word for changeable. Immutable is the oppositean object thatcant be changed once its created. On the OCA exam, you need to know that String isimmutable.

More on Immutability

You wont be asked to identify whether custom classes are immutable on the exam, butits helpful to see an example. Consider the following code:

class Mutable {
private String s;
public void setS(String newS){ s = newS; } // Setter makes it mutable
public String getS() { return s; }
}
final class Immutable {
private String s = "name";
public String getS() { return s; }
}

Immutable only has a getter. There’s no way to change the value of s once it’s set.Mutable has a setter as well. This allows the reference s to change to point to a differentString later. Note that even though the String class is immutable, it can still be used in a mutable class. You can even make the instance variable final so the compiler remindsyou if you accidentally change s.Also, immutable classes in Java are final, and subclasses cant add mutable behavior.

You learned that + is used to do String concatenation in Java. Theres another way,which isnt used much on real projects but is great for tricking people on the exam. Whatdoes this print out?

String s1 = "1";
String s2 = s1.concat("2");
s2.concat("3");
System.out.println(s2);

Did you say “12”? Good. The trick is to see if you forget that the String class is immutableby throwing a method at you.

The String Pool

Since strings are everywhere in Java, they use up a lot of memory. In some production applications,they can use up 2540 percent of the memory in the entire program. Java realisesthat many strings repeat in the program and solves this issue by reusing common ones. Thestring pool, also known as the intern pool, is a location in the Java virtual machine (JVM)that collects all these strings. The string pool contains literal values that appear in your program. For example,name is a literal and therefore goes into the string pool. myObject.toString() is a stringbut not a literal, so it does not go into the string pool. Strings not in the string pool are garbage collected just like any other object.Remember back when we said these two lines are subtly different?

String name = "Fluffy";
String name = new String("Fluffy");

The former says to use the string pool normally. The second says No, JVM. I reallydont want you to use the string pool. Please create a new object for me even though it isless efficient. When you write programs,you wouldnt want to do this. For the exam, you need to know that it is allowed.

Important String Methods

The String class has dozens of methods. Luckily, you need to know only a handful for theexam. The exam creators pick most of the methods developers use in the real world.For all these methods, you need to remember that a string is a sequence of characters and Java counts from 0 when indexed. Below figure shows how each character in the string”animals” is indexed.

string-indexing

Lets look at thirteen methods from the String class. Many of them are straightforwardso we wont discuss them at length. You need to know how to use these methods.

length()

The method length() returns the number of characters in the String. The method signatureis as follows:

int length()

The following code shows how to use length():

String string = "animals";
System.out.println(string.length()); // 7

Wait. It outputs 7? Didnt we just tell you that Java counts from 0? The difference isthat zero counting happens only when youre using indexes or positions within a list. Whendetermining the total size or length, Java uses normal counting again.

charAt()

The method charAt() lets you query the string to fi nd out what character is at a specific index.

Method Chaining

It is common to call multiple methods on the same String, as shown here:

String start = "AniMaL ";
String trimmed = start.trim(); // "AniMaL"
String lowercase = trimmed.toLowerCase(); // "animal"
String result = lowercase.replace('a', 'A'); // "Animal"
System.out.println(result);

This is just a series of String methods. Each time one is called, the returned value is putin a new variable. There are four String values along the way, and Animal is output.However, on the exam there is a tendency to cram as much code as possible into a small space. Youll see code using a technique called method chaining. Heres an example:

String result = "AniMaL ".trim().toLowerCase().replace('a', 'A');
System.out.println(result);

StringBuilder Class

A small program can create a lot of String objects very quickly. For example, how manydo you think this piece of code creates?

10: String alpha = "";
11: for(char current = 'a'; current = 'z'; current++)
12: alpha += current;
13: System.out.println(alpha);

The empty String on line 10 is instantiated, and then line 12 appends an “a”. However,because the String object is immutable, a new String object is assigned to alpha and the object becomes eligible for garbage collection. The next time through the loop, alpha is assigned a new String object, “ab”, and the “a” object becomes eligible for garbagecollection. The next iteration assigns alpha to “abc” and the “ab” object becomes eligiblefor garbage collection, and so on.This sequence of events continues, and after 26 iterations through the loop, a total of 27objects are instantiated, most of which are immediately eligible for garbage collection. This is very ineffi cient. Luckily, Java has a solution. The StringBuilder classcreates a String without storing all those interim String values. Unlike the String class,StringBuilder is not immutable.

15: StringBuilder alpha = new StringBuilder();
16: for(char current = 'a'; current = 'z'; current++)
17: alpha.append(current);
18: System.out.println(alpha);

On line 15, a new StringBuilder object is instantiated. The call to append() on line 17adds a character to the StringBuilder object each time through the for loop and appendsthe value of current to the end of alpha. This code reuses the same StringBuilder without creating an interim String each time.

Mutability and Chaining

Were sure you noticed this from the previous example, but StringBuilder is not immutable.In fact, we gave it 27 different values in the example (blank plus adding eachletter in the alphabet). The exam will likely try to trick you with respect to String and StringBuilder being mutable.Chaining makes this even more interesting. When we chained String method calls, theresult was a new String with the answer. Chaining StringBuilder objects doesnt workthis way. Instead, the StringBuilder changes its own state and returns a reference to itself! Lets look at an example to make this clearer:

4: StringBuilder sb = new StringBuilder("start");
5: sb.append("+middle"); // sb = "start+middle"
6: StringBuilder same = sb.append("+end"); // "start+middle+end"

Line 5 adds text to the end of sb. It also returns a reference to sb, which is ignored. Line6 also adds text to the end of sb and returns a reference to sb. This time the reference isstored in samewhich means sb and same point to the exact same object and would print out the same value.The exam wont always make the code easy to read by only having one method per line.What do you think this example prints?

4: StringBuilder a = new StringBuilder("abc");
5: StringBuilder b = a.append("de");
6: b = b.append("f").append("g");
7: System.out.println("a=" + a);
8: System.out.println("b=" + b);

Did you say both print “abcdefg”? Good. Theres only one StringBuilder objecthere. We know that because new StringBuilder() was called only once. On line 5, thereare two variables referring to that object, which has a value of “abcde”. On line 6, those two variables are still referring to that same object, which now has a value of “abcdefg”.Incidentally, the assignment back to b does absolutely nothing. b is already pointing to thatStringBuilder.

StringBuilder vs. StringBuffer

When writing new code that concatenates a lot of String objects together, you shoulduse StringBuilder. StringBuilder was added to Java in Java 5. If you come across oldercode, you will see StringBuffer used for this purpose. StringBuffer does the same thing but more slowly because it is thread safe. Youll learn about threads for the OCP exam. Intheory, you dont need to know about StringBuffer on the exam at all. However, we bringthis up anyway, since an older question might still be left on the exam.

All OCJP Java Certification Tutorials

  1. Oracle (OCJP) Java Certification Exam
  2. Java Building Blocks Java 8 Certification
  3. Operators And Statements
  4. Java Core API
  5. Java Class Design
  6. Java Exception
  7. Java Try-Catch Block
  8. Exceptional Handling in Java
  9. Common Exception in Java