Presentation is loading. Please wait.

Presentation is loading. Please wait.

CMSC 202 Java Primer. July 24, 2007 Copyright © 2008 Pearson Addison-Wesley 2 A Sample Java Application.

Similar presentations


Presentation on theme: "CMSC 202 Java Primer. July 24, 2007 Copyright © 2008 Pearson Addison-Wesley 2 A Sample Java Application."— Presentation transcript:

1 CMSC 202 Java Primer

2 July 24, 2007 Copyright © 2008 Pearson Addison-Wesley 2 A Sample Java Application

3 July 24, 20073 System.out.println Java programs work by having things called objects perform actions  System.out : an object used for sending output to the screen The actions performed by an object are called methods  println : the method or action that the System.out object performs Copyright © 2008 Pearson Addison-Wesley. All rights reserved

4 July 24, 20074 System.out.println Invoking or calling a method: When an object performs an action using a method  Also called sending a message to the object  Method invocation syntax (in order): an object, a dot (period), the method name, and a pair of parentheses  Arguments: Zero or more pieces of information needed by the method that are placed inside the parentheses System.out.println("This is an argument"); Copyright © 2008 Pearson Addison-Wesley. All rights reserved

5 July 24, 20075 Variable Declarations Like most languages, Java variables are declared using the type, the name, and a semi-colon int total; Unlike C, variables may declared anywhere in the code. This allows you to declare variables close to where they are used. Also allows reuse of for-loop index (later)

6 July 24, 20076 Identifiers Identifier: The name of a variable or other item (class, method, object, etc.) defined in a program  A Java identifier must not start with a digit, and all the characters must be letters, digits, or the underscore symbol  Java identifiers can theoretically be of any length  Java is a case-sensitive language: Rate, rate, and RATE are the names of three different variables Copyright © 2008 Pearson Addison-Wesley. All rights reserved

7 July 24, 20077 Primitive Types Copyright © 2008 Pearson Addison-Wesley. All rights reserved

8 July 24, 20078 Size of Primitive Types Because Java byte-code runs on the Java Virtual Machine, the size (number of bytes) for each primitive type is fixed. The size is not dependent on the actual machine/device on which the code executes. There is no sizeof operator in Java as there is in C – it’s not necessary.

9 July 24, 20079 Arithmetic Operators Java supports all the same arithmetic operators as you used in ‘C’ Assignment =, +=, -=, *=, etc Multiplication, addition, mod, etc *, +, /, % Increment and Decrement (pre- and post) ++, --

10 July 24, 200710 Arithmetic Operators and Expressions If an arithmetic operator is combined with int operands, then the resulting type is int If an arithmetic operator is combined with one or two double operands, then the resulting type is double If different types are combined in an expression, then the resulting type is the right-most type on the following list that is found within the expression byte  short  int  long  float  double char  Exception: If the type produced should be byte or short (according to the rules above), then the type produced will actually be an int Copyright © 2008 Pearson Addison-Wesley. All rights reserved

11 July 24, 200711 Integer and Floating-Point Division When one or both operands are a floating-point type, division results in a floating-point type 15.0/2 evaluates to 7.5 When both operands are integer types, division results in an integer type  Any fractional part is discarded  The number is not rounded 15/2 evaluates to 7 Be careful to make at least one of the operands a floating-point type if the fractional portion is needed Copyright © 2008 Pearson Addison-Wesley. All rights reserved

12 Jan 14, 200812 Assignment/Arithmetic Review Arithmetic operators http://www.csee.umbc.edu/courses/undergraduate/201/spring08/misc/ar ithmetic.shtml Assignment operators http://www.csee.umbc.edu/courses/undergraduate/201/spring08/misc/a ssignments.shtml

13 July 24, 200713 Type Casting A type cast takes a value of one type and produces a value of another type with an "equivalent" value  If n and m are integers to be divided, and the fractional portion of the result must be preserved, at least one of the two must be type cast to a floating-point type before the division operation is performed double ans = n / (double)m;  Note that the desired type is placed inside parentheses immediately in front of the variable to be cast  Note also that the type and value of the variable to be cast does not change Copyright © 2008 Pearson Addison-Wesley. All rights reserved

