Lesson Weekend

Like many languages, Java has a ton of built-in tools and methods we can use. However, Java is downright huge! We can't load every little bit of Java into every program just in case we might want to use one of its tools! This would make our application run very slowly. Instead, when we want to use a specific part of Java, we can explicitly import it into our program. That way we're only loading tools we need, and our applications can remain speedy and well-organized.

In this lesson we'll walk through how to import code. We will create an application that asks the user what their favorite color is, gathers their answer, and provides a response based upon how they answered. Some code seen in this lesson will be quite advanced, but nevertheless the only way to reliably receive user input running an app inside IntelliJ. Don't worry if this feels confusing or overwhelming at first - we'll show exactly how to work with this code, and you are not expected to be able to write it from scratch, or memorize it.

If you are confused by the try /catch - here's a super brief summary. We'll revisit this more in depth later in the class. A try/catch block allows us to say: "Hey Java, i want you to run some code that might, under some circumstances, cause an error (Input/Output exception - something is most likely null when it shouldn't be). If that error happens, don't panic or crash, just print the stacktrace (error log)". This allows us to handle errors a bit more gracefully and make our apps more stable.

In order to gather the user's response through the console, we'll import Java's BufferedReader class. This will allow us to retrieve user-inputted text from the command line.

Also, throughout this process you'll hear terms like classes, or packages. Keep in mind that a Class is, as discussed, a Java file that has been compiled. A package is simply a group of files - kind of like a directory.

Application Setup

First, create a project, a process we're becoming quickly familiar with, called favorites. In our src/main/java directory we'll make a file called FavoriteColor.java and set up our required class and method. This part should look familiar:

src/main/java/FavoriteColor.java
public class FavoriteColor {
  public static void main(String[] args) { //try typing psvm + tab to autocomplete!

  }
}

Remember, the name of our class must directly reflect the name of our file. Since our file is called FavoriteColor.java, our class name is FavoriteColor.

System Out

Now, we want our application to ask the user what their favorite color is in the command line. Let's add code to print "What's your favorite color?" for the user:

src/main/java/FavoriteColor.java
public class FavoriteColor {
  public static void main(String[] args) {
    System.out.println("What is your favorite color?");
  }
}

When data travels from within our application out to the user, like it is here when our application prints "What is your favorite color?" to the command line, it's known as system out. Notice that this is reflected in our line of code: System.out precedes the println() function.

Now, compile and run your program by choosing Run > Run > FavoriteColor.

fave-color-terminal-out

And we should see "What is your favorite color?" in our terminal. Perfect! Now, let's add code that allows the user to enter a response, and our application to collect that response.

Retrieving Input from the User

Carefully copy the following code into your FavoriteColor.java file:

FavoriteColor.java
public class FavoriteColor {

   public static void main(String[] args) {
       System.out.println("What is your favorite color?");

       try{
           BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
           String inputString = bufferedReader.readLine();

           System.out.println("Color entered : " + inputString);
       }
       catch(IOException e)
       {
           e.printStackTrace();
       }
   }
}

Wow, this is looking pretty complicated. And, lots of things on our page are red, and there are squiggly lines in places. Don't worry! You don't need to understand everything here. And we'll fix the squiggles in a sec.

Importing Classes

The red areas and squiggles appear because we haven't yet imported the specific areas of Java we're trying to use. We need to manually import it. We can do this by adding the following line to the top of our FavoriteColor.java:

import java.io.BufferedReader;

Including this line has granted our file access to methods in Java's BufferedReader class. Great. This made one of the red areas disappear!

Now, this isn't the only way to import code. There is a much easier to import code with IntelliJ. As you can see, you have a red squiggly under InputStreamReader - this indicates that IntelliJ's code checker has found an issue or inconsistency with your code. It's because we haven't yet imported import java.io.InputStreamReader; from our code. If you hover over the code, it'll tell you it "Cannot resolve symbol InputStreamReader". A symbol is Java's umbrella term for any variable, data type or object it can't locate.

Let's import the necessary code Java needs to work with InputStreamReader objects the smart way. Place your cursor next to InputStreamReader, until you see an underline. (you may need to move the cursor back or forward a few spaces. It'll get easier to make work after a few tries.) When you see the underline, hit the windows + enter key on our classroom macs (alt + enter or option + enter on your home machine).

code-import-intellij

Sweet! IntelliJ is able to import our code for us. Remember this command, it's super useful. Do this again for the IOException, and now IntelliJ shouldn't show any red squiggles and is feeling much happier. Good stuff.

While we are at it, let's change our very factual System.out.println("Color entered : " + inputString); to a friendlier System.out.println("Your favorite color is " + inputString + "? Me too!");

This is what our complete code looks like now:

src/main/java/FavoriteColor.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FavoriteColor {

   public static void main(String[] args) {
       System.out.println("What is your favorite color?");
       try{
           BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
           String inputString = bufferedReader.readLine();

           System.out.println("Your favorite color is " + inputString + "? Me too!");

       }
       catch(IOException e)
       {
           e.printStackTrace();
       }
   }
}

We can compile and run our application one more time. When you see the phrase "What is your favorite color?" place the cursor below it, and type your input, then press enter. You should see something like this:

What is your favorite color?
red
Your favorite color is red? Me too!

Process finished with exit code 0

When the terminal stops, it is waiting for you to provide a response and hit Enter.

If we type in "blue", and hit enter, we should see the response "Your favorite color is blue? Me too!". Nice work! We are now interacting with a Java program we wrote ourselves. Pretty cool!