Chapter 4 - Core APIs Flashcards

(49 cards)

1
Q

List down core methods of String

A

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

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

Checking for empty or blank strings

A

boolean isEmpty()
boolean isBlank()

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

Formatting values

A

static String format(String format, Object… args)
static String format(Locale loc, String format, Object… args)
String formatted(Object… args)

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

Common formatting symbols

A

%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

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

var str=“Food: %d tons”.formatted(2.0);
print(str);

A

compiles but throws exception

Since we are passing double value in place of integer. System throws IlegalFormateConversionException

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

var pi=3.14159265359;
print(“%f”,pi);
“%12.8f”, pi
“%012f”,pi
“%12.2f”,pi
“%.3f”,pi

A

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

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

Creating a StringBuilder

A

new StringBuilder();
new StringBuilder(“animal”);
new StringBuilder(12);

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

StringBuilder methods

A

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

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

StringBuilder methods

A

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()

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

What is the output?
var sb=new StringBuilder (“Venkatesh”);
sb.delete(1,16);
print(sb);

A

V

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

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

A

B

It first does a logical delete from begin to end and replaces with whatever the string passed at begin position

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

What is the output
var x=“hello world“;
var y=“ hello world “.trim();
print(x==y);

A

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

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

String intern()

This adds the string to the string pool

A

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

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

String pool

A

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

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

Various ways to declare an int array

A

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

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

Common array methods

A

boolean equals(Array arr)
Arrays.toString(Array)
Arrays.sort(arr) -» use 7Up order

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

Array length vs length()

A

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

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

Arrays.binarySearch(array, target)

A

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

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

Arrays.equals(array1, array2)

A

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

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

int Arrays.compare(arr1, arr2)

A

-> 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

21
Q

Output?

Arrays.compare (new int[]{1}, new String(“Venky”)):

A

Doesn’t compile

Both parameters should be of same type

22
Q

Arrays.mismatch (arr1,arr2)

A

Returns -1 if they are exactly equal

Returns index of first differing value

23
Q

Is this valid?

int[][] diff={{1,2}, {4}, {6,1,9}};

A

It’s valid the second and third dimension can be varied across first dimension

24
Q

Is this valid?

int [][] args= new int[2][];

A

Yes
You can initialize second dimension later

args[0]=new int[5];

Now args[1] denotes null if uninitialized

25
Math APIs
double min(double a, double b) float min(float a, float b) int min(int a, int b) long min(long a, long b) max() - similar to min but higher num long round(double num) long round(float num) double ceil(double d) double floor(double d) double pow(double d1, double d2) double random() -> 0<=a<1
26
BigInteger
You can pass a long You can chain methods like add, divide,max You use this to handle larger integers that dont fit in regular integer and long
27
BigDecimal
Can take either long or double as parameter when declaring Used for larger values that don’t fit in float or double. It’s used for currencies as well to preserve the cents calculation
28
LocalDate LocalTime LocalDateTime ZonedDateTime
LocalDate: Contains just date - no time and no time zone LocalTime: contains just the time- no date no timezone LocalDateTime: contains date, time but no timezone ZonedDateTime: contains date, time, and timezone Static methods: now()
29
Example of date and timezone
LocalDate of(int year, int month, int day) LocalDate of(int year, Month month, int day) LocalTime of(int hour, int minute, int second, int nanos) Note: seconds and nanos are optional LocalDateTime of(int year, int month, int date, int hour, int minute) LocalDateTime of(LocalDate d, LocalTime t) Note: secs and nanos optional ZonedDateTime of(LocalDate, LocalTime, ZoneId) ZonedDateTime of(LocalDateTime ldt, ZoneId zone) ZonedDateTime of(int year, int month, int date, int hour, int minute, int second, int nanos, ZoneId zone)
30
Output? var d= new LocalDate(12, 24, 12); print(d)
Doesn’t. Compile Date and Time classes don’t have public constructors. They use factory pattern. They have static methods of() to create objects Also note that ZonedDateTime doesn’t have overloaded method that takes Month enum
31
Are date time classes immutable
Yes Remember to assign the return values to its original reference or a new reference to store the new manipulated value
32
Manipulation of dates
plusDays(int days) plusWeeks(int weeks) plusMonths(int months) plusYears(int years) minusDays minusHours minusSeconds
33
Leap year
Leap years are years that are multiple of 4 or 400, but not other multiples of 100
34
There are methods to convert from one type to another. Date to Time vice versa
LocalDateTime LocalDate.atTime(int h, int m) Note: secs, nanos optional LocalDateTime LocalDate.atStartOfDay() LocalDate LocalTime.atDate(LocalDate l) ZonedDateTime LocalDateTime.atZone(ZoneId z)
35
Period class Used for duration between dates and performed on dates
Period.ofMonths(2) Period.ofYears(1) Period.ofWeeks(3) Period.ofDays(20) Period.of(int year, int month, int days)
36
Period using between() method
Period.between(LocalDate l1, LocalDate l2) Think of like l2 - l1
37
Output? var x=Period.ofYears(1).ofWeeks(1); A) doesn’t compile B) 1 year C) 1 week D) 1 year and 1 week
And: C You can’t chain period methods to achieve 1 year and 1 week. These are static methods. So the last method return value is stored in x
38
Additional period rules var p=Period.ofMonths(-1); var t=LocalTime.of(10,2,34); t.plus(p);
Compiles but exception thrown You can’t pass a period of months to a time. Incompatible data types
39
Duration class Used for duration between times
Duration.ofDays(1) Duration.ofHours(1) Duration.ofMinutes(1) Duration.ofSeconds(10) Duration.ofMillis(23) Duration.ofNanos(45) Duration.of(1, ChronoUnit.DAYS) Duration.
40
Duration class using ChronoUnit which has a TemporalUnit members
Duration.of(1, ChronoUnit.DAYS) Duration.of(1, ChronoUnit.HOURS) Duration.of(1, ChronoUnit.MINUTES) Duration.of(10, ChronoUnit.SECONDS) Duration.of(1, ChronoUnit.MILLIS) Duration.of(1, ChronoUnit.NANOS)
41
ChronoUnit for difference
It takes 2 arguments of same data type such as LocalDate, LocalTime and so on ChronoUnit.HOURS.between(one,two) ChronoUnit.MINUTES.between(one,two)
42
Output? var time=LocalTime.of(3,12,34); var truncated = time.truncated(ChronoUnit.MINUTES); print(truncated);
03:12
43
Can you add Duration of hours to a date?
No UnsupportedTemporalTypeException
44
Can you add Duration of hours to a LocalDateTime variable?
Yes
45
Period vs Duration
Period is to be used on Date objects such as LocalDate, LocalDateTime, ZonedDateTime Duration is to be used in time objects such as LocalTime, LocalDateTime, ZonedDateTime
46
Instant class
Instant is a specific moment in time in GMT time zone var now=Instant.now(); var duration=Duration.between(now, later); toInstant() works on ZonedDateTime to convert the local zone time to GMT
47
Daylight Savings
1:59am is the turning point Spring forward in the spring and fall back in the fall
48
Is this valid? int[][] x=new int[5][0]; int[][] y=new int[5][];
Both valid
49
Output? var x=“”; x+=“abc”; var y=“abc”; print(x==y);
false Though x seems to be a compile time constant but its built with operation on 2 separate lines If var x = “”+”abc”; This would have been equal reference in string pool since its constant while declaring