14 July 24, 200714 Variable Scope The scope of a variable is that set of code statements in which the variable is known to the compiler; where is can be referenced in your program. Most commonly, the scope of a variable is limited to the code block in which it is defined. A code block is a set of code enclosed in braces ({, }). One interesting application of this principle allowed in Java involves the for-loop construct.

15 July 24, 200715 for-loop index Java gives us ability to define variables in the heading of a for loop. Most commonly the loop index is declared and initialized in the for loop heading. These variables are considered local to the for-loop and so may be reused in other loops. String s = “hello world”; int count = 1; for (int i = 0; i < s.length(); i++) { count *= 2; } // using 'i' here generates a compiler error

16 July 24, 200716 Java Flow Control Java supports the usual flow control constructs with the same basic syntax as C/C++. We assume you are familiar with these constructs. Decisions if, if-else, switch Loops for, while, do-while Boolean expressions  Like C/C++, Java flow control constructs evaluate boolean expressions

17 July 24, 200717 Boolean Expressions A Boolean expression is an expression (or Boolean variable) that is either true or false The simplest Boolean expressions compare the value of two expressions time < limit yourScore == myScore  Note that Java, like C, uses two equal signs ( == ) to perform equality testing: A single equal sign ( = ) is used only for assignment  A Boolean expression does not need to be enclosed in parentheses, unless it is used in an if-else statement Copyright © 2008 Pearson Addison-Wesley. All rights reserved

18 July 24, 200718 Building Boolean Expressions When two Boolean expressions are combined using the "and" ( && ) operator, the entire expression is true provided both expressions are true  Otherwise the expression is false When two Boolean expressions are combined using the "or" ( || ) operator, the entire expression is true as long as one of the expressions is true  The expression is false only if both expressions are false Any Boolean expression can be negated using the ! operator  Place the expression in parentheses and place the ! operator in front of it Unlike mathematical notation, strings of inequalities must be joined by && ( the “and” operator)  Use (min < result) && (result < max) rather than min < result < max Copyright © 2008 Pearson Addison-Wesley. All rights reserved

19 July 24, 200719 Naming Conventions Start the names of variables, classes, methods, and objects with a lowercase letter, indicate "word" boundaries with an uppercase letter, and restrict the remaining characters to digits and lowercase letters topSpeed bankRate1 timeOfArrival Start the names of classes with an uppercase letter and, otherwise, adhere to the rules above FirstProgram MyClass String Copyright © 2008 Pearson Addison-Wesley. All rights reserved

20 July 24, 200720 Java Comparison Operators Copyright © 2008 Pearson Addison-Wesley. All rights reserved

21 July 24, 200721 Named Constants Instead of using "anonymous" numbers in a program, always declare them as named constants, and use their name instead public static final int INCHES_PER_FOOT = 12; public static final double RATE = 0.14;  The “ final ” modifier prevents a value from being changed inadvertently. We’ll talk more about public and static later.  It has the added advantage that when a value must be modified, it need only be changed in one place  Note the naming convention for constants: Use all uppercase letters, and designate word boundaries with an underscore character

22 July 24, 200722 Comments A line comment begins with the symbols //, and causes the compiler to ignore the remainder of the line  This type of comment is used for the code writer or for a programmer who modifies the code A C-style block comment begins with the symbol pair /*, and ends with the symbol pair */  The compiler ignores anything in between  This type of comment can span several lines  This type of comment provides documentation for the users of the program Copyright © 2008 Pearson Addison-Wesley. All rights reserved

23 July 24, 200723 Comments & Named Constant Copyright © 2008 Pearson Addison-Wesley All rights reserved

24 Jan 14, 200824 Comments and Coding Standards Be sure to check the course website regarding comment requirements in projects http://www.csee.umbc.edu/courses/ undergraduate/202/spring08/Projects/ codingstd.shtml

