-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjava_basic_questions
623 lines (457 loc) · 28 KB
/
java_basic_questions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
Java Platform
1 What is bytecode?
bytecode is set of instructions for JVM
2 Compare JDK vs JVM vs JRE
JDK=JRE+JVM
JRE=JVM+libs
JVM=interpretor, execute code, request classloader to load files
3. What is the role for a classloader in Java?
classloader loads class files dynamically to the JVM during runtime
4. ClassNotFoundException vs NoClassDefError
ClassNotFoundException is a checked exception. This happens when we load classes using Class.forname
NoClassDefError is an error, The lib was avaiable during compile time but is missing during runtime
Strings
5 . Where are String values stored in memory?
string is stored in heap memory
string.intern will store its reference in pool
Until Java 8, Strings were internally represented as an array of characters – char[], encoded in UTF-16, so that every character uses two bytes of memory.
With Java 9 a new representation is provided, called Compact Strings. This new format will choose the appropriate encoding between char[] and byte[] depending on the
stored content. Since the new String representation will use the UTF-16 encoding only when necessary, the amount of heap memory will be significantly lower,
which in turn causes less Garbage Collector overhead on the JVM.
6 . What are the important things to consider when implementing equals method?
reflexive: an object must equal itself
symmetric: x.equals(y) must return the same result as y.equals(x)
transitive: if x.equals(y) and y.equals(z), then also x.equals(z)
consistent: the value of equals() should change only if a property that is contained in equals() changes (no randomness allowed)
equals and hashcode contract
equals consistency: objects that are equal to each other must return the same hashCode
collisions: unequal objects may have the same hashCode
7 . What is the Hashcode method used for in Java?
used in hashing function by HashMap
8 . What is method overloading?
Two methods will be treated as overloaded if both follow the mandatory rules below:
Both must have the same method name.
Both must have different argument lists.
And if both methods follow the above mandatory rules, then they may or may not:
Have different return types.
Have different access modifiers.
Throw different checked or unchecked exceptions.
9 . What is method overriding?
It must have the same method name.
It must have the same arguments.
It must have the same return type. From Java 5 onward, the return type can also be a subclass (subclasses are a covariant type to their parents).
It must not have a more restrictive access modifier (if parent --> protected then child --> private is not allowed).
It must not throw new or broader checked exceptions.
And if both overriding methods follow the above mandatory rules, then they:
May have a less restrictive access modifier (if parent --> protected then child --> public is allowed).
May throw fewer or narrower checked exceptions or any unchecked exception.
Apart from the above rules, there are also some facts to keep in mind:
Only inherited methods can be overridden. That means methods can be overridden only in child classes.
Constructors and private methods are not inherited, so they cannot be overridden.
Abstract methods must be overridden by the first concrete (non-abstract) subclass.
final methods cannot be overridden.
A subclass can use super.overridden_method() to call the superclass version of an overridden method.
10 . What is an abstract class? declare class as abstract , declare one of the method as abstract which will force you to make class abstract
11 . When do you use an abstract class?
when we want to add all the common behaviour in a class and want to reuse the features in sub classes.
12 . Compare abstract class vs interface?
Collection is an Interface
AbstractCollection is an abstract class
Cloneable is interface
Serialiazable is an interface
13 . Can a constructor be called directly from a method? No, constuctor can only be called with new operator
14 . Is a super class constructor called even when there is no explicit call from a sub class constructor? yes
15 . What is the use of a final modifier on a class? restrict class extension
16 . What is the use of a final modifier on a method? restrict method overriding
17 . What happens when a variable is marked as volatile?
it increases the visibility of the shared object among the threads. The object is marked to be not copied to local memory of each thread.
Instead it is stored in heap to be shared among the threads.
18 . Should default be the last case in a switch statement? not necessary
19 . Can a switch statement be used around a String yes
Exception handling
20 . What design pattern is used to implement exception handling features in most languages? chain of responsibiltiy pattern
21 . What is the need for finally block? The finally block in java is used to put important codes such as clean up code
e.g. closing the file or closing the connection
22 . In what scenarios is code in finally not executed? system.exit or system failure like out of memory
23 . Is try without a catch is allowed? yes but try needs to be closed either with catch or finally
24 . Can you explain the hierarchy of exception handling classes?
Throwable -> Error
-> Exception -> Checked Exception
-> Unchecked Exception -> Runtime exception
25 . What is the difference between error and exception?
An Error "indicates serious problems that a reasonable application should not try to catch."
An Exception "indicates conditions that a reasonable application might want to catch."
26 . What is the difference between error and unchecked/runtime exceptions?
IOException is a checked exception. When trying to get contents of a file, you have to keep in mind that the disk drive can suddenly fail,
or the file can't be found, or something else. You have to be prepared to deal with this situation.
For instance, you can catch the exception, tell the user that the file isn't accessible, and try again later.
IllegalArgumentException is an unchecked exception. The programmer messed up: They called a method, but passed illegal arguments.
The program crashes, and nothing can be done until the programmer fixes his mistake.
OutOfMemoryError means our world collapsed. Maybe the programmer did something stupid, or maybe the application just needs a lot of resources.
Either way, how are you going to recover when the application has run out of memory?
27 . Can you explain about try with resources?
The try-with-resources statement is a try statement that declares one or more resources.
A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end
of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Miscellaneous topics
28 Garbage Collection , Memory Model
Heap, Non-Heap, and Cache
Heap – Young Generation (Eden, Survivor 0, and Survivor 1) and Old Generation
Young Generation (Eden, Survivor 0, and Survivor 1)
• This is reserved for containing newly allocated objects
• Most of the newly created objects goes Eden space.
• When Eden space is filled with objects, Minor GC (a.k.a. Young Collection) is performed and all the survivor objects are moved to one of the survivor spaces.
• Minor GC also checks the survivor objects and moves them to the other survivor space. So, at a time, one of the survivor spaces is always empty.
• Objects that are survived after many cycles of GC, are moved to the Old generation memory space. Usually, it’s done by setting a threshold for the age of
the young generation objects before they become eligible to promote to the Old generation.
Old Generation
This is reserved for containing long-lived objects that could survive after many rounds of Minor GC
When Old Gen space is full, Major GC (a.k.a. Old Collection) is performed (usually takes longer time)
Non-Heap Memory
This includes Permanent Generation (Replaced by Metaspace since Java 8)
Perm Gen stores per-class structures such as runtime constant pool, field and method data, and the code for methods and constructors, as well as interned Strings
Its size can be changed using -XX:PermSize and -XX:MaxPermSize
• Metaspace — Since Java 8, Permanent Generation is replaced by Metaspace.
It can auto increase its size (up to what the underlying OS provides) even though Perm Gen always has a fixed maximum size.
If the class loader is alive, the metadata remains alive in the Metaspace and can’t be freed.
Cache Memory
This includes Code Cache
Stores compiled code (i.e. native code) generated by JIT compiler, JVM internal structures, loaded profiler agent code, and data, etc.
When Code Cache exceeds a threshold, it gets flushed (and objects are not relocated by the GC).
Stack
Java Stack memory is used for the execution of a thread and it contains method-specific values and references to other objects in Heap.
29 . What is serialization?
Serialization is the conversion of the state of an object into a byte stream; deserialization does the opposite.
if class is not serializable, we will get NotSerializableException
30 . How do you serialize an object using serializable interface?
FileOutputStream and ObjectOutputStream to writeObject to file
FileInputStream and ObjectInputStream to readObject from file
31 . What do you do if only parts of the object have to be serialized?
use transient
It is useful for fields that do not represent the state of the object
We use it for any non-serializable references
32 . How do you serialize a hierarchy of objects?
all the sub classes will be serializable
in case of composition or any object used in the serializable class is not serializable , we will get NotSerializableException
33 if you use different version of serialVersionUID to write and read object, you will get java.io.InvalidClassException
34 . Are the constructors in an object invoked when it is de-serialized? no
35 . Are the values of static variables stored when an object is serialized?
The values of static variables will not be preserved during the de-serialization process.
In-fact static variables are also not serialized but since these belongs to the class. After de-serialization they get their current values from the class.
Collections
36. What are the important interfaces in the collection hierarchy?
Set, List, Queue
37. Can you explain briefly about the List interface?
Ordered
can have duplicates
can have null
38 . How do you sort elements in an ArrayList using comparable interface?
implement class with Comparable interface and override compareTo method and Collections.sort(list)
39 . How do you sort elements in an ArrayList using comparator interface?
Collection.sort(list, Comparator.comparing(Class::getField).thenComparing(Class::getField))
Comparator vs Comparable
use comparable to compare object with itself and we have only one option of comparison
where as comparator can be use to compare object based on different set of properties of the object
40. Can you explain briefly about the Set interface?
LinkedHashSet Ordered
HashSet UnOrdered, TreeSet Sorted, does not maintain order of insertion
can not have duplicates
can have only one null object
41 . Can you give examples of implementations of navigableSet? TreeSet and ConcurrentSkipListSet
42 Explain briefly about Queue interface?
Ordered List, First in First out , implementation is LinkedList and PriorityQueue
43 . Explain the BlockingQueue interface?
The Java BlockingQueue interface represents a queue that can block
- threads inserting elements into the queue if the BlockingQueue is full,
- or thread removing elements from the queue if the BlockingQueue is empty.
A BlockingQueue is typically used to have one thread produce objects, which another thread consumes.
The producing thread will keep producing new objects and insert them into the BlockingQueue, until the queue reaches some upper bound on what it can contain.
It's a limit, in other words. If the blocking queue reaches its upper limit, the producing thread is blocked while trying to insert the new object.
It remains blocked until a consuming thread takes an object out of the queue.
The consuming thread keeps taking objects out of the BlockingQueue to processes them. If the consuming thread tries to take an object out of an empty queue,
the consuming thread is blocked until a producing thread puts an object into the queue.
http://tutorials.jenkov.com/java-util-concurrent/blockingqueue.html
ArrayBlockingQueue
DelayQueue
LinkedBlockingQueue
LinkedBlockingDeque
LinkedTransferQueue
PriorityBlockingQueue
44 . What is a priorityQueue?
The PriorityBlockingQueue class implements the BlockingQueue interface.
The PriorityBlockingQueue is an unbounded concurrent queue. It uses the same ordering rules as the java.util.PriorityQueue class.
You cannot insert null into this queue. All elements inserted into the PriorityBlockingQueue must implement the java.lang.Comparable interface.
The elements thus order themselves according to whatever priority you decide in your Comparable implementation.
Notice that the PriorityBlockingQueue does not enforce any specific behaviour for elements that have equal priority (compare() == 0).
Also notice, that in case you obtain an Iterator from a PriorityBlockingQueue, the Iterator does not guarantee to iterate the elements in priority order.
45. Can you briefly explain about the Map interface?
HashMap
unordered
can have one null key
LinkedHashMap
ordered
can have one null key
TreeMap
unordered
sorted by key
46. How hashmap works?
hashmap has an initial capacity of 16 and a loadfactor of 75%. when it reaches the loadfactor, it resize the hashmap by double and does the rehashing
HashMap depends on the hashing function to store an object in the bucket. hashing function gets the hashcode of the key and determines the index of the bucket
and then store the object if it identifies that there are more then 1 object at an index, which is also called collision,
it creates a linked list to store the object.
With java 8 and above, after a certain threshold limit, it creates a balanced binary tree when collision occurs.
47. How hashset works?
hashset uses hashmap internally to store the objects.
the value of hashset is used as key of hashmap and PRESENT (an object constant) is added as a value of the hashmap.
Advanced collections
48. Unmodifiable Collections
Read-only view
source changes are available
get UnsupportedOperation exception, if modified
49. Immutable Collections
Read-only copy of the source e.g. List.of
Source changes are not available
get UnsupportedOperation exception, if modified
Null values are not allowed in List.of, List.copyOf
List.of takes collections of elements where List.copyOf takes Collection
50 . What is the difference between synchronized and concurrent collections in Java?
Though both Synchronized and Concurrent Collection classes provide thread-safety, the differences between them come in performance, scalability,
and how they achieve thread-safety. Synchronized collections like synchronized HashMap, Hashtable, HashSet, Vector,
and synchronized ArrayList are much slower than their concurrent counterparts like ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteHashSet.
The main reason for this slowness is locking; synchronized collections lock the whole collection
e.g. whole Map or List while concurrent collection never locks the whole Map or List.
Synchronized Collections
Returns synchronized collections, basically all the operations are implemented under synchronized block
CopyOnWriteArrayList
Use to synchronize the collection
Create a copy of the collection when add or set operation is performed
Iterator is fail-safe, gets an immutable collection
Best if used only for a read operation
ConcurrentHashMap
Use to synchronize map
Segment/bucket-wise locking, the segment is calculated based on the same hashing function which is used to store objects.
In the Put and remove method, it identifies the segment using hashing function and then put a lock on the segment
In the get method, there is no lock
The default segment size is 16
51. What is compareandswap approach?
Compare and swap is a technique used when designing concurrent algorithms.
The approach is to compare the actual value of the variable to the expected value of the variable and if the actual value matches the expected value,
then swap the actual value of the variable for the new value passed in.
private boolean locked = false;
public synchronized boolean lock() {
if(!locked) {
locked = true;
return true;
}
return false;
}
Atomic Operation
After Java 5, we don’t have to implement or write a synchronized block with the check and act code anymore,
Java 5 offers this support via java.util.concurrent.atomic: a toolkit of classes used for lock-free, thread-safe programming on single variables.
AtomicBoolean makes sure that only one thread can read it at a time.
public static class MyLock {
private AtomicBoolean locked = new AtomicBoolean(false);
public boolean lock() {
return locked.compareAndSet(false, true);
}
}
public static class MyLock {
private AtomicBoolean locked = new AtomicBoolean(false);
public boolean lock() {
return locked.compareAndSet(false, true);
}
}
AtomicInteger: This variable lets you update an int value atomically.
AtomicLong: Long with thread-safe “Compare and Swap” functionality.
AtomicReference: This variable provides an object reference variable which can be read and written atomically.
AtomicIntegerArray, AtomicLongArray, and AtomicReferenceArray
52 . What is a lock? How is it different from using synchronized approach?
53 . What is difference between fail-safe and fail-fast iterators?
Fail-fast Iteration - Fails on concurrent modification
Fail-safe - Example ConcurrentSkiptList, it is a snapshot of the collection at the time of calling
Weekly consistent - Never throw concurrent modification, however, doesn’t guarantee if all the elements will be returned if concurrent modification happens.
54. object level lock vs class level lock
object level lock is used for non-static data and methods
class level lock is used for static data and methods
55. can object used for synchronized block lead to nullpointer exception
Java synchronization will throw NullPointerException if object used in synchronized block is null. For example, in above code sample if lock is initialized as null,
the “synchronized (lock)” will throw NullPointerException.
56. What are the different states of a thread?
new running runnable blocked/waiting terminated
57. Explain different ways of creating executor services .
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
58. How do you check whether an executionservice task executed successfully?
we can get a completable future and then we can check isDone
59. What is callable? How do you execute a callable from executionservice?
callable returns future object where as runnable does not return anything
Future future = executorservice.submit(callable);
60. Can a static method be synchronized?
yes, example singleton class
61. What is the use of join method in threads?
join will wait for the thread to complete
62 . What is a deadlock?
Resource A and resource B are used by process X and process Y
X starts to use A.
X and Y try to start using B
Y 'wins' and gets B first
now Y needs to use A
A is locked by X, which is waiting for Y
63 . What are the important methods in Java for inter-thread communication?
wait(), notify(), notifyAll join
64. ThreadLocal
local copy of the object for a particualr thread
basically its an implementation of Map which stores thread id and object
65. Reentrant lock
it has same basic behaviour has sychronized block but with extra flexibility.
lock can be unlock at different scope
use Condition condition = lock.newCondition() to
equivalent to wait() -> condition.await()
equivalent to notify() -> condition.signal()
we can define fairness policy, reentrant lock has a constructor which access boolean flag.
with fairness policy true, locks favor granting access to the longest waiting thread otherwise lock does not gaurantee any particulatar access order
ReentrantReadWriteLock
we can have readLock and writeLock
only one thread can go inside writeLock
multiple threads can go into read lock
if atleast one thread has acquired a read lock then no other thread can go into write lock
in other words, either Readlock is being used by n threads or writelock is being used by 1 thread but never both at the same time
newCondition is allowed only on write lock
66. Types of ThreadPool
FixedThreadPool
initial size = constuctor arg
maxpoolsize = corepoolsize
LinkedBlockingQueue
cpu intensive task - ideal pool size - cpu core count
allocate fixed thread pool based on Runtime.getRuntime().availableProcessors() to maximize utilization of cpu.
IO intensive task - ideal pool size - High
Task like DB, http or file access wait for the OS to get the response, in these case we can have large size of the pool
CachedThreadPool - synchronous queue
create thread pool in runtime. increase and decrease pool size .
initial size = 0
maxpoolsize = Int.maxvalue
Synchronous queue
ScheduleThreadPool
schedule after certain delay - schedule to tun after 10 seconds delay
scheduleAtFixedRate - schedule to run repeatedly every 10 seconds
sceduleAtFixedDelay - complete the task and wait for fixed delay to execute again
initial size = constuctor arg
maxpoolsize = Int.maxvalue
DelayedWorkQueue
SingleThreadExecutor - pool size of 1 - used when we have to execute task in particular order
initial size = 1
maxpoolsize = 1
LinkedBlockingQueue
67 - Rejection Policy
AbortPolicy - submitting new tasks throws RejectedExecutionException
DiscardPolicy - submitting new tasks silently discards it
DiscardOldestPolicy - submitting new tasks drop existing oldest task and new task is added to the queue
CallerRunsPolicy - submitting new task will execute the task on the called thread itself
68. Lifecycle
service.shutdown - any task submitted after this will throw an exception
service.isShutdown - check if the shutdown has began
service.isTerminate - will return true if all tasks are compeleted
service.awaitTermination - block until all tasks are completed or if timeout occurs
service.shutdownnow - will intiate shutdown and return all queued task
69. CountDownLatch
UseCase -> consolidate data from multiple sources to single file
1) main thread starts n threads with countdown latch new CountDownLatch(3)
2) main thread waits for number of counts to be finished to continue running rest of the code -> latch.await()
3) called thread brings the count down -> latch.countdown()
latch.await() -> waits for all the threads to complete to open the latch
latch.countdown() -> brings the count down, flag that indicates the task is completed and brings the count down
with each latch.countdown(), the counter is decremented, once the counter is 0, it can not be initialized back to original value.
70. CyclicBarrier
UseCase -> to run set of tasks together multiple time. with this, the threads wait for each other to complete to execute rest of the code
1) main thread starts n threads with a barrier involving n parties -> new CyclicBarrier(3)
2) participating thread waits for the other threads to complete -> barrier.await()
cyclicbarrier can be run in loop as count of parties will be reset to original value after all the participating threads reaches the await stage.
- Latch has a countDown() and await() methods. When countDown() is invoked n times, all the awaiting threads are notified.
Cyclic barrier similarity has await() method, which when invoked by n threads, all waiting threads are notified and optionally a Runnable() is also invoked
- The countDown() method can be invoked by one thread or multiple threads whereas in case of CB n threads need to await() before it notifies all
- CB can be reset, but Latch is not resettable
- CB follows an all-or-none symantec. If a thread which is waiting for signal throws an exception then all the waiting threads will get a
BrokenBarrier exception or a InterruptedException
71. Java IO vs NIO
Basic concepts of NIO - channel, selector and buffer
- IO is blocking, NIO non-blocking
- IO is stream based, NIO is buffer based
- Streams can't be traversed back and forth, to support this, streams have to be cached in a buffer
- Streams are usually read-only or write-only. Channels are both read/write
- NIO uses buffers, but to determine if data is fully delivered we have to manually check its contents
- Because NIO is non-blocking the thread can request to get available data, and then continue with other NIO data
- NIO supports selectors, which means that a single thread can subscribe to multiple channels and multiplex available data
- Channels always read from buffer and write to buffer
Functional Programming - Lamdba expressions and Streams
72 . What is a stream?
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
- intermediate operations
These operations are used to pipeline other methods and to transform into the other streams.
They don't produce results because these operation does not invoke until the terminal operation gets executed.
- terminal operations
a terminal operation is always the last operation in a Stream pipeline.
73. What are lambda expressions?
Lamdas are expressions that are shorthand for anonymous inner classes & adapt to a functional interface
74. Functional interface?
A functional interface is an interface with one single abstract method (default methods do not count), no more, no less
Consumer – takes one argument returns nothing
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
List<String> names = Arrays.asList("John", "Freddy", "Samuel"); names.forEach(name -> System.out.println("Hello, " + name));
Supplier – takes nothing returns Object of type T
@FunctionalInterface
public interface Supplier<T> {
T get();
}
Supplier<String> supplier= ()-> "hello";
System.out.println(supplier.get());
UnaryOperator – takes T returns T
BinaryOperator – takes T, R returns T
Function – takes T, R returns R
Function<Integer,Double> functionSqrt = n -> Math.sqrt(n);
Predicate – takes T return Boolean
Predicate<Integer> predicate=new Predicate<Integer>() {
@Override
public boolean test(Integer i) {
return i > 100;
}
};
75. Immutable Class
Make all fields final
No setter methods
Inside getter methods, return a clone of the member variable
Implement cloneable, override clone method and throw CloneNotSupported if you want to throw custom exception
otherwise it is needed as we have not implemented class as cloneable. object class by default throws clonenotsupportedexception
Implement serializable, override readResolve method
To protect, reflection use enum
Wrapper classes are immutable
76. Optional Classes
The main purpose of Optional, as designed by its creators, is to be a return type of method that previously would return null.
Such methods would require us to write boilerplate code to check the return value, and we could sometimes forget to do a defensive check.
In Java 8, an Optional return type explicitly requires us to handle null or non-null wrapped values differently
77. What are the new features between Java 11 and 17?
records - equivalent to @Data of lombok
better visibilty on Nullpointer exception - for eg. in a chain of expression,
it will now point out at the exact expression which has thrown an error instead of a line number
TextBlock
instanceOf operator -
if(obj instanceOf String str){
// no need to cast now
system.out.println(str);
}
better handling of switch -
now return anytime, no break statement needed
stream.tolist
now, we do not need stream.collect(Collectors.toList)
sealed classes
public abstract sealed class FruitSealed permits AppleSealed, PearSealed {
}
public non-sealed class AppleSealed extends FruitSealed {
}
public final class PearSealed extends FruitSealed {
}