Strings Flashcards
String basics and String methods
‘new’ keywords stores objects in which memory type?
heap memory
in which memory are literals stored?
pool memory
What are the 2 ways to create a String?
String str = new String(“Java”)
String str = (“Java”)
Method to check length of String?
int l = str.length()
Method to find character at specified index?
int s = str.charAt(5)
Method to search a character in the String from left to right and right to left?
str.indexOf(“k”, starting index), str.lastIndexOf(“J”,starting index)
What are the return types of compareTo method?
-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)
Explain why the outputs will be different:
str1.equals(str2);
str1==str2;
.equals() compares the strings whereas ‘==’ compares the reference of strings.
3 points
Why are Java Strings immutable?
- Saves a lot of heap space
- if modifiable, it won’t be secure because a hacker can modify reference value and cause security issues.
- String is safe for multithreading because it is immutable.
How is StringBuffer created?
StringBuffer sb = new StringBuffer();
StringBuffer sb = new StringBuffer(int size);
StringBuffer sb = new StringBuffer(“String”);
Name any 5 StringBuffer methods.
- append(): adds element
- length(): returns length of sb
- delete(beginIndex,endIndex);
- insert(startIndex, ‘char’/”string”);
- reverse();
think of advantages, disadv. and when to use
3 differences between StringBuffer and StringBuilder class?
- StringBuilder is not synchronized, thus not thread safe
- Its adv. over StringBuffer is faster performance
- When using multiThreading, StringBuffer should be used.