11Some material adapted from Mary Hall’s Core Web ProgrammingCMSC 331Basic Java Basic Java SyntaxSyntaxIntroduction to Java2Agenda• Creating, compiling, and executing simple Java programs• Accessing arrays• Looping• Using if statements• Comparing strings• Building arrays– One-step process– Two-step process• Using multidimensional arrays• Manipulating data structures• Handling errorsIntroduction to Java3Getting Started• Name of file must match name of class– It is case sensitive, even on Windows• Processing starts in main– public static void main(String[] args)– Routines usually called “methods,” not “functions.”• Printing is done with System.out– System.out.println, System.out.print• Compile with “javac”– Open DOS window; work from there– Supply full case-sensitive file name (with file extension)• Execute with “java”– Supply base class name (no file extension)Introduction to Java4Example• File: HelloWorld.javapublic class HelloWorld {public static void main(String[] args) {System.out.println("Hello, world.");}}• CompilingDOS> javac HelloWorld.java• ExecutingDOS> java HelloWorldHello, world.2Introduction to Java5More 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] returns second command-line argument• Etc.• The length field gives the number of elements in an 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 argumentsIntroduction to Java6Example• File: ShowTwoArgs.javapublic class ShowTwoArgs {public static void main(String[] args) {System.out.println("First arg: " +args[0]);System.out.println("Second arg: " +args[1]);}}Introduction to Java7Example (Continued)• CompilingDOS> javac ShowTwoArgs.java• ExecutingDOS> java ShowTwoArgs Hello WorldFirst args HelloSecond arg: ClassDOS> java ShowTwoArgs[Error message]Introduction to Java8Looping Constructs• whilewhile (continueTest) {body;}• dodo {body;} while (continueTest);• forfor(init; continueTest; updateOp) {body;}3Introduction to Java9While Loopspublic static void listNums1(int max) {int i = 0;while (i <= max) {System.out.println("Number: " + i);i++; // "++" means "add one"}}Introduction to Java10Do Loopspublic static void listNums2(int max) {int i = 0;do {System.out.println("Number: " + i);i++;} while (i <= max); // ^ Don’t forget semicolon}Introduction to Java11For Loopspublic static void listNums3(int max) {for(int i=0; i<max; i++) {System.out.println("Number: " + i);}}Introduction to Java12Aside: Defining Multiple Methods in Single Classpublic class LoopTest {public static void main(String[] args) {listNums1(5);listNums2(6);listNums3(7);}public static void listNums1(int max) {…}public static void listNums2(int max) {…}public static void listNums3(int max) {…} }4Introduction to Java13Loop Example• File ShowArgs.java:public class ShowArgs {public static void main(String[] args) {for(int i=0; i<args.length; i++) {System.out.println("Arg " + i + " is " + args[i]);}}}Introduction to Java14If Statements• Single Optionif (boolean-expression) {statement;}• Multiple Optionsif (boolean-expression) {statement1;} else {statement2;}Introduction to Java15Boolean Operators• ==, !=– Equality, inequality. In addition to comparing primitive 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.• <, <=, >, >=– Numeric less than, less than or equal to, greater than, greater than or equal to.• &&, ||– Logical AND, OR. Both use short-circuit evaluation to more efficiently compute the results of complicated expressions.• !– Logical negation.Introduction to Java16Example: If Statementspublic static int max2(int n1, int n2) {if (n1 >= n2) return(n1);else return(n2);}5Introduction to Java17Strings• String is a real class in Java, not an array of characters as in C and C++.• The String class has a shortcut method to create a new object: 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 ==Introduction to Java18Strings: Common Errorpublic static void main(String[] args) {String match = "Test";if (args.length == 0) {System.out.println("No args");} else if (args[0] == match) {System.out.println("Match");} else {System.out.println("No match");}}• Prints "No match" for all inputs – Fix:if (args[0].equals(match))Introduction to Java19Building Arrays: One-Step Process• Declare and allocate array in one fell swoop type[] var = { val1, val2, ... , valN };• Examples:int[] values = { 10, 100, 1000 };Point[] points = { new Point(0, 0),new Point(1, 2), ... };Introduction to Java20Building Arrays: Two-Step Process• Step 1: allocate an array of references:type[] var = new type[size];• Eg:int[] values = new int[7];Point[] points = new Point[someArray.length];• Step 2: populate the arraypoints[0] = new Point(...);points[1] = new Point(...);...Points[6] = new Point(…);• If you fail to populate an entry– Default value is 0 for numeric arrays– Default value is null for object arrays6Introduction to Java21Multidimensional Arrays• Multidimensional arrays are implemented as arrays of arraysint[][] twoD = new int[64][32];String[][] cats = { { "Caesar", "blue-point" },{ "Heather", "seal-point" },{ "Ted", "red-point" } };• Note: the number of elements in each row (dimension) need not be equalint[][] irregular = { { 1 }, { 2, 3, 4},{ 5 },{ 6, 7 } };Introduction to Java22TriangleArray: Examplepublic class TriangleArray {public static void main(String[] args) {int[][] triangle = new int[10][];for(int i=0; i<triangle.length; i++) {triangle[i] = new int[i+1];}for (int i=0; i<triangle.length; i++) {for(int j=0; j<triangle[i].length; j++) {System.out.print(triangle[i][j]);}System.out.println();}}}Introduction to Java23TriangleArray: Result> java TriangleArray0000000000000000000000000000000000000000000000000000000Introduction to Java24Data Structures• Java 1.0 introduced two synchronized data structures in the java.util package– Vector• A strechable (resizeable) array of Objects• Time to access an element is constant
View Full Document