1 / 78

Java Programming: From the Ground Up

Java Programming: From the Ground Up. Chapter 9 Objects and Classes I: Encapsulation Strings and Things Slides produced by Antonio Martinez. Objects.

errol
Download Presentation

Java Programming: From the Ground Up

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Programming:From the Ground Up • Chapter 9 Objects and Classes I: Encapsulation Strings and Things Slides produced by Antonio Martinez

  2. Objects • An object is a representation or an abstraction of some entity such as a car, a dog, a flea, an elephant, a person, a house, or a string of characters. • An object may be physical, like a radio, or intangible, like a song. • Just as a noun is a person, place, or thing; so is an object

  3. Objects • An object has characteristics or attributes • An object has actions or behaviors. • Specifically, an object is an entity that consists of: • data (the attributes) • methods that use or manipulate the data • ( the behaviors).

  4. Objects • A remote control unit is an object. • A remote control object has three attributes: • the current channel, an integer, • the volume level, an integer, and • the current state of the TV, on or off, true or false, • Along with five behaviors or methods: • raise the volume by one unit, • lower the volume by one unit, • increase the channel number by one, • decrease the channel number by one, and • switch the TV on or off.

  5. Objects Three different remote objects, each with unique attribute values (data) but all sharing the same methods or behaviors.

  6. Objects The remote control unit exemplifies encapsulation. • Encapsulation is defined as the language feature of packaging attributes and behaviors into a single unit. • Data and methods comprise a single entity. • Each remote control object encapsulates data and methods, attributes and behaviors. • An individual remote unit, an object, stores its own attributes – channel number, volume level, power state – and has the functionality to change those attributes. • .

  7. Objects • A rectangle is an object. • The attributes of a rectangle might be length and width, two floating point numbers; the methods compute and return area and perimeter. • Each rectangle has its own set of attributes; all share the same behaviors

  8. Three rectangle objects

  9. Three String Objects • A character string is an object that encapsulates data and methods. • The string data consists of an ordered sequence of characters and two (of many) methods include a method that returns the number of characters in the String and one that returns the ith character

  10. Classes • A class is a template, or blueprint, from which objects are created. • A Rectangle class might specify that every Rectangle object consists of two variables of type double: • double length, and • double width, • Every Rectangle object comes equipped with two methods: • doublearea(), and //returns the area, length x width, • double perimeter(), //returns the perimeter, 2(length + width). • Individual Rectangle objects may differ in dimension but all Rectangle objects share the same methods

  11. Classes • The Scanner class, which is a member of the java.util , defines a host of methods including nextInt() and nextDouble(). • The statement: Scanner input = new Scanner(System.in); instantiates or creates a new Scanner object from a blueprint in java.util. • The variable input is a reference that holds the address of the newly created Scanner object. • All methods are accessed via input: e.g., input.nextInt(), input.nextDouble().

  12. Java Libraries and Packages • Java provides a rather large library containing hundreds of pre-defined classes which can be used as blueprints to create objects. • Related classes are organized or grouped into packages

  13. Java Libraries and Packages • To include a Java class in an application, use an importin either of two forms: • import java.packagename.classname;or • import java.packagename.*; • All import statements must appear in a file before any class definitions. For example, to use the Scanner class in an application, include either of the following import statements at the start of the file: • import java.util.Scanner; or • import java.util.*;

  14. Create an Object • To instantiate or create an object, use the new operator: • Scanner myScanner = new Scanner(System.in); or • Scanner myScanner; • myScanner = new Scanner(System.in);

  15. Random - Another Class of java.util • The methods available to a Random object can generate random numbers, both integer and floating point. To instantiate a Random object: • Random random= new Random(); • Some methods of Random: • int nextInt(int n): • returns an integer greater than or equal to 0 and less than n. • double nextDouble(): • returns a double value greater than or equal to 0.0 and less than 1.0.

  16. Random • Instantiate a Random object and generate two random numbers between 1 and 6 inclusive that simulate rolling a pair of dice: • Random die = new Random(); • int dice = (die.nextInt(6) + 1) + (die.nextInt(6) + 1); • To instantiate a Random object so that it always produces the same sequence of “random” numbers pass Random(...) a “seed,” that is, an arbitrary integer of type long. • Random rand = new Random(12345678); //123456768 is the seed // the seed can be any long integer

  17. The java.lang Package • One special package: • java.lang is automatically imported into every application. • The java.lang package contains the Math class and the String class.

  18. Strings Are Objects • The String class is contained in the java.lang package, which is imported automatically into every application. • The instantiation of a String object is accomplished with the newoperator. For example: • String myDog = new String("Fido"); • The variable myDog is not a String object but a reference to a String object. • myDog holds the address of a String object.

  19. Strings • Java provides a shorter form of String instantiation. The more compact statement: • String myDog = "Fido" • assigns the address of the String literal "Fido" to the reference myDog. • Two convenient String methods: • int length(), which returns the number of characters in a String, and • char charAt(int i), which returns the character at position i.

  20. Strings • The dot operator is used to invoke the method of any particular String object. • myDog.length() returns 4 since “Fido” consists of four characters • myDog.charAt(0) returns the character 'F' because, like arrays, are indexed from 0 • myDog.charAt(2) returns 'd'

  21. Strings Problem Statement Writea program that interactively accepts an arbitrary character string and displays the string in reverse.

  22. Strings Solution The Scanner method String next() // returns a reference to the next input string facilitates input. • //Reads a character string and prints it in reverse • import java.util.*; • public class Reverse • { • public static void main(String[] args) • { • Scanner input= new Scanner(System.in); • System.out.print("Enter a word: "); • String word = input.next(); // returns a String (reference) • System.out.print(word+ " in reverse is "); • for( int i = word.length() - 1; i >= 0; i--) • System.out.print(word.charAt(i)); • System.out.println(); • } • }

  23. Output Enter a word: AString AString in reverse is gnirtSA Enter a word: racecar racecar in reverse is racecar

  24. Discussion Line 9: String word = input.next(): • wordis declared as a reference variable. • The variable word is not a String object; word is reference that can the address of a String object. • input.next() skips whitespace andthe next string entered at the keyboard. The method returns a reference a String object • The address of this String object is assigned to the reference variable, word.

  25. Strings Are Objects Lines 11-12: for( int i = word.length()-1; i >= 0; i--) System.out.print(word.charAt(i)); • word.length()returns 3. • The loop iterates from 2 down to 0. • On each iteration, word.charAt(i) returns the character at position i: • i = 2; charAt(2) returns 'C' • i = 1; charAt(1) returns 'B' • i = 0; charAt(0) returns 'A'. • These three characters, are displayed as output. • Thus the output is the string "CBA."

  26. String Concatenation • Concatenation is the process of joining, connecting, or linking Strings together. • Strings can be joined or concatenated using the "+" operator or the more compact "+=" operator.

  27. String Concatenation

  28. The nextLine() Method • Another Scanner method is input.nextLine(). • The nextLine() method advances the Scanner to the beginning of the next line of input and returns a reference to a String object comprised of all the characters that were skipped in the process, including whitespace but excluding the newline character. • If input consists of a single line of text, nextLine() returns a reference to a String comprised of the entire line, including spaces and tabs. • The nextLine() method advances the Scanner past the current line and returns the input that was skipped. • The method returns the rest of the current line, excluding any line separator at the end. • The position is set to the beginning of the next line.

  29. The nextLine() Method • Consider the following segment: System.out.print("Enter String on one line: "); String message = input.nextLine(); System.out.print("Enter an integer in the range 0-25: "); int num = input.nextInt() ; • If the input is Hello 8 then message refers to “Hello” and num gets the value 8. .

  30. The nextLine() Method • Change the segment and begin with a request for shift:  System.out.print("Enter an integer in the range 0-25 : "): int num = input.nextInt() ; System.out.print("Enter String on one line: "); String message = input.nextLine(); • With valid input: 8 Hello num gets the value 8

  31. The nextLine() Method • After reading the 8, the Scanner is positioned before the (invisible) newline character following 8. • The call to nextLine() advances the Scanner to the beginning of the next line and returns the input that was skipped, that is, the empty string! • Thus message refers to the empty string and not "Hello” • Using nextLine() for reading strings line by line, causes no problems. • However, care must be taken when mixing calls to nextLine() with other Scanner calls such as next(), nextInt() or nextDouble().

  32. Strings are Immutable • Java String objects are immutable. • Strings are read-only.  • A String reference may be reassigned, but once a String object is created, that object cannot be altered. • String s = "E.T."; s = s.toLowerCase(); • The assignment statement instantiates a new String object referenced by s.

  33. Strings are Immutable The variable s references the String "E.T."And, the method call on line 2 creates a new object (with lower case letters). The variable s references a new String; "E.T" is no longer accessibleThe original String object ("E.T.") has not been changed. Instead, a new String is created. The original String object ("E.T.") is now inaccessible because no reference holds its address.

  34. More String Methods • Methodchar charAt(int index) • Explanations.charAt(i) returns the character at index i. All Strings are indexed from 0. • ExampleString s = “Titanic”;s.charAt(3) returns ‘a’

  35. More String Methods • Method int compareTo(String t) • Explanationcompares two Strings, character by character, using the ASCII values of the characters.s.compareTo(t) returns a negative number if s < t.s.compareTo(s) returns 0 if s == t.s.compareTo(t) returns a positive number if s > t. • ExampleString s = “Shrek”;String t = “Star Wars”;s.compareTo(t) returns a negative number.s.compareTo(s) returns 0.t.compareTo(s) returns a positive number

  36. More String Methods • Method int compareTolgnoreCase(String t) • Explanationsimilar to compareTo(...) but ignores differences in case. • ExampleString s = “E.T.”;String t = “e.t.”; s.compareToIgnorecase(t) returns 0.

  37. More String Methods • Method boolean endsWith(String suffix) • Explanations.endsWith(t) returns true if t is a suffix of s. • ExampleString s = “Forrest Gump”;s.endsWith(“ump”) returns true

  38. More String Methods • Method boolean startsWith(String prefix) • Explanations.startsWith(t) returns true if t is a prefix of s. • ExampleString s = “ Jurassic Park”;s.startsWith(“Jur”) returns true s.startsWith(“jur”) returns false

  39. More String Methods • Method boolean equals(Object t)(The strange parameter will make sense later. For now, think of the parameter as String) • Explanations.equals(t) returns true if s and t are identical. • ExampleString s = “FINDING NEMO”;String t = “Finding Nemo”;s.equals(t) returns falses.equals("FINDING NEMO") returns true

  40. More String Methods • Method boolean equalslgnoreCase(String t) • Explanations.equalsIgnoreCase(t) returns true if s and t are identical, ignoring case. • ExampleString s = “FINDING NEMO”;String t = “Finding Nemo”;s.equalsIgnorecase(t) returns true

  41. More String Methods • Method int indexOf(String t) • Explanations.indexOf(t) returns the index in s of the first occurrence of t and returns -1 if t is not a substring of s. • ExampleString s = "The Lord Of The Rings";s.indexOf("The") returns 0;s.indexOf("Bilbo") returns –1.

  42. More String Methods • Method int indexOf(String t, int from) • Explanations.indexOf(t, from) returns the index in s of the first occurrence of t beginning at index from; an unsuccessful search returns –1. • ExampleString s = "The Lord Of The Rings";s.indexOf("The", 6) returns 12;.

  43. More String Methods • Method int length( ) • Explanations.length() returns the number of characters in s. • ExampleString s = “Jaws”;s.length() returns 4

  44. More String Methods • Method String replace( char oldChar, char newChar) • Explanations.replace(oldCh, newCh)returns a String obtained by replacing every occurrance of oldChwith newCh. • ExampleString s = “Harry Potter”;s.replace (‘r’,’m’) returns “Hammy Pottem”

  45. More String Methods • Method String substring(int index) • Explanations.substring(index) returns the substring of s consisting of all characters withindex greater than or equal to index. • ExampleString s = “The Sixth Sense”;s.substring(7) returns “th Sense”

  46. More String Methods • Method String substring(int start, int end) • Explanations.substring(start, end) returns the substring of s consisting of all characters with index greater than or equal to start and strictly less than end. • ExampleString s = “The Sixth Sense”;s.substring(7, 12) returns “th Se”

  47. More String Methods • MethodString toLowerCase() • Explanations.toLowerCase() returns a String formed from s by replacing all upper case characters with lower case characters. • ExampleString s = “The Lion King”;s.toLowerCase() returns “the lion king”

  48. More String Methods • Method String toUpperCase() • Explanations.toUpperCase() returns a String formed from s by replacing all lower case characters with upper case characters. • ExampleString s = “The Lion King”;s. toUpperCase() returns “THE LION KING”

  49. More String Methods • Method String trim() • Explanations.trim()returns the String with all leading and trailing white space removed. • ExampleString s = “ Attack of the Killer Tomatoes “;s.trim() returns “Attack of the Killer Tomatoes”

  50. equals(...) and == • To determine whether or not the character sequences of two String objects are identical use the equals(...) method. • The == operator compares references (addresses) not characters.

More Related