APCS: Unit 5

¡Supera tus tareas y exámenes ahora con Quizwiz!

What is the output: "APCS Rules!".substring(11)

""

True or false? (a)Literal strings are objects of the String type. (b)The \n character is not allowed in literal strings. (c)The value of a literal string also serves as this string's name. (d)You can call a literal string's methods, as in "Hello".equals(str).

(a) T (b) F (c) F (d) T

Consider the following method: public String mince(String str) { int n = str.length() / 3; if (n >= 1) { str = mince(str.substring(2*n)) + mince(str.substring(n, 2*n)) + mince(str.substring(0, n)); } return str; } True or false? The call str.equals(mince(str)) returns true for the following value of str: (a) "*********" (b) "ababcbaba" (c) "123454321"

(a) T (b) T (c) T

What is the output given String date: "May 6, 2016" of date.indexOf("2015")?

-1

Literal Strings

-A String literal is a sequence of zero or more characters contained in double quotes. -Literal strings don't have to be constructed: they are "just there." Literal Strings: -can be assigned to String variables. -can be passed to methods and constructors as parameters.

Where is a method defined / what does it return / what can their parameters be?

-A method is always defined inside a class. -A method returns a value of the specified type unless it is declared void; the return type can be any primitive data type or a class type. -A method's parameters can be of any primitive data types or class types.

What does a methods name look like?

-A method name starts with a lowercase letter. -Method names usually sound like verbs. -The name of a method that returns the value of a field often starts with get: (getters or accessors) **getWidth, getX -The name of a method that sets the value of a field often starts with set:(setters or mutators) **setLocation, setText -If you have multiple names, remember camel case ex: getTheNameOfTheFriend

Local variables

-Any variable defined inside the curly braces of a method (or inside any block statement, such as if/else clauses or bodies of loops) is a local variable -Local variables can be declared inside a method -The formal parameters of a method are also local variables when the method is invoked -When the method finishes, all local variables are destroyed (including the formal parameters) -Keep in mind that instance variables, declared at the class/object level, exist for as long as the object exists ex: public String toString() { String result = "" + faceValue; return result; } **The variable named result is accessible only inside this toString() method

Methods - concatenation

-Given two strings, you can concatenate them to one long string using '+'. The result consists of all characters in the first string followed by all characters in the second string. -" " is an empty space -When the expression to the left or right of a + operator is a string, the other one is automatically forced to become a string as well, and both strings are concatenated. ex: String result = s1 + s2; //concatenates s1 and s2 String result = s1.concat (s2); //the same as s1 + s2 result += s3; //concatenates s3 to result result += num; //converts num to String and concatenates it to result

NullPointer Exception

-If you try to call a method or access a public field through a null reference, your program "throws" a NullPointerException -You never need to throw a NullPointerException yourself.

Why is a String immutable

-In Java, String is a final (cannot be modified) and immutable class, which makes it the most special. -It cannot be inherited, and once created, we can not alter the object. -The hashcode of a string is frequently used in Java. Being immutable guarantees that hashcode (integer value that is associated with each object) will always be the same so that it can be cashed without worrying about the changes. -String object is one of the most-used objects in any of the programs. -That means, there is no need to calculate hashcode every time it is used. This is more efficient.

Restrictions with using Strings

-May not span multiple lines. ex: "This is not a legal String." -May not contain a " character. ex: "This is not a "legal" String either."

What are overloaded methods?

-Methods of the same class that have the same name but different numbers or types of parameters are called overloaded methods. -Use overloaded methods when they perform similar tasks -The return type alone is not sufficient for distinguishing between overloaded methods.

Important info regarding Strings

-Most people think that numbers are what computers are really good at, but many programmer work more with text than with numbers. -Think of text as individual letters being strung together. -In Java when working with Strings and it's methods the 1st letter in a String is called position "0" i.e. 0 1 2 3 4 5 6 7 C o m p u t e r -Strings are very useful when working with text. -String is not a primitive data type -Strings work like any other objects, with two exceptions: **Strings in double quotes are recognized as literal constants ** + and += concatenate strings (or a string and a number or an object, which is converted into a string)

How are objects passed?

-Objects are always passed as references: the reference is copied, not the object. -This is different from other languages, such as C++, where you can pass an object either "by value" (copy the whole object and pass the copy to the method), or "by reference" (pass the address of the same object to the method). In Java the object is NEVER copied into the parameter inside a method; instead, a copy of the reference is passed to a method.

Immutability

