In this chapter we will summarize what we have learned so far in the Java basics area and point out some common mistakes.
General Rules
How to Define a Variable Name
Variable name string
case-sensitive
okay to include numbers 0 to 9
okay to have underscore _ or dollar sign $
Variable name string:
cannot start with number
cannot use reserved words, such as for, class, void, if, else, etc.
How to Output in Console
System.out.print(<string + value>);
System.out.println(<string + value>);
How to Listen to Input in Console
Scanner input = new Scanner(System.in);
input.nextLine();
input.next();
input.nextInt();
input.nextFloat();
How to Repeat an Operation
for(<initial state>; <condition check>; <increment/decrement count>) {
<do something>;
}
while(<condition check>) {
<do something>
}
or,
do {
<do something>
}
while(<condition check>)
How to Control a Conditional Operation
if (<condition check>) {
<do something>;
}
if (<condition check>) {
<do something>;
} else {
<do something else>;
}
if (<condition check>) {
<do something>;
}
else {
<do something else with the nested if/else statement(s)>;
}
Basic Coding Structure
public class MyClass {
public static void main(...) {
myMethod();
}
private static void myMethod(...) {
for (... ; ... ; ...) {
......;
}
if (...) {
......;
}
else {
......;
}
}
}
Curly Braces
Always come with a pair of curly braces: “{......}”
Always come first with: “{”, and then “}”
- Common patterns (two pairs of open/close as an example)
{ { } } open, open, close, close
{ } { } open, close, open, close
{ } } { wrong!
} { } { wrong!
- What is the basic rule of these patterns?
At beginning, start with “{”
Finally, end with “}”
Never has more “}” than “{”
Lab Work
- 1.What is the output produced from the following program?public class StoryOfMethods {public static void main(String[] args) {method1();method2();System.out.println("Done with main.");}public static void method1() {System.out.println("This is from method1.");}public static void method2() {System.out.println("This is from method2.");method1();System.out.println("Done with method2.");}}
- 2.What is the output produced from the following program?public class OrderOfFunctions {public static void main(String[] args) {second();first();second();third();}public static void first() {System.out.println("Inside the first function.");}public static void second() {System.out.println("Inside the second function.");first();}public static void third() {System.out.println("Inside the third function.");first();second();}}