Strings Flashcards

String basics and String methods

1
Q

‘new’ keywords stores objects in which memory type?

A

heap memory

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

in which memory are literals stored?

A

pool memory

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

What are the 2 ways to create a String?

A

String str = new String(“Java”)
String str = (“Java”)

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

Method to check length of String?

A

int l = str.length()

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

Method to find character at specified index?

A

int s = str.charAt(5)

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

Method to search a character in the String from left to right and right to left?

A

str.indexOf(“k”, starting index), str.lastIndexOf(“J”,starting index)

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

What are the return types of compareTo method?

A

-1: first string is smaller(smaller Ascii or comes first in alphabet)
0: both Strings are equal
+1: First string is larger(greater ascii or comes after in alphabet)

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

Explain why the outputs will be different:

str1.equals(str2);
str1==str2;

A

.equals() compares the strings whereas ‘==’ compares the reference of strings.

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

3 points

Why are Java Strings immutable?

A
  1. Saves a lot of heap space
  2. if modifiable, it won’t be secure because a hacker can modify reference value and cause security issues.
  3. String is safe for multithreading because it is immutable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How is StringBuffer created?

A

StringBuffer sb = new StringBuffer();
StringBuffer sb = new StringBuffer(int size);
StringBuffer sb = new StringBuffer(“String”);

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

Name any 5 StringBuffer methods.

A
  1. append(): adds element
  2. length(): returns length of sb
  3. delete(beginIndex,endIndex);
  4. insert(startIndex, ‘char’/”string”);
  5. reverse();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

think of advantages, disadv. and when to use

3 differences between StringBuffer and StringBuilder class?

A
  1. StringBuilder is not synchronized, thus not thread safe
  2. Its adv. over StringBuffer is faster performance
  3. When using multiThreading, StringBuffer should be used.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly