Unit1 2
Unit1 2
Programming in Java
• For now:
• we'll limit ourselves to writing a single class
• you can just think of a class as a container for your program
• Notes:
• the class begins with a header:
public class name
• the code inside the class is enclosed in curly braces
({ and })
Methods
• A method is a collection of instructions that perform
some action or computation.
• Notes:
• the main method always begins with the same header:
public static void main(String[] args)
• the code inside the method is enclosed in curly braces
• each statement typically ends with a semi-colon
• the statements are executed sequentially
Identifiers
• Used to name the components of a Java program like
classes and methods.
• Rules:
• must begin with a letter (a-z, A-Z), $, or _
• can be followed by any number of letters, numbers, $, or _
• spaces are not allowed
• cannot be the same as a keyword – a word like class
that is part of the language itself (see the Resources page)
Printing Text
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello, world");
}
}
The next text to be printed will begin just after this text –
on the same line.
• For example:
System.out.print("I ");
System.out.print("program ");
System.out.println("with class!");
is equivalent to
System.out.println("I program with class!");
Escape Sequences
• Problem: what if we want to print a string that includes
double quotes?
• example: System.out.println("Jim said, "hi!"");
• this won’t compile. why?
• Other examples:
• \n a newline character (goes to the next line)
• \t a tab
• \\ a backslash