Preparation

a. Make sure you are booted into the Mac OSX side of the computer.

b. Mount the COURSES network drive by double clicking the alias icon you created previously. If you were unable to set up the alias, you can follow the Course Directory Setup instructions to mount the drive and create the alias.

c. Open up a Terminal, navigate to your StuWork/USERNAME directory, create a folder named lab-09-14, and change your directory to the newly created folder. (Remember that you should replace USERNAME with your actual username!)

$ cd /Volumes/COURSES/cs201-01-f18/StuWork/USERNAME/
$ mkdir lab-09-14
$ cd lab-09-14

d. Discuss with your partner what text editor you would like to use and open it up. Don’t be afraid to learn something new! You might find that you really like it! (I will be using Brackets primarily when writing live code.)

Exercise 1

In this exercise, we will experiment with different ways of printing to the output.

a. Create a new file called PrintTest.java in your lab folder with the following contents:

public class PrintTest
{
    public static void main(String[] args)
    {
        System.out.println("This prints this text AND a newline at the end");
        System.out.print("No newline should be printed automatically at the end of this line.");

        // the \n is an "escaped newline"
        System.out.print(" I am not manually inserting a newline here.\n");

        System.out.format("Here is an int and a float: %d %f\n", 5, 10.75);
        System.out.println("Here is an int and a float: " + 5 + " " + 10.75);
    }
}

b. Compile it with your terminal by executing javac PrintTest.java and then run it with java PrintTest. Is the output what you expect?

c. Of the last two statements, do you prefer the format or the println version of the same line? Why?

Exercise 2

Here we will explore building a long String using StringBuilder and StringJoiner classes.

a. Create a file named StringBuilderTest.java with the following text.

public class StringBuilderTest
{
    public static void main(String[] args)
    {
        String str = "0";
        for (int i = 1; i < 100; i++)
        {
            str = str + ", " + i;
        }
        System.out.println(str);
    }
}

b. Compile and run the code to verify it works as expected.

c. Since strings in Java are immutable, every time a new string is created the JVM must create a new string object and copy the string contents into the new object. Why do you think the above method of building the long string is inefficient? What if we created an even bigger string made up of a million components?

d. The StringBuilder class can help us avoid this overhead of creating unnecessary intermediate string objects while we are building our string. Modify the code in StringBuilderTest so that it uses StringBuilder instead.

(Hint, the append method will be especially helpful. Take a look at the following code to create a “Hello world” string)

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" world!");
System.out.println(sb.toString());

e. Modify your code again to use the StringJoiner class. (Hint: initialize the class with a delimiter of " ," use the add method.)

Exercise 3

A common interview question in CS is to write the “fizzbuzz” function which takes an int num as a parameter and does the following:

  • When num is divisible by 3, print fizz to System.out
  • When num is divisible by 5, print buzz to System.out
  • When num is neither divisible by 3 or 5, print 5 to System.out

(Note that if a number is divisible by both 3 and 5 it should print fizzbuzz.)

a. Create a new file called Fizzbuzz.java.

b. Write a method with signature public static void fizzbuzz(int num) that does what is described above.

c. Write a main method that calls fizzbuzz on all integers starting at 1 through 100.

d. Test your program of course!

In class on Monday, we will look at the various approaches to solving this problem, and how an interviewer would evaluate your solution. Stay tuned!

Exercise 4

In this exercise we will explore arrays and loops.

a. Create a new file called Loops.java with the following starter code.

public class Loops
{
    /**
     * Creates an integer array of size n initialized with values
     * ranging from 0, 1, 2,..., n-1.
     *
     * @param A non-negative integer that is the size of the array
     */
    public static int[] range(int n)
    {
        int[] arr = new int[n];  // create array of appropriate size
        for (int i = 0; i < arr.length; i++)
        {
            arr[i] = i + 1;
        }
        return arr;
    }

    public static void main(String[] args)
    {
        int[] arr = range(20);
        for (int i = 0; i < arr.length; i++)
        {
            System.out.print(i);
            System.out.print(" ");
        }
        System.out.println();
    }
}

b. Verify the code works by compiling it and running it.

c. Modify the range method so that it uses a while loop instead of a for loop.

d. Create a new method with signature public static int[] range(int start, int end) that takes integers satisfying start <= end and returns an array containing all the numbers (in increasing order) between start (inclusive) and end (exclusive). For example, range(5,10) should return the array {5,6,7,8,9}.

Creating two methods with the same name but different parameters is called overloading the method and is quite useful sometimes.