Strings Useful methods of String char Atint index

  • Slides: 71
Download presentation
Strings

Strings

Useful methods of String • • char. At(int index) int compare. To(String another. String)

Useful methods of String • • char. At(int index) int compare. To(String another. String) boolean ends. With(String suffix) int index. Of(multiple) int length() String substring(int begin, int end) String trim()

String is Immutable • When delcaring String, we can treat them as if they

String is Immutable • When delcaring String, we can treat them as if they are primitives, but they are objects! – // String str. Animal= “Dog”; //these are equivalent – // String str. Animal = new String(“Dog”); //these are equivalent • Immutable class: Has no mutator methods (e. g. , String): String str. Name = "John Q. Public"; String str. Uppercased = str. Name. to. Upper. Case(); // str. Name is not changed • It is safe to give out references to objects of immutable classes; no code can modify the object at an unexpected time. The implicit paramater is immutable! Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

String Pools • To optimize performance, the JVM may keep a String in a

String Pools • To optimize performance, the JVM may keep a String in a pool for reuse. Sometimes is does and sometimes it doesn't. Very unpredictable. • This means that in some VMs (or even the same VM at different times), two or more object references may be pointing to the same String in memory. • However, since you can not rely upon pooling, you MUST assume that each string has its own object reference. • Besides, since Strings are immutable, you need not consider the consequences of passing a reference. • Using. equals() rather than ==.

The String Class • A string is a sequence of characters • Strings are

The String Class • A string is a sequence of characters • Strings are objects of the String class • A string literal is a sequence of characters enclosed in double quotation marks: "Hello, World!" • String length is the number of characters in the String • Example: "Harry". length() is 5 • Empty string: "" • Although we use the shortcut: String str. Name = “Robert”; we are actually doing this: String str. Name = new String(“Robert”); Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Concatenation • Use the + operator: String str. Name = "Dave"; String str. Message

Concatenation • Use the + operator: String str. Name = "Dave"; String str. Message = "Hello, " + str. Name; // str. Message is "Hello, Dave" • If one of the arguments of the + operator is a string, all the others are converted to a string String str. A = "Agent”; int n = 7; char c = 'b' String str. Bond = str. A + n + c; // str. Bond is "Agent 7 c" Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Substrings • String str 2 = str. Greeting. substring(7, 12); // str 2 is

Substrings • String str 2 = str. Greeting. substring(7, 12); // str 2 is "World" • Substring starts at the begin-index and ends at end-index - 1 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Escape Sequences • to include the quotes in a string, use the escape sequences:

Escape Sequences • to include the quotes in a string, use the escape sequences: • str. One = ""Quotation""; • to print \ • Str. Back. Slashes = "\\"; • Unicode values http: //oreilly. com/actionscript/excerpts/as 3 cookbook/appendix. html

Escape Sequences Escape Sequenc e Character n newline t tab b backspace f form

Escape Sequences Escape Sequenc e Character n newline t tab b backspace f form feed r return " " (double quote) ' ' (single quote) \ (back slash) u. DDDD character from the Unicode character set (DDDD is four hex digits)

Keyboard Input edu. uchicago. cs. java. lec 02. scanner

Keyboard Input edu. uchicago. cs. java. lec 02. scanner

Keyboard Input • Scanner -- or you can define your own • Scanner scn

Keyboard Input • Scanner -- or you can define your own • Scanner scn = new Scanner(System. in); • Scanner scn = new Scanner(File fil. Source); throws File. Not. Found. Exception • str. Input = scn. next. Line();

Reading Input • System. in has minimal set of features — it can only

Reading Input • System. in has minimal set of features — it can only read one byte at a time • In Java 5. 0, Scanner class was added to read keyboard input in a convenient manner • Scanner scn = new Scanner(System. in); System. out. print("Enter quantity: "); int n. Quantity = scn. next. Int(); • next. Double reads a double • next. Line reads a line (until user hits Enter) • next reads a word (until any white space) Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Random See edu. uchicago. cs. java. lec 02. random

Random See edu. uchicago. cs. java. lec 02. random

Random numbers • import java. util. Random; • int n = rnd. next. Int();

Random numbers • import java. util. Random; • int n = rnd. next. Int(); • double d = rnd. next. Double(); • int n = rnd. next. Int(int n. Num); rnd. next. Int(20); //0 -19 //in this above case 20 is multipled by some real number between 0 and 1 exclusive; then converted to int; it will return 0 to 19.

Project || Generate Javadoc || path to the bin of the sdk

Project || Generate Javadoc || path to the bin of the sdk

Calling Static Methods • A static method does not operate on an object double

Calling Static Methods • A static method does not operate on an object double d. Y = 4; double d. Y = mat. Object. sqrt(); // Error double d. Y = Math. sqrt(9); //correct • Static methods are declared inside classes • Naming convention: Classes start with an uppercase letter; objects start with a lowercase letter: Math System. out Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Implicit versus Explicit Parameters • The implicit parameter is the object reference, whereas the

