List down core methods of String
int length()
char charAt(int index)
int codePointAt(int index)
int codePointBefore(int index)
int codePointCount(int start, int end)
String substring(int index)
String substring(int start, int end)
int indexOf(int ch)
int indexOf(int ch, int begin)
int indexOf(int ch, int begin, int end)
int indexOf(String str)
int indexOf(String str, int begin)
int indexOf(String str, int begin, int end)
String toLowerCase()
String toUpperCase()
boolean equals(Object o)
boolean equalsIgnore(String str)
boolean startsWith(String pfx)
boolean startsWith(String pfx, int begin)
boolean endsWith(String sfx)
boolean contains(CharSequence cseq)
String replace(char old, char new)
String replace(CharSequence old, CharSequence new)
String trim()
String strip()
String stripLeading()
String stripTrailing()
String indent(int noofspaces)
String stripIndent(int noofspaces)
Indent methods adds the same number of blank spaces to the beginning of each line if you pass a positive number but if you pass negative number it will remove those many spaces. If the negative number is larger than available spaces it removes only the available spaces. If you pass 0, it will do nothing and returns original
Indent normalizes white space characters . It will add \n at the end, if there is \r\n it will normalize it to \n
stripIndent removes all incidental white space. It doesn’t add \n at the end
Note: strip() does everything trim() does but it supports Unicode
Checking for empty or blank strings
boolean isEmpty()
boolean isBlank()
Formatting values
static String format(String format, Object… args)
static String format(Locale loc, String format, Object… args)
String formatted(Object… args)
Common formatting symbols
%s -> any type commonly strings
%d -> applies to integer values like int, long
%f -> applies to floating values, flow and double
%n -> inserts a line break
var str=“Food: %d tons”.formatted(2.0);
print(str);
compiles but throws exception
Since we are passing double value in place of integer. System throws IlegalFormateConversionException
var pi=3.14159265359;
print(“%f”,pi);
“%12.8f”, pi
“%012f”,pi
“%12.2f”,pi
“%.3f”,pi
By default floating point displays 6 digits after the decimal
Here b means 1 space
3.141593
bb3.14159265
00003.141593
bbbbbbbb3.14
3.142
Creating a StringBuilder
new StringBuilder();
new StringBuilder(“animal”);
new StringBuilder(12);
StringBuilder methods
String substring(int begin, int end)
int length()
char charAt(int index)
StringBuilder append(String)
StringBuilder insert(int offset, String str)
StringBuilder delete(int begin, int end)
StringBuilder deleteCharAt(int index)
In delete() method if you specify end index larger than the length, Java will assume it’s the end of the string
StringBuilder methods
String substring(int begin, int end)
int length()
Char charAt(int index)
StringBuilder append(String str)
StringBuilder appendCodePoint(int idx)
StringBuilder insert(int idx, String str)
StringBuilder delete(int begin, int end)
StringBuilder deleteCharAt(int idx)
StringBuilder replace(int begin, int end, String str);
StringBuilder reverse()
What is the output?
var sb=new StringBuilder (“Venkatesh”);
sb.delete(1,16);
print(sb);
V
StringBuilder replace method
var sb=new StringBuilder(“Venkatesh “);
sb.replace(2,6,”AMU”);
A) doesn’t compile
B) VeAMUesh
C) VeAMUtesh
D) throws runtime exception
B
It first does a logical delete from begin to end and replaces with whatever the string passed at begin position
What is the output
var x=“hello world“;
var y=“ hello world “.trim();
print(x==y);
False
JVM creates string pool with literals used at compile time. Here y is evaluated to be same as x at run time they both refers to two different objects
String intern()
This adds the string to the string pool
This method makes sure you create an object from string pool
var name=“Hello World”
var name2=new String(“Hello World”).intern()
print(name==name2);
True
String pool
JVM creates string pool with compile time constants of class files
var x= “rat” + 1;
var x= “r”+”a”+”t”+1;
Both above points to the same object in string pool
var y=“rat”+new String(“1”);
This would point to a completely different object and not from a string pool
Various ways to declare an int array
new int[3]
new int[]{1,2,3}
{1,2,3}
int[] ids,types —> both arrays
int ids[], types —> ids array and type single integer
Common array methods
boolean equals(Array arr)
Arrays.toString(Array)
Arrays.sort(arr) -» use 7Up order
Array length vs length()
Array object has inherent variable called length that gives you no of occurrences
int x=new int[4];
print(x.length) —> gives 4
print(x.length()); -» doesn’t compile
Arrays.binarySearch(array, target)
If found it will return index
If not found it will return 1 smaller than the negative value if the index where a match needs to be inserted to preserve the order
If applied on unsorted array it will return an unpredictable output
Arrays.equals(array1, array2)
It compares if the 2 arrays are equal in size and the elements match
When comparing primitive values it uses == and equals() for object references
int Arrays.compare(arr1, arr2)
-> a negative number means the first array is smaller than second
-> a zero means the arrays are equal
-> a positive number means that first array is larger than second array
Think of like arr1 - arr2
Note: null is smaller than any other value
Output?
Arrays.compare (new int[]{1}, new String(“Venky”)):
Doesn’t compile
Both parameters should be of same type
Arrays.mismatch (arr1,arr2)
Returns -1 if they are exactly equal
Returns index of first differing value
Is this valid?
int[][] diff={{1,2}, {4}, {6,1,9}};
It’s valid the second and third dimension can be varied across first dimension
Is this valid?
int [][] args= new int[2][];
Yes
You can initialize second dimension later
args[0]=new int[5];
Now args[1] denotes null if uninitialized