Formatting Strings for the Java Foundations Junior Associate exam

Thinking about using our OCA 8 book to study for the Java Foundations Junior Associate exam? It covers most of the topics. See what other topics you need to learn and where to read about that. One of those topics is formatting a String using %s, %n and %d. Conveniently for you , I had written a draft of this material for our OCP book before finding out that topic is not on the OCP 8 exam. I asked our publisher if I could post the material online and they said yes. I’ve edited it down to cover the subset that is on the Java Foundations Junior Associate exam. While the style matches our book, keep in mind it has not gone through the normal editing process by our publisher.

Note that the exam only expects you to know %d (digit/integer), %s (string) and %n (new line). This post covers a bit about %f (decimal) for two reasons:

  1. To help you remember why %d is digit/integer and not a floating point number
  2. To see the power of printf!

Formatting Strings

Formatting a String is useful because they let us specify a lot of complex logic clearly and succinctly . Imagine you had to write code to print out exactly 3 decimal places and align the decimal places. That would be a lot of coding and logic. Or it could be done using formatting:

List<Double> values = Arrays.asList(123.456, -1.4, 2.0);

for (Double d : values)

System.out.printf("%7.3f%n", d);

Don’t worry if this seems like magic. In a nutshell, this uses a width of 7 with 3 decimal places followed by a new line. It outputs:

123.456
-1.400
2.000

You don’t have to be able to write code like this. It is just to show the power of formatting. Also, there are a lot more types and options in existence than you need to know for the exam. See the Formatter class in the Javadoc for the ones not on the exam. The following figure shows what is going on from a high level. Java is substituting the parameter into a part of the format string.c05f003Ok. From this point on, you do need to know the material for the exam.

The PrintStream class defines the methods format and printf. They do the exact same thing. Java wanted to name the method format. However, C++ has had this method called printf for decades. Java supports both names to make things easy for both C++ developers and new developers.

System.out and System.err are both PrintStream instances. Remember that System.out.println() can show up in questions on just about anything as can System.out.printf(). This means you won’t know specifically if you are being tested on printf or something else.

The signatures of these two methods are:

  • public PrintWriter format(String fmt, Object… args)
  • public PrintWriter printf(String fmt, Object… args)

Remember that the three dots mean varargs. You can pass as many arguments as you want here. Also, remember that format and printf are exactly the same so we will start to use them interchangeably.

The first parameter is a String with embedded format parameters. The remaining parameters are an ordered list of the parameters to be inserted:

int num = 3;

String s = "Three: ";

System.out.format("%s %d", s, num);

Java sees a format string of a String to be inserted, followed by a space and then followed by a number to be inserted. The output is:

Three: 3

There are a number of parts to a format string. You only need to know a simplified version which looks like:

%[arg_index$]conversion_char

Conversion Character

%d and %s are format conversion specifiers. These format specifiers indicate the type of the parameter. You are only required to know three of the format specifiers for the exam as listed in following table. You do have to memorize these. They are copied from C++ so some of the types might seem odd to you. We’ve tried to give a description that helps you remember it rather than the shortest one possible. If you are a C++ developer, you might know that %d actually stands for decimal rather than digit. This is harder to remember for a new developer because the whole point of %d is that there is not a decimal point.

Remember that %d is digit (integer) and not double.

Conversion Specifier Description
%d Specifies a number with digits and no decimal point. (also known as an integer number)
%n New line (line break)
%s Specifies a String

Argument Index

The remaining part of a format string is the argument index. This is the index number followed by a $.

Argument indexes start counting from 1 instead of 0.

These examples should be straightforward:

System.out.printf("%s, %s", "play", "time");    // play, time

System.out.printf("%2$s, %1$s", "play", "time"); // time, play

System.out.printf("%2$s, %2$s", "play", "time"); // time, time

The first line can omit the argument index since we want to use them in the order provided. The second line shows how to reverse the arguments. The final line shows how to use the same argument multiple times.

The Formatter Class

The Formatter class is an interpreter for the format strings used in format/printf methods. The class is similar to the PrintWriter class except that Formatter defines only the format methods and not the printf methods. Since the Formatter class didn’t exist in C++, Java didn’t need to be compatible with it. You invoke format in the way you do PrintWriter: passing in a format specifier followed by a comma-separated list of arguments.

For example, the following statements create a Formatter object and format a string of primitive types. What do you think this outputs?

StringBuilder sb = new StringBuilder();

Formatter fmt = new Formatter(sb);

int x = 123;

fmt.format("x=%d", x);

System.out.println(sb.toString());

In this example, the Formatter writes its output to a StringBuilder object. The int x is formatted and the resulting StringBuilder looks like this:

x=123

As you can see, working with Formatter is similar to working with PrintWriter.

Summary

printf() and format() use a format string. You need to know the simplified format of: %[arg_index$]conversion_char. The arg_index is optional. However, it must be specified in the correct order if present. The components you need to know are:

  • arg_index is an index that starts counting with one
  • conversion_character includes:
    • %b for boolean
    • %d for digit/decimal/integer (no decimal point)
    • %n for new line
    • %s for strings

Practice Questions

Question 1

What is the result of the following code?

System.out.format("%2$d is bigger than %2$d", 10, 5);

A: 10 is bigger than 5
B: 5 is bigger than 10
C: 10 is bigger than 10
D: 5 is bigger than 5
E: The code does not compile
F: A runtime exception is thrown

Question 2

Which of the following are true about the format string passed to printf? (Choose all that apply)

A: The argument index is a 0 based index.
B: The argument index is a 1 based index.
C: double goes with %d
D: int goes with %d

Question 3

What is the output of this statement?

System.out.printf("%2$d %1$s", "entry", 123.456);

A: 123 entry
B: 123.456 entry
C: entry 123
D: entry 123.456
E: The code does not compile
F: A runtime exception is thrown

Question 4

What is the output of this statement?

System.out.format("$n, $s", 123.456);

A: %n %s
B: $n $s
C: %n, %s
D: $n, $s
E: None of the above
F: A runtime exception is thrown

Question 5

What is the output of this statement?

System.out.println("%d", 123);

A: 0
B: 123
C: %d
D: The code does not compile
E: A runtime exception is thrown

The answers are posted here.

Junior Associate Blog Post Answers

How to study for the Java Foundations Junior Associate exam links to practice exam questions. This page provides the answers to those questions. It’s a separate page so you don’t accidentally see the answers while reading the questions.

Questions on Random and Math

  1. B: The Math class has static methods. The Random class needs to be instantiated. This is memorizing, but you have to memorize it.
  2. A, B: This method returns double values from 0 to 1 including 0 and not including 1. C and D are incorrect because they are too high.
  3. A,C: This method returns int values from 0 to 4 including 0 and 4. B is incorrect because is not an int. D is incorrect because it is too high.
  4. C: Using a random seed in the constructor provides the same sequence of “random” values each time.

Questions on Real World Applications of Java

  1. B,C: Servlets and JSF are both core web technologies. EJBs are used for the back end. SMTP is related to email.
  2. B: JMS is used for messaging without needing to wait for a reply.
  3. B,C: JDBC and JPA are the two core database technologies in Java.
  4. A: Applets run in a browser. JSF, JSP and Servlets are web technologies, but all run on a server

Questions on Formatting Strings

  1. D: The “2$” portion of “%2$d” denotes the second argument to be formatted, which is the 5. Therefore, 5 is output twice and the 10 does not appear in the result. The output is 5 is bigger than 5 and the answer is D.
  2. B,D: The argument index is 1 based. %d means digit/decimal and goes with int.
  3. F: This question is checking to see if you notice that %d is for int values and we’ve used it as a double. A runtime exception is thrown because we are passing a floating point number.
  4. D: Trick question! The format strings use % and not $. Since no actual replacements are present, the output is just the literal text and Choice D is correct. If the format string was %n, %s, the answer would be Choice F because the wrong arguments are passed in.
  5. D: The format strings are using with printf or format. The code calls println which expects a single String.

Questions on Using Iterators

  1. A: This is your standard iterator idiom
  2. C: Since Iterator doesn’t use generics, it requires a cast to convert from Object to String
  3. A: Since List doesn’t use generics, Iterator gives a warning since it does use generics. The code still compiles though when using the standard iterator idiom.

Questions on CompareTo

  1. A,E: Uppercase letters sort before lowercase ones making the first string smaller and compareTo() return a negative number. The Strings are not an exact match so equals() returns false.
  2. C,E: Blanks sort before uppercase letters making the second string smaller  and compareTo() return a positive number. The Strings are not an exact match so equals() returns false.
  3. B,D: The strings are the same so compareTo() returns 0 and equals() returns true.
  4. F: The method is compareTo(), not compare() so the code doesn’t compile.
  5. C,E: Numbers letters sort before letters making the first string larger and compareTo() return a positive number. The Strings are not an exact match so equals() returns false.

 

Math and Random for the Java Foundations Junior Associate exam

 