Implicit versus Explicit Parameters • The implicit parameter is the object reference, whereas the explicit parameter(s) are/is the argument(s) to the method. • str. Name. index. Of(c. Space); • Math. pow(2, 3); //no implicit param -- static • Most often, when we refer to parameters, we mean the explicit parameters.

Static Methods • Example: public class Metric { public static double get. Kilograms(double d.

Static Methods • Example: public class Metric { public static double get. Kilograms(double d. Pounds){ return d. Pounds * 0. 454; } // More methods can be added here. } • Call with class name instead of object: double d. Kilos = Metric. get. Kilograms(150);

Syntax 4. 3 Static Method Call Big Java by Cay Horstmann Copyright © 2009

Syntax 4. 3 Static Method Call Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Suppose Java had no static methods. How would you use the Math. sqrt method

Suppose Java had no static methods. How would you use the Math. sqrt method for computing the square root of a number x? Answer: Math mat = new Math(); double d. Result = mat. sqrt(x); //note that Math methods ARE STATIC Suppose the methods of java. util. Random were static, how would you call them? Answer: int n. Result = Random. next. Int(20); //int betweeen 0 -19 //note that Random methods ARE NON-STATIC Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Static Variables • A classs need not be exclusively static or non-static, it can

Static Variables • A classs need not be exclusively static or non-static, it can be both.

Static Variables • public Bank. Account() { // Generates next account number to be

Static Variables • public Bank. Account() { // Generates next account number to be assigned last. Assigned. Number++; // Updates the static variable account. Number = last. Assigned. Number; // Sets the instance variable } /this no-args constructor create a serial number the bank account Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

A Static Variable and Instance Variables Big Java by Cay Horstmann Copyright © 2009

A Static Variable and Instance Variables Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Static Variables • Exception: Static constants, which may be either private or public: public

Static Variables • Exception: Static constants, which may be either private or public: public class Bank. Account {. . . public static final double OVERDRAFT_FEE = 5; // Refer to it as Bank. Account. OVERDRAFT_FEE } //in the above case, OVERDRAFT_FEE is a constant Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Class Objects

Class Objects

Self Check 8. 15 Harry tells you that he has found a great way

Self Check 8. 15 Harry tells you that he has found a great way to avoid those pesky objects: Put all code into a single class and declare all methods and variables static. Then main call the other static methods, and all of them can access the static variables. Will Harry’s plan work? Is it a good idea? Answer: Yes, it works. Static methods can access static variables of the same class. But it is a terrible idea. As your programming tasks get more complex, you will want to use objects and classes to organize your programs. Use static appropriately and parsimoniously. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Constants

Constants

Syntax 4. 1 Constant Definition Big Java by Cay Horstmann Copyright © 2009 by

Syntax 4. 1 Constant Definition Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Constants: final • A final variable is a constant • Once its value has

Constants: final • A final variable is a constant • Once its value has been set, it cannot be changed • Named constants make programs easier to read and maintain • Convention: Use all-uppercase names for constants final double QUARTER_VALUE = 0. 25; DIME_VALUE = 0. 1; NICKEL_VALUE = 0. 05; PENNY_VALUE = 0. 01; payment = dollars + quarters * QUARTER_VALUE + dimes * DIME_VALUE + nickels * NICKEL_VALUE + pennies * PENNY_VALUE; Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Packages

Packages

Packages • • Packages help organize your code Packages disambiguate Packages avoid naming conflicts

Packages • • Packages help organize your code Packages disambiguate Packages avoid naming conflicts Using the fully qualified name of an object, you need not import it (though it's best to import).

The API Documentation of the Standard Java Library Big Java by Cay Horstmann Copyright

The API Documentation of the Standard Java Library Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Packages • Package: a collection of classes with a related purpose • Import library

Packages • Package: a collection of classes with a related purpose • Import library classes by specifying the package and class name: import java. awt. Rectangle; • You don’t need to import classes in the java. lang package such as String and System Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Syntax 2. 4 Importing a Class from a Package Big Java by Cay Horstmann

Syntax 2. 4 Importing a Class from a Package Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Packages • Package: Set of related classes • Important packages in the Java library:

Packages • Package: Set of related classes • Important packages in the Java library: Package Purpose Sample Class java. lang Language support Math java. util Utilities Random java. io Input and output Print. Stream java. awt Abstract Windowing Toolkit Color java. applet Applets Applet java. net Networking Socket java. sql Database Access Result. Set javax. swing Swing user interface JButton omg. w 3 c. dom Document Object Model for XML documents Document Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Organizing Related Classes into Packages • To put classes in a package, you must

Organizing Related Classes into Packages • To put classes in a package, you must place a line package. Name; as the first instruction in the source file containing the classes • Package name consists of one or more identifiers separated by periods Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Importing Packages • Can always use class without importing: java. util. Scanner in =

Importing Packages • Can always use class without importing: java. util. Scanner in = new java. util. Scanner(System. in); • Tedious to use fully qualified name • Import lets you use shorter class name: import java. util. Scanner; . . . Scanner in = new Scanner(System. in) • Can import all classes in a package: import java. util. *; • Never need to import java. lang • You don’t need to import other classes in the same package Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Package Names • Use packages to avoid name clashes java. util. Timer vs. javax.

Package Names • Use packages to avoid name clashes java. util. Timer vs. javax. swing. Timer • Package names should be unambiguous • Recommendation: start with reversed domain name: com. horstmann. bigjava • edu. sjsu. cs. walters: for Britney Walters’ classes (walters@cs. sjsu. edu) • Path name should match package name: com/horstmann/bigjava/Financial. java Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Package and Source Files • Base directory: holds your program's Files • Path name,

Package and Source Files • Base directory: holds your program's Files • Path name, relative to base directory, must match package name: com/horstmann/bigjava/Financial. java Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Self Check 8. 18 Which of the following are packages? a. java b. java.

Self Check 8. 18 Which of the following are packages? a. java b. java. lang c. java. util d. java. lang. Math Answer: a. No b. Yes c. Yes d. No Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Self Check 8. 19 Is a Java program without import statements limited to using

Self Check 8. 19 Is a Java program without import statements limited to using the default and java. lang packages? Answer: No — you simply use fully qualified names for all other classes, such as java. util. Random and java. awt. Rectangle. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Gregorian Calendar Extra Credit

Gregorian Calendar Extra Credit

Asciify Example

Asciify Example

Polymorphism: assingment to references • An object (instantiated in memory) may be assigned to

Polymorphism: assingment to references • An object (instantiated in memory) may be assigned to the following reference types: • 1/ a reference type of the same type: – Double dub. Val = new Double(91. 5); • 2/ any superclass reference, including abstract classes. i. e; any class in the upline of that object’s hierarchy. – Number num. Num = new Double(9. 15); – Object obj. Num = new Double(91. 5);

Is-a; or to be or not to be. • . . . that is

Is-a; or to be or not to be. • . . . that is the question. • To check whether an instantiated object may be stored in reference of another type, it must affirmatively answer this question: "Is object a reference. Type? "

Upcasting/Downcasting

Upcasting/Downcasting

Polymorphism: assingment to references • 3/ Any Interface that the object implements Comparable com.

Polymorphism: assingment to references • 3/ Any Interface that the object implements Comparable com. Num = new Double(91. 5); •

Interfaces • A class implements an interface rather than extends it. Any class that

Interfaces • A class implements an interface rather than extends it. Any class that implements the interface must override all the interface methods with it's own methods. • Interface names often end with "able" to imply that they add to the capabilty of the class. • An interface is a contract; it defines the methods

Inheritence • A class that extends a superclass inherets all the fields and methods

Inheritence • A class that extends a superclass inherets all the fields and methods of its superclass AND those of its entire class hierarchy. • A superclass is more generic and contains less data. A subclass is more specific and contains more data. • Access to members through get and set.

Interfaces • A class implements an interface rather than extends it. Any class that

Interfaces • A class implements an interface rather than extends it. Any class that implements the interface must override all the interface methods with it's own methods. • Interface names often end with "able" to imply that they add to the capabilty of the class.

Sprint. Race Example

Sprint. Race Example

Poster Example

Poster Example

Console 21

Console 21

One player and one dealer play against one another in a game of 21.

One player and one dealer play against one another in a game of 21. A player starts with some money (100 dollars) and bets 10 dollars each hand. The game is played with a 52 -card chute. The game ends when the player decides to quit. Game-play starts with the player introducing himself by name, and the dealer dealing himself and the player two cards each. After the initial deal If the dealer and the player both have blackjack, then push, ask to play again. If the dealer has blackjack then the player loses his 10 dollars, ask to play again. If the player has blackjack, then the player wins 15 dollars, ask to play again If neither dealer nor player have blackjack, then the player has the option to either hit (so long as the total value of his hand is less than or equal to 21) or stick. If the player busts when hitting, then the player loses his 10 dollars, and is asked to play again. If the player does not bust, then the dealer is obliged to hit while his total is less than 17. If the dealer busts, then the player wins $10, and is asked to play again. If neither dealer nor player busts, then a tie will push. If the player has the highest hand, then the player wins $10, and is asked to play again. If the dealer has the highest hand, then the player loses $10, and is asked to play again. Once the hand is over, both players return their cards, and those cards are put-back onto the top of the chute. The chute is shuffled once 52 cards have been dealt.

Packages • • Packages help organize your code Packages disambiguate Packages avoid naming conflicts

Packages • • Packages help organize your code Packages disambiguate Packages avoid naming conflicts Using the fully qualified name of an object, you need not import it (though it's best to import).

Packages • Package: a collection of classes with a related purpose • Import library

Packages • Package: a collection of classes with a related purpose • Import library classes by specifying the package and class name: import java. awt. Rectangle; • You don’t need to import classes in the java. lang package such as String and System Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Syntax 2. 4 Importing a Class from a Package Big Java by Cay Horstmann

Syntax 2. 4 Importing a Class from a Package Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Packages • Package: Set of related classes • Important packages in the Java library:

Packages • Package: Set of related classes • Important packages in the Java library: Package Purpose Sample Class java. lang Language support Math java. util Utilities Random java. io Input and output Print. Stream java. awt Abstract Windowing Toolkit Color java. applet Applets Applet java. net Networking Socket java. sql Database Access Result. Set javax. swing Swing user interface Big Java by Cay Horstmann JButton Copyright © 2009 by John Wiley & Sons. All rights reserved. Document Object Model for XML

Organizing Related Classes into Packages • To put classes in a package, you must

Organizing Related Classes into Packages • To put classes in a package, you must place a line package. Name; as the first instruction in the source file containing the classes • Package name consists of one or more identifiers separated by periods Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Organizing Related Classes into Packages • For example, to put the Financial class introduced

Organizing Related Classes into Packages • For example, to put the Financial class introduced into a package named com. horstmann. bigjava, the Financial. java file must start as follows: package com. horstmann. bigjava; public class Financial {. . . } • Default package has no name, no package statement Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Importing Packages • Can always use class without importing: java. util. Scanner in =

Importing Packages • Can always use class without importing: java. util. Scanner in = new java. util. Scanner(System. in); • Tedious to use fully qualified name • Import lets you use shorter class name: import java. util. Scanner; . . . Scanner in = new Scanner(System. in) • Can import all classes in a package: import java. util. *; • Never need to import java. lang • You don’t need to import other classes in the same package Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Package Names • Use packages to avoid name clashes java. util. Timer vs. javax.

Package Names • Use packages to avoid name clashes java. util. Timer vs. javax. swing. Timer • Package names should be unambiguous • Recommendation: start with reversed domain name: com. horstmann. bigjava • edu. sjsu. cs. walters: for Britney Walters’ classes (walters@cs. sjsu. edu) • Path name should match package name: com/horstmann/bigjava/Financial. java Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Package and Source Files • Base directory: holds your program's Files • Path name,

Package and Source Files • Base directory: holds your program's Files • Path name, relative to base directory, must match package name: com/horstmann/bigjava/Financial. java Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Self Check 8. 18 Which of the following are packages? a. java b. java.

Self Check 8. 18 Which of the following are packages? a. java b. java. lang c. java. util d. java. lang. Math Answer: a. No b. Yes c. Yes d. No Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Java Doc • Generate default Java. Docs. • Using decorations/tags. • Project || Generate

Java Doc • Generate default Java. Docs. • Using decorations/tags. • Project || Generate Java. Doc. – In Eclipse; navigate to JDKbinjavadoc. exe to configure. • Scope; public to private methods • Use F 1 to pull up your javadocs.

Self Check 8. 19 Is a Java program without import statements limited to using

Self Check 8. 19 Is a Java program without import statements limited to using the default and java. lang packages? Answer: No — you simply use fully qualified names for all other classes, such as java. util. Random and java. awt. Rectangle. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Gregorian Calendar Example

Gregorian Calendar Example

Adding examples code to javadocs /** * * @param per. Soldiers Array. List<String> *

Adding examples code to javadocs /** * * @param per. Soldiers Array. List<String> * @return Person object * * <pre> * Example: * per. Senior = get. Most. Senior(per. Vets); //will return a reference to Person * </pre> */ Use the <pre> code here </pre> tages in javadocs before the methods Good idea!

Object Composition • • • Objects are composed of instance fields Instance fields can

Object Composition • • • Objects are composed of instance fields Instance fields can be primitives or other objects //fields of this class private String str. First. Name; private String str. Last. Name; private byte y. Age; //-128 to 127 private boolean b. Veteran; private String str. Social. Security. Num; private Array. List<Person> per. Dependents;

Imports and the Java API • Determine the version of Java you’re using. From

Imports and the Java API • Determine the version of Java you’re using. From the cmd line> java –version • http: //download. oracle. com/javase/6/docs/api/ • java. lang. * is automatically imported. This default behavior is know as ‘convention over configuration’. So • Eclipse is very good about importing packages and catching compile-time errors. • To use the javadoc for the core Java API; F 1 – JDKsrc. zip • To see source code; F 3