Working with Strings, Arrays, and ArrayLists Flashcards

1
Q

How each character of a String is represented in Java?

A

In Java, each character in a string is a 16-bit Unicode character. Because Unicode characters are 16 bits (not the skimpy 7 or 8 bits that ASCII provides), a rich, international set of characters is easily represented in Unicode.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Are strings object or primitive?

A

Strings are objects and like every other object you can create instance of a string using new keyword.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the constructors that can be used to create a string object?

A
String s = new String("abcdef");
String s = "abcdef";
What they have in common is that they all create a new String object, with a value of "abcdef", and assign it to a reference variable s
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What happens when we concat a String?
String s = “abcdef”;
s = s.concat(“ more stuff”);

A

The Java Virtual Machine (JVM) took the value of string s (which was “abcdef”) and tacked “ more stuff” onto the end, giving us the value “abcdef more stuff”. Since strings are immutable, the JVM couldn’t stuff this new value into the old String referenced by s, so it created a new String object, gave it the value “abcdef more stuff”, and made s refer to it. At this point in our example, we
have two String objects: the first one we created, with the value “abcdef”, and the second one with the value “abcdef more stuff”. Technically there are now three String objects, because the literal argument to concat, “ more stuff”, is itself a new String object. But we have references only to “abcdef” (referenced by s2) and “abcdef more stuff” (referenced by s).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the output? For extra credit, how many String objects and how many reference variables were created prior to the println statement?

String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);
A

Answer: The result of this code fragment is spring winter spring summer. There are two reference variables: s1 and s2. A total of eight String objects were created as follows: “spring “, “summer “ (lost), “spring summer “, “fall “(lost), “spring fall “ (lost), “spring summer spring “ (lost), “winter “(lost), “spring winter “ (at this point “spring “ is lost). Only two of the eight String objects are not lost in this process.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How JVM uses String Constant Pool?

A