25 Jan 14, 200825 The Class String There is no primitive type for strings in Java The class String is a predefined class in Java that is used to store and process strings Objects of type String are made up of strings of characters that are written within double quotes  Any quoted string is a constant of type String "Live long and prosper." A variable of type String can be given the value of a String object. String blessing = "Live long and prosper.“ String greeting = “Hello”; String name = “Bob”; Copyright © 2008 Pearson Addison-Wesley. All rights reserved

26 July 24, 200726 Concatenation of Strings Concatenation: Using the + operator on two strings in order to connect them to form one longer string  greeting + name is equal to "HelloBob" Any number of strings can be concatenated together When a string is combined with almost any other type of item, the result is a string  "The answer is " + 42 evaluates to "The answer is 42“ Java Strings also support the += operator  If greeting is equal to ”Hello”, then greeting += “ Bob”; changes greeting to “Hello Bob” Copyright © 2008 Pearson Addison-Wesley. All rights reserved

27 July 24, 200727 String Methods The String class contains many useful methods for string- processing applications  A String method is called by writing the name of a String object, a dot, the name of the method, and a pair of parentheses to enclose any arguments  If a String method returns a value (e.g. an int), then it can be placed anywhere that a value of its type can be used String greeting = "Hello“; int count = greeting.length(); System.out.println("Length is " + greeting.length());  Always count from zero when referring to the position or index of a character in a string Copyright © 2008 Pearson Addison-Wesley. All rights reserved

28 July 24, 200728 Some Methods in the Class String (1 of 8) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

29 July 24, 200729 Some Methods in the Class String (2 of 8) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

30 July 24, 200730 Some Methods in the Class String (3 of 8) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

31 July 24, 200731 Some Methods in the Class String (4 of 8) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

32 July 24, 200732 Some Methods in the Class String (5 of 8) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

33 July 24, 200733 Some Methods in the Class String (6 of 8) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

34 July 24, 200734 Some Methods in the Class String ( 8 of 8) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

35 July 24, 200735 Some Methods in the Class String (7 of 8) Copyright © 2008 Pearson Addison-Wesley All rights reserved

36 July 24, 200736 String Indexes Copyright © 2008 Pearson Addison-Wesley All rights reserved The characters within the String may be accessed (but not changed) using the charAt( int index) method.

37 July 24, 200737 Escape Sequences A backslash ( \ ) immediately preceding a character (i.e., without any space) denotes an escape sequence or an escape character  The character following the backslash does not have its usual meaning  Although it is formed using two symbols, it is regarded as a single character Copyright © 2008 Pearson Addison-Wesley All rights reserved

38 July 24, 200738 Escape Sequences Copyright © 2008 Pearson Addison-Wesley All rights reserved

39 July 24, 200739 Pitfall: Using == with Strings The equality comparison operator ( == ) can correctly test two values of a primitive type However, when applied to two objects such as objects of the String class, == tests to see if they are stored in the same memory location, not whether or not they have the same value (more on this later) In order to test two strings to see if they have equal values, use the method equals, or equalsIgnoreCase if (string1.equals(string2)) or if (string1.equalsIgnoreCase(string2)) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

40 July 24, 200740 Introduction to Arrays We assume that you have seen and used arrays and array elements previously. An array is a data structure used to process a collection of data that is all of the same type  An array behaves like a numbered list of variables with a uniform naming mechanism  It has a part that does not change: the name of the array  It has a part that can change: an integer in square brackets  For example, given five scores: score[0], score[1], score[2], score[3], score[4] Copyright © 2008 Pearson Addison-Wesley. All rights reserved

41 July 24, 200741 Creating and Accessing Arrays An array that behaves like a collection of variables, all of type double, can be created using one statement double[] score = new double[5]; Or using two statements: double[] score; score = new double[5];  The first statement declares the variable score to be of the array type double[] (an array of doubles)  The second statement creates an array with five numbered variables of type double and makes the variable score a name for the array Copyright © 2008 Pearson Addison-Wesley. All rights reserved