-Once created, a string cannot be changed: none of its methods can change the string. -Such objects are called immutable. -Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change. -Integer, Character and Double - wrapper classes are immutable too. -Java has another class for representing character strings called StringBuffer. -StringBuffer objects are not immutable -There are methods to change characters and other things.

What is some important information regarding parameters?

-Parameters are like "placeholders" for the actual values passed to the method (i.e. the arguments) when the method is called. -Explicit parameters are those that appear in the parameter list in the method heading. -Every method has an additional implicit parameter that does not appear in the parameter list. It is a reference to the object for which the method is called, and its name is this. -Keyword this may be used implicitly (without appearing in the statement) whenever the method accesses one of the object's instance variables, or calls another method for the same object.

Parameter vs. Argument

-Parameters are used in a function/method definition -Arguments are used in a function/method call

How are primitive parameters passed?

-Primitive data types are always passed "by value": the value is copied into the parameter. -So, there is no way to write a swap(int x, int y) method in Java. A method cannot change the value of a variable (of a primitive data type) passed to it. Actually, this is not such a big limitation as it might first appear. If a method needs to change a variable's value, that variable is usually a field in an object or an element in an array, and a reference to that object or array can be passed to the method.

Methods - length, CharAt

-Returns the number of characters in the string -Returns the k-th char ex: int length (); char charAt (k); "Flower".length(); // returns 6 "Wind".charAt (2); // returns 'n'

How do compilers treat overloaded methods?

-The compiler treats overloaded methods as completely different methods. -The compiler knows which one to call based on the number and the types of the parameters passed to the method.

What is an implicit parameter?

-The implicit parameter is a reference to the object for which the method is called -It is the object variable before the method name in the method call, the object on which a method is invoked. Implicit parameters are not defined within a method declaration because they are implied by the class the method is in. The implicit parameter is the object the method belongs to. ex: Employee dave = new Employee(); dave.setJobTitle("Candlestick Maker") **dave is the implicit parameter

Differences between strings and literals

-They have access to the same methods, but there is a difference between literal and non-literal Strings. -Unlike String literals, Strings that are created using a String constructor and the new operator will point to different objects regardless of the String that they hold. -When a String literal is created, all occurrences of other String literals with the same value will point to the same object. ex: String m1 = "hello"; String m2 = "hello"; In addition, all other future occurrences of "hello" in this program will refer to this same object!

"Throw" error handling

-Throw it if the arguments passed to your method fall outside acceptable values. -This Percentage type only accepts values between 0 and 100 inclusive; any value outside that range throws an exception. Syntax: if (an argument does not meet some specific pre-condition) { throw new IllegalArgumentException("explanation of what failed and why"); }

How would you define a method?

-decide between public and private (usually public) give it a name -specify the types of parameters and give them names -specify the method's return type or chose void -write the method's code

String concatenation

-string concatenation: Using + between a string and another value to make a longer string. ex: "hello" + 42 is "hello42" 1 + "abc" + 2 is "1abc2" "abc" + 1 + 2 is "abc12" 1 + 2 + "abc" is "3abc" "abc" + 9 * 3 is "abc27" "1" + 1 is "11" 4 - 1 + "abc" is "3abc -Use + to print a string and an expression's value together. ex: System.out.println("Grade: " + (95.1 + 71.9) / 2); Output: Grade: 83.5

What's an explicit parameter?

-they are passed by specifying the parameter in the parenthesis of a method call. It is all parameters except the implicit parameter. ex: System.out.println(greeting) **greeting is the explicit parameter

A playing card has a rank represented by an integer from 1 to 13 and a suit represented by an integer from 1 to 4. (c) Let's say card1 beats card2 if they have the same suit and card1 has a higher rank. Write the following method of the PlayingCard class:

// Returns true if this card beats other; otherwise returns // false. public boolean beats(PlayingCard other) { return suit == other.suit && rank > other.rank; //or // getSuit() == other.getSuit && getRank() > other.getRank(); }

The length method returns ______________ for an empty string.

0

What are the two ways to create a new string?

1. By using the keyword new and the String constructor method. • Example: String word = new String("Happy"); 2. By using the short-cut technique. (Only Strings have a short-cut like this—all other objects are constructed by using the new operator.) • Example: String m1 = "hello"; **This short-cut technique results in what we call a String Literal!

What is the output given String date: "May 6, 2016" of date.indexOf('6',5)?

10

What output is produced by these statements? String name = "Joanne Hunt"; System.out.println(name.length());

11

String message = "Java is cool!" What is the value of message.length()?

13

What does this print: System.out.print (1 + 2 + "yolo" + 4 + 6)?

