Download Java Primer

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CMSC 202
Java Primer 2
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.";
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
2
Concatenation of Strings




Concatenation: Using the + operator on two strings in order to
connect them to form one longer string
 If greeting is equal to "Hello ", and javaClass is equal to
"class", then greeting + javaClass is equal to "Hello
class"
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”
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
3
Classes, Objects, and Methods



A class is the name for a type whose values are objects
Objects are entities that store data and take actions
 Objects of the String class store data consisting of strings of
characters
The actions that an object can take are called methods
 Methods can return a value of a single type and/or perform an
action
 All objects within a class have the same methods, but each can
have different data values
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
4
Classes, Objects, and Methods

Invoking or calling a method: a method is called into
action by writing the name of the calling object,
followed by a dot, followed by the method name,
followed by parentheses



This is sometimes referred to as sending a message to the
object
The parentheses contain the information (if any) needed by
the method
This information is called an argument (or arguments)
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
5
String Methods

The String class contains many useful methods for stringprocessing applications
 A String method is called by writing 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
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
6
Some Methods in the Class String (1 of 8)
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
7
Some Methods in the Class String (2 of 8)
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
8
Some Methods in the Class String (3 of 8)
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
9
Some Methods in the Class String (4 of 8)
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
10
Some Methods in the Class String (5 of 8)
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
11
Some Methods in the Class String (6 of 8)
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
12
Some Methods in the Class String ( 8 of 8)
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
13
Some Methods in the Class String (7 of 8)
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley
All rights reserved
14
String Indexes
The characters within the String may be accessed (but
not changed) using the charAt( int index) method.
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley
All rights reserved
15
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
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley
All rights reserved
16
Escape Sequences
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley
All rights reserved
17
String Processing



A String object in Java is considered to be immutable, i.e.,
the characters it contains cannot be changed
There is another class in Java called StringBuffer that has
methods for editing its string objects
However, it is possible to change the value of a String variable
by using an assignment statement
String name = "Soprano";
name = "Anthony " + name;
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley
All rights reserved
18
Naming 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
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley
All rights reserved
19
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
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
20
Program Documentation

Java comes with a program called javadoc that will
automatically extract documentation from block comments
in the classes you define
 As long as their opening has an extra asterisk (/**)
Ultimately, a well written program is self-documenting
 Its structure is made clear by the choice of identifier names
and the indenting pattern
 When one structure is nested inside another, the inside
structure is indented one more level

We’ll discuss javadoc in lab

July 24, 2007
Copyright © 2008 Pearson Addison-Wesley
All rights reserved
21
Comments & Named Constant
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley
All rights reserved
22
Comments and Coding Standards

Be sure to check the course website
regarding comment requirements in
projects
http://www.csee.umbc.edu/courses/
undergraduate/202/fall07/Projects/
codingstd.shtml
July 24, 2007
23
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
July 24, 2007
24
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
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
25
Java Comparison Operators
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
26
Building Boolean Expressions

When two Boolean expressions are combined using the "and" (&&)
operator, the entire expression is true provided both expressions are
true


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


Otherwise the expression is false
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
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
27
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
string1.equals(string2)
string1.equalsIgnoreCase(string2)
July 24, 2007
Copyright © 2008 Pearson Addison-Wesley.
All rights reserved
28
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
29
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
July 24, 2007
30