Unit 1: Introduction to Java
Lesson 2: Your First Program
All java programs are inside something called a class. You'll learn more about what a class is later.
There are a couple of types of Java programs: applications, applets, and web start applications. In this course, we'll only be looking at applications. Applets are Java programs that run in web browsers and are normally normally blocked because of th number of security issues that they cause. I'm not sure of Java Web Start programs have the same issues as Applets.
import java.util.Timer; public class FirstProgram { public static void main(String[] args) { String name = "awesome"; System.out.println("Hello " + name); } } |
0. if you have to import any othe classes, put them first. DO NOT type in this line as we don't need to import anything here. 1. save this file as FirstProgram.java 2. all applications must have a main() method This is what Java looks for and runs first. "main" can call other classes and methods. The text in this line must be EXACTLY this way. The only word that can be changed is "args". "args" is a list of command line arguments which we rarely use, so you could just call it "junk". 3. The program code goes here. Each line must end with ; unless it ends in a { or } 4. The two } close off the code blocks for the main method and then the whole class |
Type in this program and then run it.
In general, program execution happens sequentially line by line. (This is always true inside code blocks.) There are exceptions when using methods,
program control statements (if, switch, for, while), and also with more complicated things inside classes - we'll get to them later.
print, println, concatenation
The way to print something to the screen is System.out.println("text")
System.out.print("text")
is the same as PRINTLN but does not add a "new line" or "enter" at the end of the line.
Thus System.out.print("text\n")
is the same as System.out.println("text")
Use a +
sign to join two strings together as in the example above (this is called concatenation).