Java Course 1: Input Output

The basic Java program is called a class.  A class is much more than a program, you’ll see why as we go on.

Classes contain methods, which are a little like functions in other languages.  The first function to run is called main().  You will notice it is written

public void main(String [] args)

I’ll explain what those other words mean later on.

Every part of a java program is contained in a block – surrounded by {}

Here is a basic java program.  See if you can run it.  Note the use of escape characters when printing.  Notice that \n gives a new line and \" literally prints "

public class JavaApplication1 {

    public static void main(String[] args) {
       System.out.println("This is really \n... \"groovy!\"");
    }
}

Be careful typing a backslash in Java. It indicates that the next character will be a special code. Be especially careful when writing file paths if you’re a Windows user. Follow the Apple/Linux pattern and use forward slashes, e.g. “C:/Java/Spoons”

Escape SequenceCharacter
\nnewline
\ttab
\bbackspace
\fform feed
\nreturn
\”” (double quote)
\’‘ (single quote)
\\\ (back slash)
\uDDDDUnicode character (DDDD is four hex digits)

Here’s how you read in text. Notice the import scanner line at the beginning.

import java.util.Scanner;

public class JavaApplication1 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter your name");
        String s = scan.nextLine();
        System.out.println("Hello " + s);
    }

Questions

  1. Print the message “I \u2665 Java!”
  2. Look up the the unicode for pi, and use that to print the formula for the circumference of a circle, C=2πr.
  3. Prompt the user to input their name and age. Output a message of the form “Hello (name). You are (age) years old.”
  4. Prompt the user to input first their forename and then their surname. Output their name in the format surname, forename.
  5. Use tabs to print out the following table. (Don’t include the borders)
JohnSmith32
JillGreen35
JackBlack22

Leave a Comment