3yolo46

What is the output given String date: "May 6, 2016" of date.indexOf('6')?

4

What is the output given String date: "May 6, 2016" of date.indexOf("2016")?

7

Given a String stars, which of the following calls returns the position of the first occurrence of '*' in it? A.stars.indexOf('*'); B. stars.firstIndexOf('*'); C. stars.charAt('*'); D. stars.find('*');

A

Given two strings, s1 and s2, what is the difference between s1 + s2 and s1.concat(s2)? A. No difference B. s1 may be a literal string in s1 + s2 but not in s1.concat(s2) C. s1.concat(s2)changes s1, while s1 + s2 leaves both s1 and s2 unchanged D. s1 + s2 changes s1, while s1.concat(s2) leaves both s1 and s2 unchanged

A

If String str = "ABCDE", what string is returned by str.substring(2, 3)? A."C" B. "BC" C. "CDE" D. "BCD"

A

Which of the following corresponds to a valid constructor header for the Player class? A) public Player() B) private Player() C) public void Player() D) private void Player()

A

Which one of the following statements can be used to extract the last five characters from any string variable str? a) str.substring(str.length() - 5, str.length()) b) str.substring(5, 5) c) str.substring(str.length() - 4, 5) d) str.substring(str.length() - 5, 5)

A

String objects

A String object is a sequence of characters. Strings are objects, so... they have access to methods! assigning one String to another copies the reference to the same String object.

Empty Strings

An empty string has no characters; its length is 0.

Instance variables belong to __________.

An object

What happens if str.length() is 8 and you call str.charAt(8)? A. charAt returns the last character of str B. StringIndexOutOfBoundsException C. charAt returns the random character that happens to be stored after the string D. charAt returns -1

B

Which of the following denotes the implicit parameter? A) void B) this C) extends D) public

B

Given, String word1 = "at", word2 = "Cat"; what is returned by word1.compareTo(word2)? A. true B. false C. A positive integer D. A negative integer

C

If s is a String, what does s.substring(5) do? A. Nothing: s doesn't have such a method B. Returns a substring made of the first 5 characters in s C. Returns the tail of s starting from the sixth character D. Returns a substring made of the 6th character in s

C

Input to a method enclosed in parentheses after the method name is known as ______________. ' A) implicit parameters B) interfaces C) explicit parameters D) return values

C

The object on which the method call is invoked provides input to the method, and is called a(n) A) interface B) procedure C) implicit parameter D) explicit parameter

C

What is the output of the following code segment? String str1 = "A"; String str2 = str1; str2 += "B"; System.out.println(str1 + str2); A. AB B. BA C. AAB D. ABAB

C

Which method call represents the invocation of a method that does not have explicit parameters? A) greeting.replace("Hello", "Welcome"); B) greeting.length C) greeting.length() D) System.out.println(greeting);

C

The + operator is used to ___________________ two or more strings?

Concatenate

A method is invoked on what type of parameter? A) public parameter B) explicit parameter C) private parameter D) implicit parameter

D

What is the main advantage of immutable objects? A. They don't need constructors B. They can be returned from methods C. They can be used for initializing static fields D. Several references can safely refer to the same object — no need to copy

D

Which of the following is a valid constructor header for the Player class that accepts the player name as a parameter? A) public void Player(String playerName) B) private Player(playerName) C) private void Player(playerName) D) public Player(String playerName)

D

What is the implicit and explicit parameter of: momsSavings.deposit(500)

Implicit: momsSavings Explicit: 500

What does "this" refer to inside a method?

Inside a method, this refers to the object for which the method was called. this can be passed to other constructors and methods as a parameter -The this reference allows an object to refer to itself -The this reference used inside a method refers to the object in which the method is being executed -The this reference can be used to distinguish the instance variable names of an object from local method parameters with the same names -The this reference allows us to use the same name for instance data and a local variable or parameter in a method and resolves ambiguity

Assuming that the user inputs "Joe" at the prompt, what is the output of the following code snippet? public static void main(String[] args) { System.out.print("Enter your name "); String name; Scanner in = new Scanner(System.in); name = in.next(); name += ", Good morning"; System.out.print(name); }

Joe, Good morning

Methods - replacements

String s2 = s1.trim (); //returns a new string formed from s1 by removing white space at both ends. //trim() only removes whitespaces at the ends of the string, not in the middle. String s2 = s1.replace(oldCh, newCh); //returns a new string formed from s1 by replacing all occurrences of oldCh with newCh String s2 = s1.toUpperCase(); String s2 = s1.toLowerCase(); //returns a new string formed from s1 by converting its characters to upper (lower) case Example - how to convert s1 to upper case: s1 = s1.toUpperCase();

