View
239
Download
0
Category
Preview:
Citation preview
7/31/2019 03 Basic Syntax
1/23
2012 Marty Hall
Originals of Slides and Source Code for Examples:
-. . .
Customized Java EE Training: http://courses.coreservlets.com/Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.3
2012 Marty Hall
For live Java EE training, please see training coursesat htt ://courses.coreservlets.com/.
JSF 2.0, PrimeFaces, Servlets, JSP, Ajax (with jQuery), GWT,Android development, Java 6 and 7 programming,
SOAP-based and RESTful Web Services, Spring, Hibernate/JPA,XML, Hadoop, and customized combinations of topics.
Taught by the author of Core Servlets and JSP , More
Customized Java EE Training: http://courses.coreservlets.com/Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
, .venues, or customized versions can be held on-site at your
organization. Contact hall@coreservlets.com for details.
7/31/2019 03 Basic Syntax
2/23
Topics in This Section
Basics rea ng, comp ng, an execu ng s mp e ava programs
Accessing arrays Loo in Indenting Code Using if statements ompar ng s r ngs Building arrays
- Two-step process
Using multidimensional arrays er orm ng as c ma ema ca opera ons Reading command-line input
5
2012 Marty Hall
Basics
Customized Java EE Training: http://courses.coreservlets.com/Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.6
7/31/2019 03 Basic Syntax
3/23
Eclipse: Making Projects
Creating new project File New Project
Java Java Project Pick an name To simplify applets later,
choose Sources/Classesin same folder
Creating new class R-click New Class
You can have Eclipse makemain when class created,or use shortcut to insert it later
You can also copy/paste existingclass, then give it new name
Getting Started: Syntax Example
public class HelloWorld { public static void main(String[] args) {
System.out.println("Hello, world.");
}
Details Processing starts in main Eclipse can create main automatically
When creating class: choose main as option Eclipse shortcut inside class: type main then hit Control-space
Routines usually called methods, not functions. . . ...
System.out.println, System.out.print, System.out.printf Eclipse shortcut: type sysout then hit Control-space
8
7/31/2019 03 Basic Syntax
4/23
7/31/2019 03 Basic Syntax
5/23
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-
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 , -
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: Command Line Args
File: ShowTwoArgs.java (nave version)
public class ShowTwoArgs {
System.out.println("First arg: " +args[0]);
ys em.ou .pr n n econ arg:args[1]);
}}
Oops! Crashes if there are less than two command-line arguments. The code should have checked the length field, like this:if (args.length > 1) {
12
doThePrintStatements();} else {
giveAnErrorMessage();}
7/31/2019 03 Basic Syntax
6/23
Example (Continued)
Compiling ( automatic on save in Eclipse )DOS> javac ShowTwoArgs.java
Manual executionava ow wo rgs e o ass
First args Hello
DOS> java ShowTwoArgs[Error message]
Eclipse execution (cumbersome) To assign command line args: R-click, Run As,
Run Configurations, click on Arguments tab13
2012 Marty Hall
Loops
Customized Java EE Training: http://courses.coreservlets.com/Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.14
7/31/2019 03 Basic Syntax
7/23
Looping Constructs
for/each
body;
} for
for(init; continueTest; updateOp) { body;
} while
while (continueTest) { body;
} do
do {o y;
} while (continueTest);
15
For/Each Loops public static void listEntries(String[] entries) {
System.out.println(entry);
}}
ResultString[] test = {"This", "is", "a", "test"};listEntries(test);
Thisisatest
16
7/31/2019 03 Basic Syntax
8/23
For Loops
public static void listNums1(int max) {or n = ;
7/31/2019 03 Basic Syntax
9/23
Do Loops
public static void listNums3(int max) {n = ;
do {S stem.out. rintln "Number: " + i ;i++;
} while (i < max);Dont orget sem co on
}
ResultlistNums3(3);
Number: 0 Number: 1 Number: 219
2012 Marty Hall
Formattin
Customized Java EE Training: http://courses.coreservlets.com/Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.20
7/31/2019 03 Basic Syntax
10/23
Defining Multiple Methods in
public class LoopTest { pu c s a c vo ma n r ng args
String[] test ={ "This", "is", "a", "test"};listEntries(test);listNums1(5);
listNums3(7);}
These methods say static because they are called directly from main.In the next two sections on OOP, we will explain what static means andwh most re ular methods do not use static. But for now, ust note that
public static void listEntries(String[] entries) {} public static void listNums1(int max) {}
methods that are directly called by main must say static.
public static void listNums2(int max) {} public static void listNums3(int max) {}
}21
Indentation: blocks that are nested Yes No
blah; blah;
for(...) {
blah;
for(...) {
blah; blah;
for(...) { blah;
for(...) {a ;
blah;a ;
blah;
} }22
7/31/2019 03 Basic Syntax
11/23
7/31/2019 03 Basic Syntax
12/23
2012 Marty Hall
Strin s
Customized Java EE Training: http://courses.coreservlets.com/Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.25
If Statements Single option
if (boolean-expression) {statement1 ;...statement N ;
} w
if (boolean-expression) {...
} else {...
} Multiple options
if (boolean-expression) {...
The value inside parens must strictly be boolean, unlikeC, C++, and JavaScript.
A widely accepted best practice is to use the braces evenif there is onl a sin le statement inside the if or else.
} else if (boolean-expression) {...
} else if (boolean-expression) {...
} else {...
}
26
7/31/2019 03 Basic Syntax
13/23
7/31/2019 03 Basic Syntax
14/23
Example: If Statements
pu c stat c nt max nt n , nt n
if (n1 >= n2) {return n1
} else {return(n2);
}}
29
Strings Basics
String is a real class in Java, not an array of characters as in Cand C++.
The Strin class has a shortcut method to create a new ob ect: just use double quotes
This differs from normal objects, where you use the new
construct to build an object Use equals to compare strings
Never use == to test if two Strings have same characters! any use u u n me o s
contains, startsWith, endsWith, indexOf,substring, split, replace, replaceAll
Note: can use regular expressions, not just static strings toUpperCase, toLowerCase, equalsIgnoreCase
30
7/31/2019 03 Basic Syntax
15/23
Common String Error:==
public static void main(String[] args) {r ng ma c = es ;
if (args.length == 0) {System.out.println("No args");} else if (args[0] == match) {
System.out.println("Match");
System.out.println("No match");}
}
Prints "No match" for all inputs Fix:
if (args[0] .equals (match))31
2012 Marty Hall
Arrays
Customized Java EE Training: http://courses.coreservlets.com/Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.32
7/31/2019 03 Basic Syntax
16/23
Building Arrays:-
Declare and allocate array in one fell swoop
type [] var = { val1, val2, ... , val N };
Examples:= , ,
String[] names = {"Joe", "Jane", "Juan"};Point[] points = { new Point(0, 0),
new Point(1, 2),new Point(3, 4) };
33
Building Arrays:
Step 1: allocate an array of references: ype var = new ype s ze ;
E.g.:int[] primes = new int[7];String[] names = new String[someArray.length];
Step 2: populate the array= = " "
primes[1] = 3; names[1] = "Jane"; primes[2] = 5; names[2] = "Juan";
" " etc.
If you fail to populate an entry Default value is 0 for numeric arrays Default value is null for object arrays
34
7/31/2019 03 Basic Syntax
17/23
Two-Step Process: Examples public static Circle[] makeCircles1(int numCircles) {
Circle[] circles = new Circle[numCircles]; // Empty array of proper sizefor(int i=0; i
7/31/2019 03 Basic Syntax
18/23
Multidimensional Arrays
Multidimensional arrays Implemented as arrays of arrays
int[][] twoD = new int[64][32];
String[][] cats = {{ "Caesar", "blue-point" },{ "Heather", "seal-point" },
" " " - ",
Note: um er o e emen s n eac row nee no e equa
int[][] irregular = { { 1 }, , , ,{ 5 },{ 6, 7 } };
37
TriangleArray: Example public class TriangleArray {
int[][] triangle = new int[10][];
for(int i=0; i
7/31/2019 03 Basic Syntax
19/23
TriangleArray: Result
> java TriangleArray
0000000000
000000000000000000000000000000
39
2012 Marty Hall
Math and Input
Customized Java EE Training: http://courses.coreservlets.com/Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.40
7/31/2019 03 Basic Syntax
20/23
7/31/2019 03 Basic Syntax
21/23
7/31/2019 03 Basic Syntax
22/23
2012 Marty Hall
Wrap-Up
Customized Java EE Training: http://courses.coreservlets.com/Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.45
Summary Basics
oops, con t ona statements, an array access s s m ar 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 , not == , to compare strings Allocate arrays in one step or in two steps
If two steps, loop down array and supply values se a . a or s mp e ma opera ons Simple input from command window
Use Scanner to read values after prompts
Neither is very important for most real-life applications46
7/31/2019 03 Basic Syntax
23/23
2012 Marty Hall
u
Customized Java EE Training: http://courses.coreservlets.com/Java 6 or 7, JSF 2.0, PrimeFaces, Servlets, JSP, Ajax, Spring, Hibernate, RESTful Web Services, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.47
Recommended