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 structures and classes used in Java, and in this section you 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. 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 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. 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 you’d be hard-pressed to write code without it. After all, you can’t even write a main() method without using the String class. A string is basically a sequence of characters; here’s an example:

String name = "Fluffy";

As you learned in my other blog, “Java Building Blocks,” this is an example of a reference type. You also learned that reference types are created using the new keyword. Wait a minute, something is missing from the previous example: it doesn’t have new in it! In Java, these two snippets 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”. They are subtly different, as you’ll see in the section “String Pool,” later in this chapter. For now, just remember that the String class is special and doesn’t need to be instantiated with new. In this section, we’ll 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 clearly 3. But what is “1” + “2”? It’s actually “12” because Java combines the two String objects. Placing one String before the other String and combining them together is called 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:
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 let’s 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 for the String are only used in code—they don’t 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: it’s “ab”. Then Java looks at the remaining expression of “ab” + 3. The second rule tells us to concatenate since 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? The exam 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 rules—and be sure to check the variable types. In this example, we start with the third rule, which tells us to consider 1 + 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, we switch 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 this example, 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 or smaller, 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 can’t bulge. There’s no way to add objects, nor can you replace objects without disturbing the entire arrangement. The trade-off for the optimal packing is zero flexibility. 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.

More on Immutability

You won’t be asked to identify whether custom classes are immutable on the exam, but it’s 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 different String 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 reminds you if you accidentally change s. Also, immutable classes in Java are final, and subclasses can’t add mutable behavior.

You learned that + is used to do String concatenation in Java. There’s another way, which isn’t used much on real projects but is great for tricking people on the exam. What does 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 immutable by 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 25–40 percent of the memory in the entire program. Java realises 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 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 string but 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 really don’t want you to use the string pool. Please create a new object for me even though it is less efficient.” When you write programs, you wouldn’t 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 the exam. 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

Let’s look at thirteen methods from the String class. Many of them are straightforward so we won’t 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 signature is 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? Didn’t we just tell you that Java counts from 0? The difference is that zero counting happens only when you’re using indexes or positions within a list. When determining 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 put in 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. You’ll see code using a technique called method chaining. Here’s 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 many do 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 garbage collection. The next iteration assigns alpha to “abc” and the “ab” object becomes eligible for garbage collection, and so on. 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 ineffi cient. Luckily, Java has a solution. The StringBuilder class creates 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 17 adds a character to the StringBuilder object each time through the for loop and appends the value of current to the end of alpha. This code reuses the same StringBuilder without
creating an interim String each time.

Mutability and Chaining

We’re 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 each letter 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, 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! Let’s 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. Line 6 also adds text to the end of sb and returns a reference to sb. This time the reference is stored in same—which means sb and same point to the exact same object and would print
out the same value. The exam won’t 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. There’s only one StringBuilder object here. We know that because new StringBuilder() was called only once. On line 5, there are 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 that StringBuilder.

StringBuilder vs. StringBuffer

When writing new code that concatenates a lot of String objects together, you should use StringBuilder. 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. You’ll learn about threads for the OCP exam. In theory, you don’t need to know about StringBuffer on the exam at all. However, we bring this up anyway, since an older question might still be left on the exam.

Comments are closed.