42 July 24, 200742 Creating and Accessing Arrays The individual variables that together make up the array are called indexed variables  They can also be called subscripted variables or elements of the array  The number in square brackets is called an index or subscript  The number of indexed variables in an array is called the length or size of the array  In Java indices must be numbered starting with 0, and nothing else score[0], score[1], score[2], score[3], score[4] Copyright © 2008 Pearson Addison-Wesley. All rights reserved

43 Jan 14, 200843 Declaring and Creating an Array An array is declared and created using the new operator which we’ll discuss in more detail later: BaseType[] ArrayName = new BaseType[size];  The size may be given as an expression that evaluates to a nonnegative integer, for example, an int variable char[] line = new char[80]; double[] reading = new double[count]; Copyright © 2008 Pearson Addison-Wesley. All rights reserved

44 July 24, 200744 The length Instance Variable An array is considered to be an object Every array has exactly one instance variable named length  When an array is created, the instance variable length is automatically set equal to its size  The value of length cannot be changed (other than by creating an entirely new array using new ) double[] score = new double[5];  Given score above, score.length has a value of 5 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

45 July 24, 200745 Initializing Arrays An array can be initialized when it is declared  Values for the indexed variables are enclosed in braces, and separated by commas  The array size is automatically set to the number of values in the braces int[] age = {2, 12, 1};  Given age above, age.length has a value of 3 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

46 July 24, 200746 Initializing Arrays Another way of initializing an array is by using a for loop double[] reading = new double[100]; for (int index = 0; index < reading.length; index++) { reading[index] = 42.0; } If the elements of an array are not initialized explicitly, they will automatically be initialized to the default value for their base type Copyright © 2008 Pearson Addison-Wesley. All rights reserved

47 July 24, 200747 Array Parameters An argument to a method may be an entire array Array arguments behave like objects of a class  Therefore, a method can change the values stored in the indexed variables of an array argument A method with an array parameter must specify the base type of the array only BaseType[]  It does not specify the length of the array 6-47 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

48 July 24, 200748 Array Parameters The following method, doubleElements, specifies an array of double as its single argument: public void doubleElements(double[] a) { int i; for (i = 0; i < a.length; i++) a[i] = a[i]*2;... } 6-48 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

49 July 24, 200749 Array Parameters Arrays of double may be defined as follows: double[] a = new double[10]; double[] b = new double[30]; Given the arrays above, the method doubleElements invoked as follows: doubleElements(a); doubleElements(b);  Note that no square brackets are used when an entire array is given as an argument  Note also that a method that specifies an array for a parameter can take an array of any length as an argument 6-49 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

50 July 24, 200750 Pitfall: Use of = with Arrays Because an array variable contains the memory address of the array it names, the assignment operator ( = ) only copies this memory address  It does not copy the values of each indexed variable  Using the assignment operator will make two array variables be different names for the same array b = a;  The memory address in a is now the same as the memory address in b : They reference the same array 6-50 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

51 July 24, 200751 Pitfall: Use of = with Arrays A for loop is usually used to make two different arrays have the same values in each indexed position: int i; for (i = 0; (i < a.length) && (i < b.length); i++) b[i] = a[i];  Note that the above code will not make b an exact copy of a, unless a and b have the same length 6-51 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

52 July 24, 200752 Pitfall: Use of == with Arrays For the same reason, the equality operator ( == ) only tests two arrays to see if they are stored in the same location in the computer's memory  It does not test two arrays to see if they contain the same values (a == b)  The result of the above boolean expression will be true if a and b share the same memory address (and, therefore, reference the same array), and false otherwise 6-52 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

53 July 24, 200753 Pitfall: Use of == with Arrays In the same way that an equals method can be defined for a class like String, an equalsArray method can be defined for a type of array  This is how two arrays must be tested to see if they contain the same elements  The following method tests two integer arrays to see if they contain the same integer values 6-53 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

