Arrays & String Handling Flashcards
Create array of 12 integers
int month_days[] = new int[12];
or
int month_days[] = {31,28,25,43,23};
Can you have multidimensional array where the sizes of second dimension are unequal?
yes, it’s an array of arrays, so you can define the vertical dimension per each row.
T/F: Java implements strings as an object type String, whereas other languages implement them as character arrays?
True
T/F: String objects cannot be changed.
True, you cannot change the characters of a String.
Each time you create an altered version, a new String object is created.
How do you create a modifiable String?
use StringBuffer or StringBuilder
Create array of characters
Create a string from 3rd letter that lasts 3 characters
char chars[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’};
String s = new String(chars, 2,3);
Explain how string concatenation works with other data types
int age = 34
String s = “He is “ + age + “years old”
int value of age is automatically converted to string representation within the String object
Explain what happens what you do println of a newly created class
Box b = new Box(2,3,4)
System.out.println(b)
automatically calls b.toString() method.
However, this is seldom sufficient and you likely want to override toString() in the new class to define it how you like.
Explain:
String s1 = “Hello”
String s2 = new String(s1)
System.out.println(s1.equals(s2))
System.out.println(s1==s2)
Output:
true
false
equals method compares the characters within the String object.
== checks if references the same instance
String arr[] = {“a”, “asdf”, “as”}
Return the length of arr
arr.length
which is 3
What does compareTo do to Strings? What are the output values?
String a = “AAAAAAA”
String b = “BBBBBBB”
Returns if before or after in the dictionary
<0 is earlier
>0 is later
0 is equal
What does indexOf do?
Finds first occurrence of that character in the string
explain String method replace()
replaces a character or character sequence with another
explain String method trim()
removes leading and trailing whitespace
what does valueOf() do?
returns the human-readable String value of that input (e.g. integer to string)