Table of Contents
J1-1 Strings
Welcome to the first course in Java!
Requirements:
- IntelliJ IDEA CE
You can download IntelliJ IDEA CE from the JetBrains webpage: https://www.jetbrains.com.cn/en-us/idea/download
Scroll down to the second option, the “Community Edition”, which is free.
Entering The Program
Start a new project called “J1-1 Strings”. Then type the following code into the Main.java file:
Main.java
Main.java
public class Main { public static void main(String[] args) { // Code starts here: // Print a message. System.out.println("Hello, my name is Appledog!"); // Create a Scanner object to read input Scanner scanner = new Scanner(System.in); // Prompt the user for their name System.out.print("What is your name? "); // Read the input from the user String name = scanner.nextLine(); // Output a response System.out.println("Hello, " + name + "!"); // Close the scanner scanner.close(); } }
Now try to run the program. On Mac it's Control-R. On windows, I think, it's Shift-F10. Get used to using a keyboard; it's faster.
Fixing any Bugs
Oh no! Your first error. Find the line with the red underlined word “Scanner”. This tells you that “Scanner” was not found. Click on this word and the IDE will suggest a fix if possible. Here, it can automatically fix the error by inserting a line of code at the top of the program:
import java.util.Scanner
Now, run the program again. What happens?
A: (Your answer).
Teacher may discuss the answers here.
The Code
Here's an explanation of what each line of the program does. We will look at it like a computer looks at it. First, here's the basic starter program:
basic starter program
public class Main { public static void main(String[] args) { // Code starts here: System.out.println("Hello world!"); } }
These aren't the droids you're looking for
First, a warning. It might be better to say “don't worry about public, private, static”, but I wanted to point out that there is a reason for these words. And yet, it's actually not important for you to think about it too much. It will make much more sense later on. So for now, if you prefer, skip the next two sections about import, public and static, and just start by understanding that all the code goes in the middle:
import
The first thing we do is import the java.util.Scanner class. This Scanner class is inside the util library, which is inside the java library. That's it's location. What is it? It is a group of utility functions for doing things like, for example, reading strings.
public
- public class Main
This is a declaration of a class. A class is a group of code and data; a specification, if you will. In this case, the specification for Main is special. Main comes from the entry point for C programs, which is called main. You may recall “int main(void){}” in C. Here, Java needs to know where the program starts. It looks for the main() function inside the Main{} class, and starts there.
So, why is “public” here? Public means that a class from “outside” can access what is inside. In this case it means that the system is allowed to start your program. Remember, the system is assuming there is a Main class and a main function. If the Main class was private, then it couldn't access the main function inside and it couldn't start the program. So it has to be marked public. The default is package-private. So Main, since it's not being accessed from another class in the same package – but by the system – has to be marked public by default.
static
- public static void main(String[] args)
We see public again; this is just so the main() function can be found by the system.
It's static, which means it runs without first making a named copy of itself. If you don't know what that means, it means that you can make as many copies of a class and run it at the same time as you want. But here, if you are trying to run a program, it just “runs the program” without making any special moves.
If you remove the static, it doesn't work and the system won't be able to find your code, because it was never instantiated.
void
- void means nothing.
This means the function doesn't return anything. Actually this surprises me, since it seems a main function should return an error code. But no, in Java there is no return. Sounds ominous. Try changing the void to an int and returning a 5. It doesn't work.
The Code
System.out.println("Hello!")
This kind of code just prints a message out.
Scanner
I'm going to deal with scanner as a block of code. Here's what it looks like if you remove the comments:
// Create a Scanner object to read input Scanner scanner = new Scanner(System.in); // Prompt the user for their name System.out.print("What is your name? "); // Read the input from the user String name = scanner.nextLine(); // Output a response System.out.println("Hello, " + name + "!"); // Close the scanner scanner.close();
First you need to understand System.out and System.in aren't the same thing. Meaning, maybe System.out isn't a character terminal but a file, or a printer, or nothing (anything sent there is destroyed). System.in also might not exist. For example on a phone, there is no keyboard. Also, it could be a file, or information sent to the program in some other way. However, in most instances on a computer the default will be set to STDIN and STDOUT – in terms of IDEA, this will be some kind of mini-terminal in the program out window.
So what the Scanner class does is find STDIN and find a way to take information from it. Since it could be anything, we have to open the Scanner on System.in. That's what
Scanner scanner = new Scanner(System.in);
does. It opens the scanner attached to System.in.
Now input is simple; just call nextLine() on scanner. This will accept input until a CR or LF is detected – i.e. the ENTER key, or the end of a line in a file.
We place this information into a String object, and then we close the scanner object. Simple.
What's a String?
A string is a bunch of characters – like 'a', 'g' or 'r', but put together. It may come as no suprise then that you can find the position of an individfual charater in a string. This is really simple, so we won't put it in the main program, but just show it here real quick:
charAt()
String s = "Appledog"; char c = s.charAt(4); // Access the 5th character (index starts at 0) System.out.println("The fifth character is: " + c);
Strings are immutable
You cannot deal with a string like you can in Python, by directly indexing it. You need to first convert it into an array, and then back again.
string as array
String s = "Appledog"; // Convert String to char[] char[] a = s.toCharArray(); // Modify the array a[5] = 'b'; // Convert char[] back to String s = new String(a); System.out.println(s);
This prints “Applebog”.
Here concludes the lesson. Next: J1-2 if-else