Post on 18-Jan-2018
description
CMSC 202
Java Primer
July 24, 2007 Copyright © 2008 Pearson Addison-Wesley
2
A Sample Java Application
July 24, 2007 3
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
July 24, 2007 4
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
July 24, 2007 5
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)
July 24, 2007 6
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
July 24, 2007 7
Primitive Types
Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 8
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.
July 24, 2007 9
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)++, --
July 24, 2007 10
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 expressionbyteshortintlongfloatdoublechar 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
July 24, 2007 11
Integer and Floating-Point Division When one or both operands are a floating-point type, division
results in a floating-point type15.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
Jan 14, 2008 12
Assignment/Arithmetic ReviewArithmetic operatorshttp://www.csee.umbc.edu/courses/undergraduate/201/spring08/misc/arithmetic.shtml
Assignment operatorshttp://www.csee.umbc.edu/courses/undergraduate/201/spring08/misc/assignments.shtml
July 24, 2007 13
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 performeddouble 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
July 24, 2007 14
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.
July 24, 2007 15
for-loop indexJava 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
July 24, 2007 16
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.
Decisionsif, if-else, switch
Loopsfor, while, do-while
Boolean expressions Like C/C++, Java flow control constructs evaluate boolean
expressions
July 24, 2007 17
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
expressionstime < limityourScore == 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
July 24, 2007 18
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
July 24, 2007 19
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
July 24, 2007 20
Java Comparison Operators
Copyright © 2008 Pearson Addison-Wesley.All rights reserved
July 24, 2007 21
Named Constants
Instead of using "anonymous" numbers in a program, always declare them as named constants, and use their name insteadpublic 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
July 24, 2007 22
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
July 24, 2007 23
Comments & Named Constant
Copyright © 2008 Pearson Addison-WesleyAll rights reserved
Jan 14, 2008 24
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
Jan 14, 2008 25
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
July 24, 2007 26
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
July 24, 2007 27
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 usedString 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
July 24, 2007 28
Some Methods in the Class String (1 of 8)
Copyright © 2008 Pearson Addison-Wesley.All rights reserved
July 24, 2007 29
Some Methods in the Class String (2 of 8)
Copyright © 2008 Pearson Addison-Wesley.All rights reserved
July 24, 2007 30
Some Methods in the Class String (3 of 8)
Copyright © 2008 Pearson Addison-Wesley.All rights reserved
July 24, 2007 31
Some Methods in the Class String (4 of 8)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 32
Some Methods in the Class String (5 of 8)
Copyright © 2008 Pearson Addison-Wesley.All rights reserved
July 24, 2007 33
Some Methods in the Class String (6 of 8)
Copyright © 2008 Pearson Addison-Wesley.All rights reserved
July 24, 2007 34
Some Methods in the Class String ( 8 of 8)
Copyright © 2008 Pearson Addison-Wesley.All rights reserved
July 24, 2007 35
Some Methods in the Class String (7 of 8)
Copyright © 2008 Pearson Addison-WesleyAll rights reserved
July 24, 2007 36
String Indexes
Copyright © 2008 Pearson Addison-WesleyAll rights reserved
The characters within the String may be accessed (but not changed) using the charAt( int index) method.
July 24, 2007 37
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-WesleyAll rights reserved
July 24, 2007 38
Escape Sequences
Copyright © 2008 Pearson Addison-WesleyAll rights reserved
July 24, 2007 39
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
July 24, 2007 40
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
July 24, 2007 41
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
July 24, 2007 42
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 elsescore[0], score[1], score[2], score[3], score[4]
Copyright © 2008 Pearson Addison-Wesley. All rights reserved
Jan 14, 2008 43
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 variablechar[] line = new char[80];double[] reading = new double[count];
Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 44
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
July 24, 2007 45
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 bracesint[] age = {2, 12, 1};
Given age above, age.length has a value of 3
Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 46
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
July 24, 2007 47
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 onlyBaseType[]
It does not specify the length of the array
6-47Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 48
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-48Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 49
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-49Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 50
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 arrayb = a;
The memory address in a is now the same as the memory address in b: They reference the same array
6-50Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 51
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-51Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 52
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-52Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 53
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-53Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 54
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-54Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 55
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-55Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 56
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-56Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 57
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
July 24, 2007 58
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 columnchar[][] 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
July 24, 2007 59
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
July 24, 2007 60
Two-Dimensional Array as an Array of Arrays (Part 1 of 2)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 61
Two-Dimensional Array as an Array of Arrays (Part 2 of 2)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 62
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
July 24, 2007 63
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
July 24, 2007 64
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 dimensionspublic void myMethod(int[][] a){ . . . }
The parameter a is a two-dimensional array
Copyright © 2008 Pearson Addison-Wesley. All rights reserved
July 24, 2007 65
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 parameterpublic double[][] aMethod(){ . . . }
The method aMethod returns an array of double
Copyright © 2008 Pearson Addison-Wesley. All rights reserved