Strings. Useful methods of String char charAt(int index) int compareTo(String anotherString) boolean endsWith(String suffix) int indexOf(multiple) int.

Slides:



Advertisements
Similar presentations
Chapter 8: Designing Classes
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
Designing Classes Chapter 8. Classes Collection of objects Objects are not actions Class names – Nouns Method names – Verbs What Makes a Good Class Represent.
Chapter Goals To learn how to choose appropriate classes to implement
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
Chapter 7 Designing Classes Goals  To learn how to choose appropriate classes to implement  To understand the concepts of cohesion and coupling  To.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
Computer Science A 2: 6/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
Chapter 2  Using Objects 1 Chapter 2 Using Objects.
References, Aliases, Garbage Collection and Packages Packages and Importing Classes Reading for this Lecture: L&L, Familiarize yourself with.
Chapter 2: Objects and Primitive Data Classes and Objects String, Random, Math, NumberFormat, DecimalFormat and Wrapper Classes.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Recitation 2 Main Method, API & Packages, Java Basics.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 4 – Fundamental Data Types.
1 The String Class Every character string is an object in Java, defined by the String class Every string literal, delimited by double quotation marks,
Classes CS 21a: Introduction to Computing I First Semester,
ICOM 4015: Advanced Programming Lecture 8 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Reading: Chapter Eight:
Computer Programming 2 Lab(1) I.Fatimah Alzahrani.
Static. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A static method does not operate on an object double dY.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eight: Designing Classes.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. int: integers, no fractional part: 1, -4, 0 double : floating-point.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
1 JAVA API & Packages Starring: Java Documentation Co-Starring: BlueJ IDE.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A class represents a single concept from the problem domain, or a.
CSS446 Spring 2014 Nan Wang.  A Java program consists of a collection of classes.  Package is a set of related classes. 2.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Lecture 2 Content: Control Structures: Branching logic Control Structures: Looping logic Diagramming Reading Files from Scanner Type Conversions Promotion.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 8 – Designing Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 3: Using Classes and Objects Coming up: Creating Objects.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Week 13 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 7 Designing Classes. Chapter Goals  To learn how to choose appropriate classes to implement  To understand the concepts of cohesion and coupling.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A string is a sequence of characters Strings are objects of the String.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
1 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used as a type to declare an object reference.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Some basic concepts of Java. Adding psuedocode to javadocs /** // instantiate a date with today's date called datToday // create a datCount set at some.
Variables in Java A variable holds either
Lecture 03 Agenda > Gamers survey > Take QT Exam
Introduction to Classes and Objects
Classes, Libraries & Packages
Programming Language Concepts (CIS 635)
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 3 Introduction to Classes, Objects Methods and Strings
Java Programming Language
Chapter 2: Basic Elements of Java
Introduction to Computer Science and Object-Oriented Programming
Packages & Random and Math Classes
Using java libraries CGS3416 spring 2019.
Presentation transcript:

Strings

Useful methods of String char charAt(int index) int compareTo(String anotherString) boolean endsWith(String suffix) int indexOf(multiple) int length() String substring(int begin, int end) String trim()

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. When delcaring String, we can treat them as if they are primitives, but they are objects! – // String strAnimal= “Dog”; //these are equivalent – // String strAnimal = new String(“Dog”); //these are equivalent Immutable class: Has no mutator methods (e.g., String ): String strName = "John Q. Public"; String strUppercased = strName.toUpperCase(); // strName 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! String is Immutable

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 ==.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 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 strName = “Robert”; we are actually doing this: String strName = new String(“Robert”); The String Class

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

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

Escape Sequences to include the quotes in a string, use the escape sequences: strOne = "\"Quotation\""; to print \\ StrBackSlashes = "\\\\"; Unicode values cookbook/appendix.html

Escape Sequences Escape Sequenc e Character \nnewline \ttab \bbackspace \fform feed \rreturn \"" (double quote) \'' (single quote) \\\ (back slash) \uDDDD character from the Unicode character set (DDDD is four hex digits)

Keyboard Input edu.uchicago.cs.java.lec02.scanner

Keyboard Input Scanner -- or you can define your own Scanner scn = new Scanner(System.in); Scanner scn = new Scanner(File filSource); throws FileNotFoundException strInput = scn.nextLine();

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 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 nQuantity = scn.nextInt(); nextDouble reads a double nextLine reads a line (until user hits Enter) next reads a word (until any white space) Reading Input

Random See edu.uchicago.cs.java.lec02.random

Random numbers import java.util.Random; int n = rnd.nextInt(); double d = rnd.nextDouble(); int n = rnd.nextInt(int nNum); rnd.nextInt(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

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A static method does not operate on an object double dY = 4; double dY = matObject.sqrt(); // Error double dY = 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 Calling Static Methods

Implicit versus Explicit Parameters The implicit parameter is the object reference, whereas the explicit parameter(s) are/is the argument(s) to the method. strName.indexOf(cSpace); Math.pow(2,3); //no implicit param -- static Most often, when we refer to parameters, we mean the explicit parameters.

Example: public class Metric { public static double getKilograms(double dPounds){ return dPounds * 0.454; } // More methods can be added here. } Call with class name instead of object: double dKilos = Metric. getKilograms (150); Static Methods

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

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 dResult = 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 nResult = Random.nextInt(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.

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

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A static variable belongs to the class, not to any object of the class: public class BankAccount {... private double balance; private int accountNumber; private static int lastAssignedNumber = 1000; } If lastAssignedNumber was not static, each instance of BankAccount would have its own value of lastAssignedNumber Static Variables

Modifier | Class | Package | Subclass | World ————————————+———————+—————————+—————————— +——————— public | ✔ | ✔ | ✔ | ✔ ————————————+———————+—————————+—————————— +——————— protected | ✔ | ✔ | ✔ | ✘ ————————————+———————+—————————+—————————— +——————— no modifier | ✔ | ✔ | ✘ | ✘ ————————————+———————+—————————+—————————— +——————— private | ✔ | ✘ | ✘ | ✘

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

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 by John Wiley & Sons. All rights reserved. Exception: Static constants, which may be either private or public: public class BankAccount {... public static final double OVERDRAFT_FEE = 5; // Refer to it as BankAccount.OVERDRAFT_FEE } //in the above case, OVERDRAFT_FEE is a constant Static Variables

Class Objects

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 can 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. Self Check 8.15 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Constants

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

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 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; final double DIME_VALUE = 0.1; final double NICKEL_VALUE = 0.05; final double PENNY_VALUE = 0.01; payment = dollars + quarters * QUARTER_VALUE + dimes * DIME_VALUE + nickels * NICKEL_VALUE + pennies * PENNY_VALUE; Constants: final

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).

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

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 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 Packages

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 Copyright © 2009 by John Wiley & Sons. All rights reserved. PackagePurposeSample Class java.lang Language support Math java.util Utilities Random java.io Input and output PrintStream java.awt Abstract Windowing Toolkit Color java.applet Applets Applet java.net Networking Socket java.sql Database Access ResultSet javax.swing Swing user interface JButton omg.w3c.dom Document Object Model for XML documents Document Packages Package: Set of related classes Important packages in the Java library:

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

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 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 Importing Packages

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 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 ( ) Path name should match package name: com/horstmann/bigjava/Financial.java Package Names

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

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 Self Check 8.18 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

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. Self Check 8.19 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Gregorian Calendar Extra Credit

Asciify Example

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 dubVal = new Double(91.5); 2/ any superclass reference, including abstract classes. i.e; any class in the upline of that object’s hierarchy. – Number numNum = new Double(9.15); – Object objNum = new Double(91.5);

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 referenceType?"

Upcasting/Downcasting

Polymorphism: assingment to references 3/ Any Interface that the object implementsComparable comNum = new Double(91.5);

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 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 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.

SprintRace Example

Poster Example

Console21

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 Using the fully qualified name of an object, you need not import it (though it's best to import).

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 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 Packages

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 Copyright © 2009 by John Wiley & Sons. All rights reserved. PackagePurposeSample Class java.lang Language support Math java.util Utilities Random java.io Input and output PrintStream java.awt Abstract Windowing Toolkit Color java.applet Applets Applet java.net Networking Socket java.sql Database Access ResultSet javax.swing Swing user interface JButton omg.w3c.dom Document Object Model for XML documents Document Packages Package: Set of related classes Important packages in the Java library:

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

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 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 Organizing Related Classes into Packages

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 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 Importing Packages

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 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 ( ) Path name should match package name: com/horstmann/bigjava/Financial.java Package Names

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

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 Self Check 8.18 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Java Doc Generate default JavaDocs. Using decorations/tags. Project || Generate JavaDoc. – In Eclipse; navigate to JDK\bin\javadoc.exe to configure. Scope; public to private methods Use F1 to pull up your javadocs.

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. Self Check 8.19 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Gregorian Calendar Example

Adding examples code to javadocs /** * perSoldiers ArrayList Person object * * Example: * perSenior = getMostSenior(perVets); //will return a reference to Person * */ Use the code here tages in javadocs before the methods Good idea!

Object Composition Objects are composed of instance fields Instance fields can be primitives or other objects //fields of this class private String strFirstName; private String strLastName; private byte yAge; //-128 to 127 private boolean bVeteran; private String strSocialSecurityNum; private ArrayList perDependents;

Imports and the Java API Determine the version of Java you’re using. From the cmd line> java –version 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; F1 – JDK\src.zip To see source code; F3