Thinking about using our OCA 8 book to study for the Java Foundations Junior Associate exam? It covers most of the topics. See what other topics you need to learn and where to read about that. One of those topics is the Math and Random classes both of which are covered in this post.

Disclaimer: I’m assuming you have already an intro to Java book and just covering what you should know when studying for the exam. This is not intended to be a complete reference for the classes; this is a basic exam. If you are looking for documentation see the JavaDoc for Random and Math.

Random

Overview of Random

The Random class is used to create a list of mostly random numbers. It’s random enough for most purposes and for the exam. When you get up to writing code that has to with security, it is no longer random enough and you’ll need to use another class such as SecureRandom. Using the Random class is easy. You create an instance of it and call methods to get random values. For example:

import java.util.*;
public class PlayTest {
   public static void main(String[] args) throws Exception {
      Random random = new Random();
      System.out.println(random.nextInt());
      System.out.println(random.nextDouble());
      System.out.println(random.nextLong());
   }
}

When I run this, I get:
-944250601
0.8115233936833056
-8514335293554058162

Running again gives:
1307999651
0.4324686951998048
1958536137379003933

Notice how they are different results. When you run it, you’ll get different numbers. That’s because they are random!

How to get random values in a smaller range

Wait a minute. It’s great to be able to generate giant random numbers. But all I want to do is simulate rolling a single die which gives me a number between 1 and 6 inclusive. Luckily, there is another method available on the Random class that we can use.

nextInt(x) returns a random number between 0 and x-1. If we called random.nextInt(6), we’d get a random number from 0-5. That’s almost what we want. Since we want to start with 1, we have to add 1 to the result. Which means we can write:

int dieRoll = random.nextInt(6) + 1);

How to get the same “random” values each time you run the program

Usually, you want to get different random values each time you run the program. However, sometimes you want to test your program so that it runs the same way every time. If your program doesn’t work the way you want it to, having it work differently each time makes troubleshooting tough! Luckily, there is a way around this problem. You can pass a “seed” to the constructor. This tells Java to always return the same sequence of “random” values for the same seed.

import java.util.*;

public class PlayTest {
   public static void main(String[] args) throws Exception {
      Random random = new Random(111);
      System.out.println(random.nextInt(6) + 1);
      System.out.println(random.nextInt(6) + 1);
      System.out.println(random.nextInt(6) + 1);
   }
}

Every time I run this program, it outputs:
2
3
2

If I pass a different seed, I get different “random” values each time. Cool, right?

Math

Unlike Random, the Math class is not instantiated. All methods in Math are static. This class is for common operations you might want to do. For example:

  • Math.abs(x) gives you the absolute value of x (removes the sign if it is negative)
  • Math.round(x) rounds x to the nearest int
  • Math.sqrt(x) gives you the square root of x
  • Math.random() gives you a random double that is >= 0 and < 1.

Wait. Say what? Didn’t we just go over a whole class about random numbers? Yes. We did. The Math class’ one doesn’t require you to instantiate it class. It’s good if you just need a quick random number. It doesn’t give as much control as Random.

You can get an int random number out of this by mutliplying and casting to an int. For example, this prints an int between 0 and 4 inclusive:

System.out.println((int) (Math.random() * 5));

Summary

What are the key takeaways for the exam in all this?

  1. The Math class has static methods
  2. Math.random() returns a double between 0 and 1 including 0 and not including 1.
  3. The Random class has instance methods.
  4. The Random class can return an int random number.
  5. If you instantiate two classes with the same random seed, they will return the same “random” numbers for the same sequence of calls.

Practice Questions

And yes, you can figure out the answers to some by looking at others. The key is to understand and remember the information.

Question 1

Which of the following fill in the blanks to make this code compile?

double num1 = _____________.random();
int num2 = ____________.nextInt();

A: Math, Random

B: Math, new Random()

C: new Math(), Random

D: new Math(), new Random()

E: None of the above

Question 2

What are possible values for Math.random() to return? (Choose all that apply)

A: 0

B: .5

C: 1

D: 5

E: None of the above

Question 3

What are possible values for new Random.nextInt(5) to return? (Choose all that apply)

A: 0

B: .5

C: 1

D: 5

E: None of the above

Question 4

Will of these statements are true? (Choose all that apply)

A: Math.random() will return the same number if called twice.

B: new Random().nextInt() will return the same number if called twice.

C: new Random(6).nextInt() will return the same number if called twice.

D: Random.nextInt() will return the same number if called twice.

E: None of the above

 

The answers are posted here.