Fill in the missing code to print out: Hry String str = "Harry"; int n = _____________________ String mystery = ___________________ System.out.println(mystery);

String str = "Harry"; int n = str.length(); String mystery = str.substring(0, 1) + str.substring(n - 2, n);

Given, String title = " The Cat\n in the Hat\n "; what is displayed by the following statements? System.out.println(title.trim()); System.out.println("============");

The Cat in the Hat ============

What is the output of the following code snippet? public static void main(String[] args) { String str1; str1 = "I LOVE MY COUNTRY"; String str2 = str1.substring(4, 11); System.out.println(str2); }

VE MY C

Write code w/ and w/o a "this" reference

Without: public class Die { private int faceValue; public Die (int value) { faceValue = value; } } With: public class Die { private int faceValue public Die (int faceValue) { this.faceValue = faceValue; } }

Given, String title = "=== The Cat in the Hat ==="; what is displayed by the following statement? System.out.println("[" + title.replace('=',' ').replace(' ', '*') + "]");

[****The*Cat*in*the*Hat****]

How can you include a double quote character into a literal string?

\"

Methods - comparisons

boolean b = s1.equals(s2); //returns true if the string s1 is equal to s2 boolean b = s1.equalsIgnoreCase(s2); //returns true if the string s1 matches s2, case-blind int diff = s1.compareTo(s2); //returns the "difference" s1 - s2 int diff = s1.compareToIgnoreCase(s2); //returns the "difference" s1 - s2, case-blind -string1.compareTo(string2) < 0 means: string1 comes before string2 in the dictionary -string1.compareTo(string2) > 0 means: string1 comes after string2 -string1.compareTo(string2) == 0 means: string1 equals string2 -"car" comes before "cargo" -All uppercase letters come before lowercase: "Hello" comes before "car"

String message = "Java is cool!" What is the value of message.substring(8)?

cool!

What is the output: System.out.println(s1.equals(s2)); // String s1 = new String ("hello"); String s2 = new String ("Hello"); String s3 = "hello"; String s4 = "hello";

false

What is the output: System.out.println(s3==s1); // String s1 = new String ("hello"); String s2 = new String ("Hello"); String s3 = "hello"; String s4 = "hello";

false

String message = "Java is cool!" What is the value of message.substring(5,10)?

is co

A playing card has a rank represented by an integer from 1 to 13 and a suit represented by an integer from 1 to 4. (b) Here is a copy constructor for the PlayingCard class. A copy construct is a constructor that takes only one argument which is of the type as the class in which the copy constructor is implemented. Copy constructors are widely used for creating duplicates of objects known as cloned objects. Duplicate object in a sense the object will have the same characteristics of the original object from which the duplicate object is created. But we have to ensure that both original and duplicate objects refer to different memory locations. This IS NOT on the test....it was just part of this example.