To make Java more memory efficient, the JVM sets aside a special area of memory called the String constant pool. When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created. (The existing String simply has an additional reference.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Is it possible to override String methods and for example make it mutable?

A
String class is marked final. Nobody can override the
behaviours of any of the String methods.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
What is the difference between these two string construction?
String s = "abc";
String s = new String("abc");
A

First one creates one String object and one. abc goes to pool and s references to it.
In second case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory and s will refer to it. In addition, the literal “abc” will be placed in the pool. It creates two objects and one reference variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is difference between String length and array length?

A

Arrays have an attribute (not a method) called length. You may encounter questions in the exam that attempt to use the length() method on an array or that attempt to use the length attribute on a String. Both cause compiler errors-consider these, for example:
String x = “test”;
System.out.println( x.length ); // compiler error
and
String[] x = new String[3];
System.out.println( x.length() ); // compiler error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the result?
String x = “0123456789”;
System.out.println( x.substring(5) );
System.out.println( x.substring(5, 8));

A

First one is “56789”

Second one is “567”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

When should one use StringBuilder class?

A
The java.lang.StringBuilder class should be used when you have to make a lot of modifications to strings of characters.A common use for StringBuilders is file I/O when large, ever-changing streams of input are being handled by the program. In these cases, large blocks
of characters are handled as units, and StringBuilder objects are the ideal way to handle a block of data, pass it on, and then reuse the same memory to handle the next block of data.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the difference between StringBuilder and StringBuffer?

A

Everything same apart from synchronization. StringBuffer’s method are sync.ed so it’s thread safe but slower.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
What is the result?
StringBuilder sb = new StringBuilder("abc");
sb.append("def");
System.out.println("sb = " + sb);
StringBuilder sb = new StringBuilder("abc");
sb.append("def").reverse().insert(3, "---");
System.out.println( sb );
A

First one is “sb = abcdef” and second one is “fed—cba”.
These StringBuilder methods operate on the value of the StringBuilder object invoking the method. So a call to sb.append(“def”); is actually appending “def” to itself (StringBuilder sb).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the rules to keep in mind when appending and inserting to StringBuilder?

A
  • If an append() grows a StringBuilder past its capacity, the capacity is updated automatically.
  • If an insert() starts within a StringBuilder’s capacity, but ends after the current capacity, the capacity is updated automatically.
  • If an insert() attempts to start at an index after the StringBuilder’s current length, an exception will be thrown.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the result?
StringBuilder sb2 = new StringBuilder(“pi = “);
sb2.append(3.14159f);
System.out.println(sb2);

A

Output is “pi = 3.14159”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
What is the result?
StringBuilder sb = new StringBuilder("0123456789");
System.out.println(sb.delete(4,6));
A

Output is “01236789”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the result?
StringBuilder sb = new StringBuilder(“01234567”);
sb.insert(4, “—”);
System.out.println( sb );

A

Output is “0123—4567”

18
Q

Where are arrays kept in Java?

A

Arrays can hold either primitives or object references, but the array itself will always be an object on the heap, even if the array is declared to hold primitive elements.

19
Q
Which are legal array declarations?
int[] key;
int key [];
Thread[] threads;
Thread threads[];
String[][][] occupantName; 
String[] managerName [];
A

All declarations are legal.

20
Q

When JVM allocates space for array?

A

JVM allocates space for array when it is actually instantiated. That’s when size matters.

21
Q

Are there any Thread objects after this code executes?

Thread[] threads = new Thread[5];

A

Despite how the code appears, the Thread constructor is not being invoked. We’re not creating a Thread instance, but rather a single Thread array object. After the preceding statement, there are still no actual Thread objects! The single object referenced by threads holds five Thread reference variables, but no Thread objects have been created or assigned to those references.

22
Q

What is the result?

int[] carList = new int[];

A

Will not compile; needs a size

23
Q

What does that code block tells?

int[][] myArray = new int[3][];

A

A two-dimensional array of type int is really an object of type int array (int []), with each element in that array holding a reference to another int array. Giving only first dimension size is OK since JVM needs to know only the size of the object assigned to the variable myArray.

24
Q
What do below lines mean?
int[][] scores = new int[3][];
scores[0] = new int[4];
scores[1] = new int[6];
scores[2] = new int[1];
A
int[][] scores = new int[3][];
// Declare and create an array (scores) holding three references
// to int arrays
scores[0] = new int[4];
// the first element in the scores array is an int array
// of four int elements
scores[1] = new int[6];
// the second element is an int array of six int elements
scores[2] = new int[1];
// the third element is an int array of one int element
25
Q

How do you get size of an array?

A

Arrays has a variable called length. It tells how many elements it holds but does not tell if the elements are ibitialized or not.

26
Q

int[][] scores = {{5,2,4,7}, {9,2}, {3,4}};

How many objects are created in this statement?

A

4- one array of ints arrays and three int arrays.

27
Q
Is this a legal array declaration?
new Object[3] {null, new Object(), new Object()};
A

No, size must not be specifed.

28
Q

What values can be assigned to primitive arrays?

A

Primitive arrays can accept any value that can be promoted implicitly to the declared type of the array.

29
Q
Are those declarations valid?
int[] weightList = new int[5];
byte b = 4;
char c = 'c';
short s = 7;
weightList[0] = b; 
weightList[1] = c; 
weightList[2] = s;
A

Yes,
int[] weightList = new int[5];
byte b = 4;
char c = ‘c’;
short s = 7;
weightList[0] = b; // OK, byte is smaller than int
weightList[1] = c; // OK, char is smaller than int
weightList[2] = s; // OK, short is smaller than int

30
Q

What values can be asssigned to object reference arrays?

A
If the declared array type is a class, you can put objects of any subclass of the declared type into the array.
If the array is declared as an interface type, the array elements can refer to any instance of any class that implements the declared interface.
The bottom line is this: Any object that passes the IS-A test for the declared array type can be assigned to an element of that array.
31
Q
Given 
int[] splats;
int[] dats = new int[4];
char[] letters = new char[5];
which assignments are valid?
splats = dats; 
splats = letters;
A
splats = dats; // OK, dats refers to an int array
splats = letters; // NOT OK, letters refers to a char array
32
Q
Given
Car[] cars;
Honda[] cuteCars = new Honda[5];
Beer[] beers = new Beer [99];
which assignments are valid?
cars = cuteCars;
cars = beers;
A
cars = cuteCars; // OK because Honda is a type of Car
cars = beers; // NOT OK, Beer is not a type of Car
33
Q

What can you assign to multi dimensional array references?

A

When you assign an array to a previously declared array reference, the array you’re
assigning must be in the same dimension as the reference you’re assigning it to.

34
Q
Given
int[] blots;
int[][] squeegees = new int[3][];
int[] blocks = new int[6];
which assignments are valid?
blots = squeegees;
blots = blocks;
A
blots = squeegees; // NOT OK, squeegees is a
// two-d array of int arrays

blots = blocks; // OK, blocks is an int array

35
Q
Given
int[][] books = new int[3][];
int[] numbers = new int[6];
int aNumber = 7;
which assignments are  valid?
books[0] = aNumber; 
books[0] = numbers;
A
books[0] = aNumber; // NO, expecting an int array not an int
books[0] = numbers; // OK, numbers is an int array
36
Q

What happens when you pass an object reference to System.out.print() or System.out.println()?

A

You’re telling them to invoke that object’s toString()

method.

37
Q

Can ArrayLists have duplicates?

A

Yes

38
Q

Can ArrayLists hold primitives or actual objects?

A

No. When you put an int to an ArrayList it is being autoboxed into an Integer object.

39
Q

What are some methods for ArrayLists?

A
  • add(element)
  • add(index, element)
  • clear()
  • boolean contains(element)
  • Object get(index)
  • int indexOf(Object)
  • remove(index)
  • remove(Object)
  • int size()
40
Q

How do we provide encapsulation?

A

When encapsulating a mutable object like a StringBuilder, or an array, or an ArrayList, if you want to
let outside classes have a copy of the object, you must actually copy the object and return a reference variable to the object that is a copy. If all you do is return a copy
of the original object’s reference variable, you DO NOT have encapsulation

41
Q

What are some String methods?

A

charAt(), concat(), equalsIgnoreCase(),
length(), replace(), substring(), toLowerCase(), toString(),
toUpperCase(), and trim()

42
Q

What are some StringBuilder methods?

A

append(), delete(), insert(), reverse(), and toString()