Basic Java Syntax
Basic Java Syntax
• Details
– Processing starts in main
• Eclipse will create main automatically
– When creatingg class,, choose main as option
p
– Eclipse shortcut later: type “main” then hit Control-space
• Routines usually called “methods,” not “functions.”
– Printing is done with System.out.print...
System out print
• System.out.println, System.out.print, System.out.printf
6
• Eclipse shortcut: type “sysout” then hit Control-space
Example
• File: ShowTwoArgs.java
9
Example (Continued)
• Compiling
DOS> javac ShowTwoArgs.java
• Executing
DOS> j
java ShowTwoArgs
Sh T A H ll Cl
Hello Class
First args Hello
Second arg: Class
Looping Constructs
• for/each
for(variable: collection) {
body;
}
• for
for(init; continueTest; updateOp) {
body;
}
• while
while (continueTest) {
body;
}
• do
do {
body;
} while (continueTest);
11
For/Each Loops
public static void listEntries(String[] entries) {
for(String entry: entries) {
System.out.println(entry);
}
}
• Result
String[] test = {"This", "is", "a", "test"};
listEntries(test);
This
is
a
test
12
For Loops
public static void listNums1(int max) {
f (i t i
for(int i=0;
0 ii<max; i++) {
System.out.println("Number: " + i);
}
}
• Result
listNums1(4);
Number: 0
Number: 1
Number: 2
Number: 3
13
While Loops
public static void listNums2(int max) {
int i = 0;
while (i < max) {
System.out.println("Number: " + i);
i++; // "++" means "add one"
}
}
• Result
listNums2(5);
( );
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
14
Do Loops
public static void listNums3(int max) {
i t i = 0
int 0;
do {
System.out.println("Number:
y p ( " + i);
);
i++;
} while (i < max);
// ^ Don’t
’t f
forget
t semicolon
i l
}
• Result
listNums3(3);
Number: 0
Number: 1
15 Number: 2
Defining Multiple Methods in
Single Class
public class LoopTest {
public
bli static
t ti void
id main(String[]
i (St i [] args)
) {
String[] test =
{ "This", "is", "a", "test"};
listEntries(test);
listNums1(5);
listNums2(6);
listNums3(7);
}
blah; blah;
blah; blah;
for(...) { for(...) {
blah; blah;
blah; blah;
for(...) { for(...) {
bl h
blah; bl h
blah;
blah; blah;
} }
} }
17
Indentation: blocks that are nested the
same should be indented the same
• Yes • No
blah; blah;
blah; blah;
for(...) { for(...) {
blah; blah;
blah; blah;
for(...) { for(...) {
bl h
blah; bl h
blah;
blah; blah;
} }
} }
18
• Multiple Options
if (boolean-expression) {
statement1;
} else
l {
statement2;
}
20
Boolean Operators
• ==, !=
–E
Equality,
lit inequality.
i lit InI addition
dditi tot comparing
i primitive
i iti
types, == tests if two objects are identical (the same
object), not just if they appear equal (have the same
fields) More details when we introduce objects.
fields). objects
• <, <=, >, >=
– Numeric less than, less than or equal to, greater than,
greater
t than
th or equall to.
t
• &&, ||
– Logical
g AND,, OR. Both use short-circuit evaluation to
more efficiently compute the results of complicated
expressions.
• !
– Logical negation.
21
Example: If Statements
public
bli static
t ti iint
t max(int
(i t n1,
1 iint
t n2)
2) {
if (n1 >= n2) {
return(n1);
} else {
return(n2);
}
}
22
Strings
• Basics
– String is a real class in Java, not an array of characters as
in C and C++.
– Thee String
S g class
c ss hass a sshortcut
o cu method
e od too ccreate
e e a new
ew
object: just use double quotes
• This differs from normal objects, where you use the new
construct to build an object
j
• Use equals to compare strings
– Never use ==
• Many useful builtin methods
– contains, startsWith, endsWith, indexOf,
substring split
substring, split, replace
replace, replaceAll
• Note: can use regular expressions, not just static strings
23
– toUpperCase, toLowerCase, equalsIgnoreCase
Common String Error:
Comparing with ==
public static void main(String[] args) {
St i
String match
t h = "T
"Test";
t"
if (args.length == 0) {
System.out.println("No
y p args");
g
} else if (args[0] == match) {
System.out.println("Match");
} else {
System.out.println("No match");
}
}
• Prints "No match" for all inputs
– Fix:
i
if (args[0].equals(match))
24
Building Arrays:
One-Step Process
• Declare and allocate array in one fell swoop
• Examples:
int[] values = { 10
10, 100
100, 1000 };
String[] names = {"Joe", "Jane", "Juan"};
Point[] points = { new Point(0, 0),
new Point(1, 2),
new Point(3, 4) };
25
Building Arrays:
Two-Step Process
• Step 1: allocate an array of references:
ttype[]
[] var = new type[size];
t [i ]
– E.g.:
int[] primes = new int[7];
String[] names = new String[someArray.length];
• Step 2: populate the array
primes[0] = 2; names[0] = "Joe";
Joe ;
primes[1] = 3; names[1] = "Jane";
primes[2] = 5; names[2] = "Juan";
primes[3] = 7; names[3] = "John";
etc.
• If you fail to populate an entry
– Default value is 0 for numeric arrays
– Default value is null for object arrays
26
• Note:
– Number
N b off elements
l t in
i eachh row needd nott be
b equall
int[][] irregular = { { 1 },
{ 2
2, 3
3, 4}
4},
{ 5 },
{ 6, 7 } };
28
TriangleArray: Example
public class TriangleArray {
public static void main(String[] args) {
0
00
000
0000
00000
000000
0000000
00000000
000000000
0000000000
30
32
Summary
• Basics
–L
Loops, conditional
di i l statements, andd array access is
i similar
i il
to C and C++
• But new for loop: for(String s: someStrings) { … }
– Indent your code for readability
– String is a real class in Java
• Use equals,
q not ==, to compare
p strings
g
• Allocate arrays in one step or in two steps
– Extremely large Object arrays have bad performance
• Use
U M Math.blah()
th bl h() for
f simple
i l math
th operations
ti
• Simple input from command window
– Use command line for strings supplied at program startup
– Use Scanner to read values after prompts or to turn
simple input into numbers
35
© 2009 Marty Hall
Questions?