54 July 24, 200754 Pitfall: Use of = and == with Arrays public boolean equalsArray(int[] a, int[] b) { if (a.length != b.length) return false; else { int i = 0; while (i < a.length) { if (a[i] != b[i]) return false; i++; } return true; } 6-54 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

55 July 24, 200755 Partially Filled Arrays The exact size needed for an array is not always known when a program is written, or it may vary from one run of the program to another A common way to handle this is to declare the array to be of the largest size that the program could possibly need Care must then be taken to keep track of how much of the array is actually used  An indexed variable that has not been given a meaningful value must never be referenced 6-55 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

56 July 24, 200756 Partially Filled Arrays A variable can be used to keep track of how many elements are currently stored in an array  For example, given the variable count, the elements of the array someArray will range from positions someArray[0] through someArray[count – 1]  Note that the variable count will be used to process the partially filled array instead of someArray.length  Note also that this variable ( count ) must be an argument to any method that manipulates the partially filled array 6-56 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

57 July 24, 200757 Multidimensional Arrays It is sometimes useful to have an array with more than one index Multidimensional arrays are declared and created in basically the same way as one-dimensional arrays  You simply use as many square brackets as there are indices  Each index must be enclosed in its own brackets double[][]table = new double[100][10]; int[][][] figure = new int[10][20][30]; Person[][] = new Person[10][100]; Copyright © 2008 Pearson Addison-Wesley. All rights reserved

58 July 24, 200758 Multidimensional Arrays Multidimensional arrays may have any number of indices, but perhaps the most common number is two  Two-dimensional array can be visualized as a two- dimensional display with the first index giving the row, and the second index giving the column char[][] a = new char[5][12];  Note that, like a one-dimensional array, each element of a multidimensional array is just a variable of the base type (in this case, char ) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

59 July 24, 200759 Multidimensional Arrays In Java, a two-dimensional array, such as a, is actually an array of arrays  The array a contains a reference to a one-dimensional array of size 5 with a base type of char[]  Each indexed variable ( a[0], a[1], etc.) contains a reference to a one-dimensional array of size 12, also with a base type of char[] A three-dimensional array is an array of arrays of arrays, and so forth for higher dimensions Copyright © 2008 Pearson Addison-Wesley. All rights reserved

60 July 24, 200760 Two-Dimensional Array as an Array of Arrays (Part 1 of 2) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

61 July 24, 200761 Two-Dimensional Array as an Array of Arrays (Part 2 of 2) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

62 July 24, 200762 Using the length Instance Variable char[][] page = new char[30][100]; The instance variable length does not give the total number of indexed variables in a two-dimensional array  Because a two-dimensional array is actually an array of arrays, the instance variable length gives the number of first indices (or "rows") in the array page.length is equal to 30  For the same reason, the number of second indices (or "columns") for a given "row" is given by referencing length for that "row" variable page[0].length is equal to 100 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

63 July 24, 200763 Using the length Instance Variable The following program demonstrates how a nested for loop can be used to process a two- dimensional array  Note how each length instance variable is used int row, column; for (row = 0; row < page.length; row++) for (column = 0; column < page[row].length; column++) page[row][column] = 'Z'; Copyright © 2008 Pearson Addison-Wesley. All rights reserved

64 July 24, 200764 Multidimensional Array Parameters Methods may have multidimensional array parameters  They are specified in a way similar to one-dimensional arrays  They use the same number of sets of square brackets as they have dimensions public void myMethod(int[][] a) {... }  The parameter a is a two-dimensional array Copyright © 2008 Pearson Addison-Wesley. All rights reserved

65 July 24, 200765 Multidimensional Array Returned Values Methods may have a multidimensional array type as their return type  They use the same kind of type specification as for a multidimensional array parameter public double[][] aMethod() {... }  The method aMethod returns an array of double Copyright © 2008 Pearson Addison-Wesley. All rights reserved


Download ppt "CMSC 202 Java Primer. July 24, 2007 Copyright © 2008 Pearson Addison-Wesley 2 A Sample Java Application."

Similar presentations


Ads by Google