public PlayingCard (PlayingCard other) { suit = other.suit; //or other.getSuit(); rank = other.rank; //or other.getRank(); }

Write a method that finds the first opening and the last closing parenthesis in a given string and returns the string inside. If not found or if the closing parenthesis precedes the opening one, your method should return the original string unchanged.

public String extractParens (String s) { int pos1 = s.indexOf ('('); int pos2 = s.lastIndexOf (')'); if (pos1 >= 0 && pos2 >= 0 && pos1 < pos2) s = s.substring (pos1 + 1, pos2); return s; }

A playing card has a rank represented by an integer from 1 to 13 and a suit represented by an integer from 1 to 4. (d) Provide a reasonable toString method.

public String toString() { output = "Card: rank = " + rank + "; suit = " + suit; return output; }

Fill in the blanks in the following method: // Returns true if p matches, case blind, a substring of s; // otherwise returns false. public boolean hasMatch(String s, String p) { return ______________________________________________ ________________________________________________; }

public boolean hasMatch (String s, String p) { return s.toUpperCase().indexOf(p.toUpperCase()) >= 0; }

A playing card has a rank represented by an integer from 1 to 13 and a suit represented by an integer from 1 to 4. (a) Write a class PlayingCard to represent a playing card. Design your class in accordance with the encapsulation principle. Write a constructor that takes two parameters: the values for the card's rank and suit. Also write a no-args constructor that sets the card's rank and suit to 1. Provide accessors for the rank and suit fields.

public class PlayingCard() { private int suit, rank; public PlayingCard() { suit = 1; rank = 1; } public PlayingCard(int s, int r) { suit = s; rank = r; } public int getSuit() { return suit; } public int getRank() { return rank; }

Write a statement that takes a phone number, stored as a ten-character string (of digits only) called phoneNumber, and converts it into a string that has parentheses around the area code

String newNumber = "(" + phoneNumber.substring(0, 3) + ")" + phoneNumber.substring(3, 10);

What is the output: "Halloween".charAt(5)?

w

Methods - substring

String greeting = "Hello, World!" String sub1 = greeting.substring(0,5); //sub 1 is "Hello" String sub2 = greeting.substring(7); // sub 2 is "World!" int length = greeting.length(); // length is 13

What is the main difference between String and StringBuffer classes?

Mutability

A method name is ____________________ if a class has more than one method with that name (but different parameter types).

Overloaded

The input to a method is called a(n) _______________.

Parameter

The output of a method is called its __________ value.

Return

How lexicographic ordering works?

Start at the left end of each String and do a character by character comparison until you reach the first character in which they differ. Then determine which of those two characters comes first in ASCII code.(Digits come first, then Capital Letters, then Lower Case Letters....spaces come before all printable characters) if s1 comes after s2, then s1 > s2, so s1.compareTo(s2) will return an int > 0 if s1 comes before s2, then s1 < s2, so s1.compareTo(s2) will return an int < 0 if s1 equals s2, then s1 == s2, so s1.compareTo(s2) will return 0

Methods - Find (indexOf)

String date ="July 5, 2012 1:28:19 PM"; date.indexOf ('J'); 0 date.indexOf ('2'); 8 date.indexOf ("2012"); 8 date.indexOf ('2', 9); 11 date.indexOf ("2020"); -1 date.lastIndexOf ('2'); 15

A playing card has a rank represented by an integer from 1 to 13 and a suit represented by an integer from 1 to 4. (e) Write a client class that tests PlayingCard's two constructors (the two-parameter constructor and the no-args constructor) and the beats method.

public class PlayingCardTest { public static void main (String[] args) { PlayingCard card1 = new PlayingCard(); PlayingCard card2 = new PlayingCard(2,10); PlayingCard card3 = new PlayingCard(2,7); PlayingCard card4 = new PlayingCard(3,7); PlayingCard card5 = new PlayingCard(card4); System.out.println ("Card 1 = " + card1 + " Card 2 = " + card2 + " Card 3 = " + card3 + " Card 4 = " + card4 + " Card 5 = " + card5); System.out.println ("Card 2 beats card 3: " + card2.beats(card3)); System.out.println ("Card 2 beats card 4: " + card2.beats(card4)); System.out.println ("Card 3 beats card 2: " + card3.beats(card2)); System.out.println ("Card 3 beats card 4: " + card3.beats(card4)); System.out.println ("Card 4 beats card 2: " + card4.beats(card2)); System.out.println ("Card 4 beats card 3: " + card4.beats(card3)); }

Example of a "throw"

public class TestScores { private final int[] scores; public TestScores(int[] scores) ... for(int score: scores) { if(score < 0 || score > 100) { throw new IllegalArgumentException("Score is not valid!"); } sum += score; } return sum/scores.length; } }

Write a method public void toCanonicalForm(StringBuffer address) that converts all letters in address to the upper case and all non-alphanumeric characters to spaces.

public void toCanonicalForm (StringBuffer adress) { for (int i = 0; i < adress.length(); i++) { char c = adress.charAt (i); if (Character.isLetter (c)) { c = Character.toUpperCase(c); } else if (!Character.isLetterOrDigit(c)) { c = ' '; } adress.setCharAt(i, c); }

Write the statement that would compute the length of the string str

str.length()

What is the output: System.out.println(s1.equalsIgnoreCase(s2)); // String s1 = new String ("hello"); String s2 = new String ("Hello"); String s3 = "hello"; String s4 = "hello";

true

What is the output: System.out.println(s3==s4); // String s1 = new String ("hello"); String s2 = new String ("Hello"); String s3 = "hello"; String s4 = "hello";

true


Conjuntos de estudio relacionados

Chapter 15 Infection and Human Immunodeficiency Virus Infection

View Set

Patho Ch 11 Spleen Review Questions

View Set

Anatomy Chapter 12 Lymphatic System and Body Defenses

View Set

Anatomy - Chapter 6 Study Guide Test

View Set

A&P I Lecture exam #3 review Part 1

View Set

Physics Units 3 & 4 Concept Quizzes

View Set