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 Sequence | Character |
---|---|
\n | newline |
\t | tab |
\b | backspace |
\f | form feed |
\n | return |
\” | ” (double quote) |
\’ | ‘ (single quote) |
\\ | \ (back slash) |
\uDDDD | Unicode 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
- Print the message “I \u2665 Java!”
- Look up the the unicode for pi, and use that to print the formula for the circumference of a circle, C=2πr.
- Prompt the user to input their name and age. Output a message of the form “Hello (name). You are (age) years old.”
- Prompt the user to input first their forename and then their surname. Output their name in the format surname, forename.
- Use tabs to print out the following table. (Don’t include the borders)
John | Smith | 32 |
Jill | Green | 35 |
Jack | Black | 22 |