Basic Java Syntax Basic Java Syntax: For Live Java EE Training, Please See Training Courses
Basic Java Syntax Basic Java Syntax: For Live Java EE Training, Please See Training Courses
Basics
• Details
– Processing starts in main
• Eclipse can create main automatically
– When creatingg class: choose main as option
p
– Eclipse shortcut inside class: 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
7
• Eclipse shortcut: type “sysout” then hit Control-space
Getting Started: Execution
• File: HelloWorld.java
public
bli class
l H ll W ld {
HelloWorld
public static void main(String[] args) {
System.out.println("Hello, world.");
}
}
• Compiling
– Eclipse: just save file
DOS> javac HelloWorld.java
• Executing
– Eclipse: R-click, Run As, Java Application
DOS> java HelloWorld
Hello, world.
8
More Basics
• Use + for string concatenation
• Arrays are accessed with [ ]
– Array indices are zero-based
– The argument to main is an array of strings that
correspond to the command line arguments
• args[0] returns first command-line argument
• args[1]
[1] returns
t secondd command-line
d li argument,t etc.
t
• Error if you try to access more args than were supplied
• The length
g field
– Gives the number of elements in any array
• Thus, args.length gives the number of command-line
arguments
• Unlike in C/C++, the name of the program is not inserted
into the command-line arguments
9
Command-line Arguments
• Are useful for learning and testing
– Command-line args are helpful for practice
– But, programs given to end users should almost never use
command-line arguments
• They should pop up a GUI to collect input.
• Eclipse has poor support
– Entering command-line args via Eclipse is more trouble
than it is worth
– So,
So to test with command-line
command line args:
• Save the file in Eclipse (causing it to be compiled)
• Navigate to folder on desktop (not within Eclipse)
• Open command window (Run cmd)
• Type “java Classname arg1 arg2 …”
Example
• File: ShowTwoArgs.java (naïve version)
Loops
14
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
15
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
16
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
17
Number: 4
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
18 Number: 2
blah; blah;
blah; blah;
for(...) { for(...) {
blah; blah;
blah; blah;
for(...) { for(...) {
bl h
blah; bl h
blah;
blah; blah;
} }
} }
21
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;
} }
} }
22
Conditionals and
Strings
g
If Statements
• Single Option
if (boolean-expression) {
statement;
}
• Multiple Options
if (boolean-expression) {
statement1;
} else
l {
statement2;
}
25
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.
26
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);
}
}
27
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
28
– toUpperCase, toLowerCase, equalsIgnoreCase
Arrays
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) };
31
Building Arrays:
Two-Step Process
• Step 1: allocate an array of references:
ttype[] var = new type
t [size];
[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
32
• 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 } };
34
TriangleArray: Example
public class TriangleArray {
public static void main(String[] args) {
0
00
000
0000
00000
000000
0000000
00000000
000000000
0000000000
36
39
Reading Simple Input
• For simple testing, use standard input
– If you wantt strings,
ti just
j t use args[0],
[0] args[1],
[1] as before
b f
• To avoid errors, check args.length first
– Convert if you want numbers. Two main options:
• Use
U S Scanner class
l
– Note that you need import statement. See next slide!
Scanner inputScanner = new Scanner(System.in);
int i = inputScanner.nextInt();
inputScanner nextInt();
double d = inputScanner.nextDouble();
• Convert explicitly (Integer.parseInt, Double.parseDouble)
String seven = "7";
int i = Integer.parseInt(seven);
• In real applications, use a GUI
– Collect input
p with textfields,, sliders,, combo boxes,, etc.
• Convert to numeric types with Integer.parseInt,
Double.parseDouble, etc.
40
Wrap-Up
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
– If two steps, loop down array and supply values
• Use
U Math.blah()
M 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
• Neither is very important for most real-life applications
43
© 2010 Marty Hall
Questions?