800 likes | 1.05k Views
Java Programming: From the Ground Up. Chapter 9 Objects and Classes I: Encapsulation Strings and Things Slides produced by Antonio Martinez. Objects.
E N D
Java Programming:From the Ground Up • Chapter 9 Objects and Classes I: Encapsulation Strings and Things Slides produced by Antonio Martinez
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
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).
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.
Objects Three different remote objects, each with unique attribute values (data) but all sharing the same methods or behaviors.
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. • .
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
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
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
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().
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
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.*;
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);
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.
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
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.
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.
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.
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'
Strings Problem Statement Writea program that interactively accepts an arbitrary character string and displays the string in reverse.
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(); • } • }
Output Enter a word: AString AString in reverse is gnirtSA Enter a word: racecar racecar in reverse is racecar
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.
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."
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.
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.
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. .
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
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().
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.
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.
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’
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
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.
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
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
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
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
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.
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;.
More String Methods • Method int length( ) • Explanations.length() returns the number of characters in s. • ExampleString s = “Jaws”;s.length() returns 4
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”
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”
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”
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”
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”
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”
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.