-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1367 lines (1019 loc) · 69 KB
/
Copy pathindex.html
File metadata and controls
1367 lines (1019 loc) · 69 KB
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<div class="light-theme-wrapper">
<style>
/* Light Theme Stylesheet */
.light-theme-wrapper {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
color: #24292f;
background-color: #f6f8fa;
padding: 24px;
line-height: 1.6;
}
.light-theme-wrapper h1,
.light-theme-wrapper h2,
.light-theme-wrapper h3,
.light-theme-wrapper h4 {
color: #0969da;
font-weight: 600;
margin-top: 24px;
margin-bottom: 16px;
border-bottom: 1px solid #d0d7de;
padding-bottom: 8px;
}
.light-theme-wrapper h1 {
font-size: 2.2em;
text-align: center;
color: #1f2328;
border-bottom: 3px solid #0969da;
padding-bottom: 15px;
margin-top: 0;
}
.light-theme-wrapper h3 {
border-bottom: none;
color: #0969da;
font-size: 1.35em;
margin-top: 20px;
}
.light-theme-wrapper h4 {
border-bottom: none;
color: #24292f;
font-size: 1.1em;
margin-top: 15px;
margin-bottom: 8px;
}
.light-theme-wrapper p {
margin-bottom: 16px;
}
/* Core Layout Cards */
.section-card {
background-color: #ffffff;
border: 1px solid #d0d7de;
border-radius: 8px;
padding: 24px;
margin-bottom: 32px;
box-shadow: 0 3px 10px rgba(0,0,0,0.03);
}
/* Code Block Formatting - GitHub Light Style */
.light-theme-wrapper pre {
background-color: #f6f8fa;
border: 1px solid #d0d7de;
border-radius: 6px;
padding: 16px;
overflow-x: auto;
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace;
font-size: 13.5px;
line-height: 1.5;
color: #24292f;
margin-bottom: 16px;
}
.light-theme-wrapper code {
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace;
background-color: rgba(175,184,193,0.2);
padding: 0.2em 0.4em;
border-radius: 6px;
font-size: 85%;
}
.light-theme-wrapper pre code {
background-color: transparent;
padding: 0;
border-radius: 0;
font-size: 100%;
}
/* Syntax Highlighting */
.keyword { color: #cf222e; font-weight: bold; }
.comment { color: #6e7781; font-style: italic; }
.string { color: #0a3069; }
.type { color: #953800; font-weight: bold; }
.annotation { color: #116329; }
/* Table Formatting */
.matrix-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 24px;
font-size: 14px;
}
.matrix-table th, .matrix-table td {
border: 1px solid #d0d7de;
padding: 10px 12px;
text-align: left;
}
.matrix-table th {
background-color: #f6f8fa;
color: #1f2328;
font-weight: 600;
}
.matrix-table tr:nth-child(even) {
background-color: #fafbfc;
}
/* Special Callout Boxes */
.analogy-box {
background-color: #fff8eb;
border-left: 4px solid #bf8700;
border-radius: 0 6px 6px 0;
padding: 16px;
margin: 16px 0;
}
.analogy-box h4 {
margin-top: 0;
color: #bf8700;
border: none;
padding-bottom: 0;
}
.microservice-box {
background-color: #ddf4ff;
border-left: 4px solid #0969da;
border-radius: 0 6px 6px 0;
padding: 16px;
margin: 16px 0;
}
.microservice-box h4 {
margin-top: 0;
color: #0550ae;
border: none;
padding-bottom: 0;
}
.fireside-chat {
background-color: #f0fbf0;
border-left: 4px solid #1a7f37;
border-radius: 0 6px 6px 0;
padding: 16px;
margin: 16px 0;
}
.fireside-chat h4 {
margin-top: 0;
color: #1a7f37;
border: none;
padding-bottom: 0;
}
.dumb-questions {
background-color: #f6f8fa;
border: 1px dashed #24292f;
border-radius: 6px;
padding: 16px;
margin: 16px 0;
}
.dumb-questions h4 {
margin-top: 0;
color: #24292f;
border: none;
padding-bottom: 0;
}
/* Diagrams */
.text-diagram {
font-family: ui-monospace, monospace;
white-space: pre;
background-color: #f6f8fa;
border: 1px dashed #d0d7de;
padding: 12px;
border-radius: 6px;
margin-bottom: 16px;
overflow-x: auto;
color: #57606a;
font-size: 13px;
}
/* Badges */
.badge {
display: inline-block;
padding: 2px 8px;
font-size: 11px;
font-weight: 500;
line-height: 18px;
border-radius: 2em;
background-color: #eff9ff;
color: #0550ae;
border: 1px solid #c2e0ff;
margin-left: 6px;
}
.badge-orange {
background-color: #fff8ec;
color: #9a6700;
border: 1px solid #f7e1ad;
}
</style>
<h1>☕ The Ultimate Java Interview Study Guide: Head First Edition</h1>
<p style="text-align: center; font-style: italic; color: #57606a; margin-bottom: 30px;">
Designed to accelerate technical prep from core foundations to production-grade, JVM-savvy backend engineering mastery.
</p>
<!-- SECTION 1: OOP CONCEPTS -->
<div class="section-card">
<h2>1. Object-Oriented Programming (OOP) Concepts</h2>
<p>Let's revisit the four pillars of OOP. Instead of academic hand-waving, let's look at the actual engineering patterns and real code behind them.</p>
<!-- Encapsulation -->
<h3>🔒 Encapsulation</h3>
<p><strong>The Idea:</strong> Setting up a protective boundary around an object's internal state. You restrict raw access to variables and force external actors to interact exclusively via public methods. This controls state invariants and safeguards consistency.</p>
<div class="microservice-box">
<h4>📡 Backend Microservice Example: Secure Config Management</h4>
<p>A class holding sensitive security tokens (such as SonarQube or Apiiro webhook secret keys). The raw token is <code>private</code> to prevent other runtime components from altering or reading it directly. Access is mediated by a getter that decrypts or logs usage dynamically.</p>
<pre><code><span class="keyword">public class</span> <span class="type">SecureConfigManager</span> {
<span class="keyword">private</span> <span class="type">String</span> decryptedToken;
<span class="keyword">private final</span> <span class="type">String</span> encryptedToken;
<span class="keyword">public</span> <span class="type">SecureConfigManager</span>(<span class="type">String</span> encryptedToken) {
<span class="keyword">this</span>.encryptedToken = encryptedToken;
}
<span class="comment">// Access is strictly controlled, audited, and lazy-loaded</span>
<span class="keyword">public synchronized</span> <span class="type">String</span> <span class="type">getDecryptedToken</span>(<span class="type">User</span> caller) {
<span class="keyword">if</span> (!caller.hasRole(<span class="string">"ADMIN"</span>)) {
<span class="keyword">throw new</span> <span class="type">SecurityException</span>(<span class="string">"Unauthorized state access!"</span>);
}
<span class="keyword">if</span> (<span class="keyword">this</span>.decryptedToken == <span class="keyword">null</span>) {
<span class="keyword">this</span>.decryptedToken = decrypt(<span class="keyword">this</span>.encryptedToken);
}
<span class="keyword">return this</span>.decryptedToken;
}
<span class="keyword">private</span> <span class="type">String</span> <span class="type">decrypt</span>(<span class="type">String</span> input) {
<span class="keyword">return</span> <span class="keyword">new</span> <span class="type">StringBuilder</span>(input).reverse().toString(); <span class="comment">// Dummy decryption logic</span>
}
}</code></pre>
</div>
<div class="analogy-box">
<h4>💡 Real-Life Analogy 1 (The TV Remote):</h4>
<p>You interact with the public interface—the <code>volumeUp()</code> button. The actual circuitry, resistors, and infrared transmitters (private properties) are safely hidden inside the plastic casing.</p>
</div>
<div class="analogy-box">
<h4>💡 Real-Life Analogy 2 (The ATM):</h4>
<p>You cannot reach into the physical vault and alter your balance (unencapsulated state). You request a withdrawal through a keypad interface (public API) which validates your PIN and balance before processing.</p>
</div>
<!-- Inheritance -->
<h3>🧬 Inheritance</h3>
<p><strong>The Idea:</strong> Designating an <em>IS-A</em> relationship to inherit common state variables and functionality from a parent class, facilitating code reuse and logical hierarchy.</p>
<div class="microservice-box">
<h4>📡 Backend Microservice Example: Authentication Provider Strategy</h4>
<p>An <code>AbstractAuthenticationProvider</code> class that establishes core identity verification mechanisms, audit logging, and MFA handshakes. Concrete subclasses like <code>OAuthProvider</code> and <code>SAMLProvider</code> inherit this common structure while implementing their respective protocol-specific logic.</p>
<pre><code><span class="keyword">public abstract class</span> <span class="type">AbstractAuthenticationProvider</span> {
<span class="keyword">protected final</span> <span class="type">String</span> providerId;
<span class="keyword">protected final</span> <span class="type">AuditLogger</span> auditLog;
<span class="keyword">protected</span> <span class="type">AbstractAuthenticationProvider</span>(<span class="type">String</span> providerId) {
<span class="keyword">this</span>.providerId = providerId;
<span class="keyword">this</span>.auditLog = <span class="keyword">new</span> <span class="type">AuditLogger</span>(providerId);
}
<span class="comment">// Inherited common identity verification utility</span>
<span class="keyword">public void</span> <span class="type">initializeAuditContext</span>(<span class="type">String</span> userId) {
auditLog.log(<span class="string">"Authentication attempt from user: "</span> + userId);
}
<span class="keyword">public abstract</span> <span class="type">AuthenticationToken</span> <span class="type">authenticate</span>(<span class="type">Credentials</span> creds);
}
<span class="keyword">public class</span> <span class="type">OAuthProvider</span> <span class="keyword">extends</span> <span class="type">AbstractAuthenticationProvider</span> {
<span class="keyword">public</span> <span class="type">OAuthProvider</span>() {
<span class="keyword">super</span>(<span class="string">"OAUTH2_OIDC"</span>);
}
<span class="annotation">@Override</span>
<span class="keyword">public</span> <span class="type">AuthenticationToken</span> <span class="type">authenticate</span>(<span class="type">Credentials</span> creds) {
initializeAuditContext(creds.getUsername()); <span class="comment">// Inherited</span>
<span class="type">String</span> accessToken = exchangeCodeForToken(creds.getOAuthCode());
<span class="keyword">return new</span> <span class="type">AuthenticationToken</span>(creds.getUsername(), accessToken);
}
<span class="keyword">private</span> <span class="type">String</span> <span class="type">exchangeCodeForToken</span>(<span class="type">String</span> code) {
<span class="comment">// OAuth2 token exchange logic</span>
<span class="keyword">return</span> <span class="string">"eyJhbGciOiJIUzI1NiIs..."</span>;
}
}</code></pre>
</div>
<div class="analogy-box">
<h4>💡 Real-Life Analogy 1 (Living Organisms):</h4>
<p>A <code>Dog</code> inherits generic metabolic and sleeping mechanisms from the <code>Mammal</code> superclass, but implements its own distinct behavior, <code>bark()</code>.</p>
</div>
<div class="analogy-box">
<h4>💡 Real-Life Analogy 2 (Electric Vehicles):</h4>
<p>An <code>ElectricCar</code> extends the core template of <code>Car</code> (inheriting steering, braking, and chassis), but replaces a gas-based fuel mechanism with high-density battery charging.</p>
</div>
<!-- Polymorphism -->
<h3>🎭 Polymorphism</h3>
<p><strong>The Idea:</strong> "Many forms." Allowing different underlying implementations to respond to the identical method invocation in their own unique way. Dynamic (runtime) polymorphism is achieved via method overriding.</p>
<div class="microservice-box">
<h4>📡 Backend Microservice Example: Multi-Factor Authentication Channels</h4>
<p>An interface named <code>MFAChannel</code> defines <code>sendChallenge(Identity user)</code>. Dynamic implementations exist for <code>EmailMFAChannel</code> and <code>SMSMFAChannel</code>. Your backend loops over a generic list of channels and sends verification codes without caring about the underlying transport layers.</p>
<pre><code><span class="keyword">public interface</span> <span class="type">MFAChannel</span> {
<span class="keyword">void</span> <span class="type">sendChallenge</span>(<span class="type">String</span> recipientId, <span class="type">String</span> verificationCode);
}
<span class="keyword">public class</span> <span class="type">EmailMFAChannel</span> <span class="keyword">implements</span> <span class="type">MFAChannel</span> {
<span class="annotation">@Override</span>
<span class="keyword">public void</span> <span class="type">sendChallenge</span>(<span class="type">String</span> recipientId, <span class="type">String</span> code) {
<span class="type">System</span>.out.println(<span class="string">"Sending email verification code to: "</span> + recipientId);
}
}
<span class="keyword">public class</span> <span class="type">SMSMFAChannel</span> <span class="keyword">implements</span> <span class="type">MFAChannel</span> {
<span class="annotation">@Override</span>
<span class="keyword">public void</span> <span class="type">sendChallenge</span>(<span class="type">String</span> recipientId, <span class="type">String</span> code) {
<span class="type">System</span>.out.println(<span class="string">"Sending SMS verification code to: "</span> + recipientId);
}
}</code></pre>
</div>
<div class="analogy-box">
<h4>💡 Real-Life Analogy 1 (The "Speak" Command):</h4>
<p>You command your pet to "Speak!". A dog responds by barking, whereas a cat responds by meowing. The execution depends entirely on the dynamic runtime type of the receiver.</p>
</div>
<div class="analogy-box">
<h4>💡 Real-Life Analogy 2 (USB-C Standard Port):</h4>
<p>One port interface interacts with chargers, audio devices, or ultra-fast storage drives. The computer transmits data via a standard protocol, while the connected hardware handles its distinct conversion task.</p>
</div>
<!-- Abstraction -->
<h3>🧱 Abstraction</h3>
<p><strong>The Idea:</strong> Hiding operational complexity and only showing the structural contract of "what" an object does rather than "how" it does it.</p>
<div class="microservice-box">
<h4>📡 Backend Microservice Example: Identity Token Management</h4>
<p>An <code>IdentityTokenManager</code> interface exposes a single method: <code>issueToken(User user)</code>. Under the hood, the implementing classes coordinate JWT claims generation, signature validation, token encryption, and revocation list checking.</p>
<pre><code><span class="keyword">public interface</span> <span class="type">IdentityTokenManager</span> {
<span class="type">String</span> <span class="type">issueToken</span>(<span class="type">User</span> user);
}
<span class="keyword">public class</span> <span class="type">JwtIdentityTokenManager</span> <span class="keyword">implements</span> <span class="type">IdentityTokenManager</span> {
<span class="annotation">@Override</span>
<span class="keyword">public</span> <span class="type">String</span> <span class="type">issueToken</span>(<span class="type">User</span> user) {
<span class="comment">// The complex JWT generation process is abstracted away from caller</span>
<span class="type">Claims</span> claims = buildSecurityClaims(user);
<span class="type">String</span> jwtToken = encodeAndSignToken(claims);
verifyTokenRevocation(user);
<span class="keyword">return</span> jwtToken;
}
<span class="keyword">private</span> <span class="type">Claims</span> <span class="type">buildSecurityClaims</span>(<span class="type">User</span> u) { <span class="comment">/* JWT claim construction */</span> }
<span class="keyword">private</span> <span class="type">String</span> <span class="type">encodeAndSignToken</span>(<span class="type">Claims</span> c) { <span class="comment">/* HMAC signature generation */</span> }
<span class="keyword">private void</span> <span class="type">verifyTokenRevocation</span>(<span class="type">User</span> u) { <span class="comment">/* Revocation list check */</span> }
}</code></pre>
</div>
<div class="analogy-box">
<h4>💡 Real-Life Analogy 1 (Operating a Car):</h4>
<p>To slow down, you step on the brake pedal. You don't manage master cylinders, hydraulic fluid pressures, or brake pads pinching rotors.</p>
</div>
<div class="analogy-box">
<h4>💡 Real-Life Analogy 2 (Espresso Machine):</h4>
<p>You press the "Double Shot" button (Abstract API). You do not manually adjust the boiler temperature, pump pressure, or water pre-infusion timings.</p>
</div>
</div>
<!-- SECTION 2: ACCESS & NON-ACCESS MODIFIERS -->
<div class="section-card">
<h2>2. Access and Non-Access Modifiers</h2>
<p>Modifiers control visibility and compile-time/runtime behaviors. Let's make sure you never mess up visibility in a code review again.</p>
<table class="matrix-table">
<thead>
<tr>
<th>Modifier</th>
<th>Same Class</th>
<th>Same Package</th>
<th>Subclass (Different Package)</th>
<th>World (Anywhere)</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>private</code></td>
<td>✅ Yes</td>
<td>❌ No</td>
<td>❌ No</td>
<td>❌ No</td>
</tr>
<tr>
<td><code>default</code> (No Keyword)</td>
<td>✅ Yes</td>
<td>✅ Yes</td>
<td>❌ No</td>
<td>❌ No</td>
</tr>
<tr>
<td><code>protected</code></td>
<td>✅ Yes</td>
<td>✅ Yes</td>
<td>✅ Yes</td>
<td>❌ No</td>
</tr>
<tr>
<td><code>public</code></td>
<td>✅ Yes</td>
<td>✅ Yes</td>
<td>✅ Yes</td>
<td>✅ Yes</td>
</tr>
</tbody>
</table>
<h3>🛡️ Top-Level vs. Member Modifier Constraints</h3>
<ul>
<li><strong>Top-Level Classes:</strong> Can only be declared as <code>public</code> or package-private/<code>default</code>. They <em>cannot</em> be declared as <code>private</code> or <code>protected</code> because a standalone class needs package-level context to exist cleanly.</li>
<li><strong>Member Elements:</strong> Methods, nested classes, and inner classes can utilize all 4 access level modifiers (`private`, `default`, `protected`, `public`) to restrict programmatic interactions.</li>
</ul>
<h3>🛠️ Non-Access Modifiers</h3>
<p>These modifiers alter the structural and execution behaviors of class definitions, methods, and variables.</p>
<h4>1. <code>static</code> <span class="badge">Class-Level Lifecycle</span></h4>
<p>Belongs directly to the Class template itself, rather than to instances. Memory is allocated once in the JVM **Metaspace** (formerly PermGen) during class loading.</p>
<pre><code><span class="keyword">public class</span> <span class="type">SecurityLogger</span> {
<span class="comment">// Shared by all instances of the class - thread safe if read-only</span>
<span class="keyword">private static final</span> <span class="type">Logger</span> logger = <span class="type">LoggerFactory</span>.getLogger(<span class="type">SecurityLogger</span>.class);
<span class="comment">// Helper static method. No class instance instantiation is needed to call it.</span>
<span class="keyword">public static boolean</span> <span class="type">isValidToken</span>(<span class="type">String</span> token) {
<span class="keyword">return</span> token != <span class="keyword">null</span> && token.length() > <span class="string">32</span>;
}
}</code></pre>
<h4>2. <code>final</code> <span class="badge">Immutability</span></h4>
<p>Prevents structural changes. Variables cannot be reassigned; methods cannot be overridden; classes cannot be extended.</p>
<pre><code><span class="keyword">public final class</span> <span class="type">ImmutableScannerConfig</span> { <span class="comment">// Cannot be extended</span>
<span class="keyword">private final</span> <span class="type">String</span> apiKey; <span class="comment">// Must be initialized exactly once</span>
<span class="keyword">public</span> <span class="type">ImmutableScannerConfig</span>(<span class="type">String</span> apiKey) {
<span class="keyword">this</span>.apiKey = apiKey;
}
<span class="keyword">public final</span> <span class="type">String</span> <span class="type">getApiKey</span>() { <span class="comment">// Cannot be overridden in subclasses</span>
<span class="keyword">return</span> apiKey;
}
}</code></pre>
<h4>3. <code>transient</code> <span class="badge">Serialization Exclusion</span></h4>
<p>Tells the JVM not to serialize this field when writing the object state into an output byte-stream.</p>
<pre><code><span class="keyword">import</span> java.io.<span class="type">Serializable</span>;
<span class="keyword">public class</span> <span class="type">UserSession</span> <span class="keyword">implements</span> <span class="type">Serializable</span> {
<span class="keyword">private static final long</span> serialVersionUID = <span class="string">1L</span>;
<span class="keyword">private</span> <span class="type">String</span> username;
<span class="comment">// Will be completely ignored by Java Serialization and initialized as null upon deserialization</span>
<span class="keyword">private transient</span> <span class="type">String</span> rawSessionPassword;
}</code></pre>
<h4>4. <code>volatile</code> <span class="badge">Multi-Threaded Visibility</span></h4>
<p>Forces all read and write operations to go directly to **Main CPU Memory**, completely bypassing thread local CPU caches (L1, L2). This guarantees that writes by one thread are immediately visible to all other reader threads.</p>
<pre><code><span class="keyword">public class</span> <span class="type">ServiceStatusMonitor</span> <span class="keyword">implements</span> <span class="type">Runnable</span> {
<span class="comment">// Without volatile, thread-local caches may loop indefinitely using stale memory values</span>
<span class="keyword">private volatile boolean</span> active = <span class="keyword">true</span>;
<span class="keyword">public void</span> <span class="type">shutdown</span>() {
active = <span class="keyword">false</span>;
}
<span class="annotation">@Override</span>
<span class="keyword">public void</span> <span class="type">run</span>() {
<span class="keyword">while</span> (active) {
<span class="comment">// Execute application loop...</span>
}
}
}</code></pre>
</div>
<!-- SECTION 3: NESTED & INNER CLASSES -->
<div class="section-card">
<h2>3. Nested and Inner Classes</h2>
<p>Nested classes help group classes that are only used in one place, keeping your code cleaner and more organized. Let's look at exactly when and how to deploy them in high-throughput backend services.</p>
<h3>1. Static Nested Class</h3>
<p>A static class declared inside an outer class. It behaves like any normal package-level class, but is physically nested for clean grouping. It does *not* hold an implicit reference to an instance of the outer class, making it memory-efficient. Use it whenever the nested class does not need access to the outer class's instance fields (e.g., the <a href="builderpattern.html" target="_blank">Builder Pattern</a>).</p>
<pre><code><span class="keyword">public class</span> <span class="type">ApiConfig</span> {
<span class="keyword">private final String</span> endpoint;
<span class="keyword">private</span> <span class="type">ApiConfig</span>(<span class="type">Builder</span> builder) {
<span class="keyword">this</span>.endpoint = builder.endpoint;
}
<span class="comment">// Static Nested Class (Often used for the Builder Pattern)</span>
<span class="keyword">public static class</span> <span class="type">Builder</span> {
<span class="keyword">private</span> <span class="type">String</span> endpoint;
<span class="keyword">public</span> <span class="type">Builder</span> <span class="type">setEndpoint</span>(<span class="type">String</span> endpoint) {
<span class="keyword">this</span>.endpoint = endpoint;
<span class="keyword">return this</span>;
}
<span class="keyword">public</span> <span class="type">ApiConfig</span> <span class="type">build</span>() {
<span class="keyword">return new</span> <span class="type">ApiConfig</span>(<span class="keyword">this</span>);
}
}
}</code></pre>
<h3>2. Non-Static <a href="nestedinnerclass.html" target="_blank">Inner Class</a></h3>
<p>Tied directly to an instance of the outer class. It can access all instance fields of the outer class directly, including private ones. However, this hidden back-reference can easily lead to unexpected memory leaks if the inner class instances outlive the outer parent. Use them sparingly (e.g., for custom Iterators or localized State wrappers within a manager).</p>
<pre><code><span class="keyword">public class</span> <span class="type">TransactionManager</span> {
<span class="keyword">private final String</span> masterId = <span class="string">"DB_CORE_PROD"</span>;
<span class="keyword">public class</span> <span class="type">TransactionSession</span> { <span class="comment">// Non-static Inner Class</span>
<span class="keyword">public void</span> <span class="type">printMetadata</span>() {
<span class="comment">// Directly accesses the outer class's private field!</span>
<span class="type">System</span>.out.println(<span class="string">"Executing query against resource: "</span> + masterId);
}
}
}</code></pre>
</div>
<!-- SECTION 4: ADVANCED COLLECTION FRAMEWORK -->
<div class="section-card">
<h2>4. The Advanced Collection Framework</h2>
<p>A Senior Developer must understand the underlying performance characteristics, memory layouts, and structural thread-safety of collection classes.</p>
<table class="matrix-table">
<thead>
<tr>
<th>Class Name</th>
<th>Ordering</th>
<th>Duplicates Allowed?</th>
<th>Thread Safe?</th>
<th>Primary Complexity (Get / Put)</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>ArrayList</code></td>
<td>Insertion Order</td>
<td>✅ Yes</td>
<td>❌ No</td>
<td>O(1) read, O(N) array resize write</td>
</tr>
<tr>
<td><code>LinkedList</code></td>
<td>Insertion Order</td>
<td>✅ Yes</td>
<td>❌ No</td>
<td>O(N) traversal lookup, O(1) insert at node</td>
</tr>
<tr>
<td><code>HashSet</code></td>
<td>None</td>
<td>❌ No</td>
<td>❌ No</td>
<td>O(1) average lookup/insert</td>
</tr>
<tr>
<td><code>TreeSet</code></td>
<td>Natural / Comparator Sorted</td>
<td>❌ No</td>
<td>❌ No</td>
<td>O(log N) balance tree parsing</td>
</tr>
<tr>
<td><code>HashMap</code></td>
<td>None</td>
<td>❌ No (Keys Only)</td>
<td>❌ No</td>
<td>O(1) average hash mapping</td>
</tr>
<tr>
<td><code>ConcurrentHashMap</code></td>
<td>None</td>
<td>❌ No (Keys Only)</td>
<td>✅ Yes</td>
<td>O(1) concurrent bucket locking / CAS</td>
</tr>
<tr>
<td><code>CopyOnWriteArrayList</code></td>
<td>Insertion Order</td>
<td>✅ Yes</td>
<td>✅ Yes</td>
<td>O(1) read, O(N) copy array write</td>
</tr>
</tbody>
</table>
<div class="fireside-chat">
<h4>🔥 Fireside Chats: ArrayList vs. LinkedList</h4>
<p><strong>ArrayList:</strong> "I'm backed by a dynamic array! If you want to fetch an element by index, I can jump straight to the index instantly (O(1)). But if you insert elements into the middle, I have to copy and shift the rest of the array down, which is painful (O(N))."</p>
<p><strong>LinkedList:</strong> "I don't use arrays. I link elements using pointers! To insert, I just link up the new node (O(1)). But if you want to find an element, I have to traverse my nodes one by one (O(N))."</p>
<p><strong>The Verdict:</strong> Always default to <code>ArrayList</code> in modern microservices. Cache locality and sequential memory layouts make array iteration orders of magnitude faster on physical hardware than pointer-hopping.</p>
</div>
<h3>📡 Collection Code Examples in Backend Contexts</h3>
<h4>1. Overriding Equals and HashCode in HashMap Keys</h4>
<p>If you use a custom object as a key in a <code>HashMap</code>, you *must* override <code>equals</code> and <code>hashCode</code> to prevent duplicate entries and memory leaks.</p>
<pre><code><span class="keyword">import</span> java.util.<span class="type">Objects</span>;
<span class="keyword">public class</span> <span class="type">ClientKey</span> {
<span class="keyword">private final String</span> clientId;
<span class="keyword">private final String</span> secretVersion;
<span class="keyword">public</span> <span class="type">ClientKey</span>(<span class="type">String</span> clientId, <span class="type">String</span> secretVersion) {
<span class="keyword">this</span>.clientId = clientId;
<span class="keyword">this</span>.secretVersion = secretVersion;
}
<span class="annotation">@Override</span>
<span class="keyword">public boolean</span> <span class="type">equals</span>(<span class="type">Object</span> o) {
<span class="keyword">if</span> (<span class="keyword">this</span> == o) <span class="keyword">return true</span>;
<span class="keyword">if</span> (o == <span class="keyword">null</span> || getClass() != o.getClass()) <span class="keyword">return false</span>;
<span class="type">ClientKey</span> that = (<span class="type">ClientKey</span>) o;
<span class="keyword">return</span> <span class="type">Objects</span>.equals(clientId, that.clientId) &&
<span class="type">Objects</span>.equals(secretVersion, that.secretVersion);
}
<span class="annotation">@Override</span>
<span class="keyword">public int</span> <span class="type">hashCode</span>() {
<span class="keyword">return</span> <span class="type">Objects</span>.hash(clientId, secretVersion);
}
}</code></pre>
<h4>2. LinkedList as a Deque for Fast Queue Mechanics</h4>
<p>Instead of search operations, use <code>LinkedList</code> through the <code>Deque</code> interface for fast FIFO or LIFO queue processing inside local rate-limiters.</p>
<pre><code><span class="keyword">import</span> java.util.<span class="type">Deque</span>;
<span class="keyword">import</span> java.util.<span class="type">LinkedList</span>;
<span class="keyword">public class</span> <span class="type">RateLimiterQueue</span> {
<span class="keyword">private final</span> <span class="type">Deque</span><<span class="type">Long</span>> timestampLogs = <span class="keyword">new</span> <span class="type">LinkedList</span><>();
<span class="keyword">public synchronized boolean</span> <span class="type">isAllowed</span>(<span class="keyword">long</span> maxRequests, <span class="keyword">long</span> timeWindowMs) {
<span class="keyword">long</span> now = <span class="type">System</span>.currentTimeMillis();
<span class="keyword">while</span> (!timestampLogs.isEmpty() && (now - timestampLogs.peekFirst() > timeWindowMs)) {
timestampLogs.pollFirst(); <span class="comment">// O(1) removal from the head</span>
}
<span class="keyword">if</span> (timestampLogs.size() < maxRequests) {
timestampLogs.addLast(now); <span class="comment">// O(1) append to tail</span>
<span class="keyword">return true</span>;
}
<span class="keyword">return false</span>;
}
}</code></pre>
<h3>⚡ ConcurrentHashMap Internals (Critical Interview Question)</h3>
<p>Unlike old legacy wrappers like <code>Collections.synchronizedMap()</code> which lock the entire map, <code>ConcurrentHashMap</code> achieves thread-safety using dynamic optimization:</p>
<ul>
<li><strong>Lock-Free Reads:</strong> Uses <code>volatile</code> node properties to read without acquiring locks.</li>
<li><strong>Compare-And-Swap (CAS):</strong> Uses atomic CPU-level instructions to insert nodes into empty buckets without locking.</li>
<li><strong>Bucket-level Synchronization:</strong> Acquired only when writing to or updating an active node. This limits thread contention.</li>
</ul>
<pre><code><span class="keyword">import</span> java.util.concurrent.<span class="type">ConcurrentHashMap</span>;
<span class="keyword">import</span> java.util.concurrent.<span class="type">CopyOnWriteArrayList</span>;
<span class="keyword">public class</span> <span class="type">ThreadSafeCache</span> {
<span class="comment">// Bucket-level locked structure for dynamic updates</span>
<span class="keyword">private final</span> <span class="type">ConcurrentHashMap</span><<span class="type">String</span>, <span class="type">String</span>> activeSessions = <span class="keyword">new</span> <span class="type">ConcurrentHashMap</span><>();
<span class="comment">// Snapshot array structure. Reads are extremely fast, but updates copy the array.</span>
<span class="keyword">private final</span> <span class="type">CopyOnWriteArrayList</span><<span class="type">String</span>> systemHooks = <span class="keyword">new</span> <span class="type">CopyOnWriteArrayList</span><>();
<span class="keyword">public void</span> <span class="type">registerSession</span>(<span class="type">String</span> id, <span class="type">String</span> meta) {
activeSessions.putIfAbsent(id, meta); <span class="comment">// Atomic execution</span>
}
}</code></pre>
<div class="dumb-questions">
<h4>🎓 Top Collection Interview Questions:</h4>
<ul>
<li><strong>Q: How does HashMap resize itself?</strong><br>
A: When the number of entries exceeds the <code>loadFactor * capacity</code> (default threshold is 75%), the map doubles its bucket size. It creates a new bucket array and rehashes the existing entries. Since Java 8, if a bucket collision count exceeds 8 and total capacity is at least 64, the linked list structure converts into a balanced Red-Black Tree (O(log N) lookup).</li>
<li><strong>Q: Why is TreeSet slower than HashSet?</strong><br>
A: HashSet uses a hash map under the hood offering O(1) performance. TreeSet is backed by a self-balancing Red-Black Tree (TreeMap), which keeps elements sorted but requires O(log N) operations to traverse and rebalance the tree structure.</li>
</ul>
</div>
</div>
<!-- SECTION 5: DEEP-DIVE GENERICS -->
<div class="section-card">
<h2>5. Deep-Dive Java Generics</h2>
<p>Generics enforce compile-time type-safety. You must know how to design extensible domain interfaces with wildcards and the **PECS Rule**.</p>
<div class="analogy-box">
<h4>💡 PECS Rule: Producer Extends, Consumer Super</h4>
<ul>
<li><strong>Producer (<code>? extends T</code>):</strong> If your structure yields objects to be read, declare it with <code>extends</code>. You can read, but cannot write.</li>
<li><strong>Consumer (<code>? super T</code>):</strong> If your structure consumes objects to store them, declare it with <code>super</code>. You can write, but cannot safely read.</li>
</ul>
</div>
<pre><code><span class="keyword">import</span> java.util.<span class="type">List</span>;
<span class="comment">// 1. Generic API Wrapper Pattern</span>
<span class="keyword">public class</span> <span class="type">ApiResponse</span><<span class="type">T</span>> {
<span class="keyword">private final</span> <span class="type">T</span> payload;
<span class="keyword">private final int</span> code;
<span class="keyword">public</span> <span class="type">ApiResponse</span>(<span class="type">T</span> payload, <span class="keyword">int</span> code) {
<span class="keyword">this</span>.payload = payload;
<span class="keyword">this</span>.code = code;
}
<span class="keyword">public</span> <span class="type">T</span> <span class="type">getPayload</span>() { <span class="keyword">return</span> payload; }
}
<span class="comment">// 2. Real World Domain Wildcard Pipeline</span>
<span class="keyword">abstract class</span> <span class="type">LogEntry</span> {}
<span class="keyword">class</span> <span class="type">SecurityLog</span> <span class="keyword">extends</span> <span class="type">LogEntry</span> {}
<span class="keyword">class</span> <span class="type">TelemetryProcessor</span> {
<span class="comment">// PRODUCER - Reads items from the list. Must extend parent class LogEntry.</span>
<span class="keyword">public void</span> <span class="type">analyzeTelemetry</span>(<span class="type">List</span><? <span class="keyword">extends</span> <span class="type">LogEntry</span>> telemetryStream) {
<span class="keyword">for</span> (<span class="type">LogEntry</span> log : telemetryStream) {
<span class="type">System</span>.out.println(<span class="string">"Analyzing class: "</span> + log.getClass().getSimpleName());
}
}
<span class="comment">// CONSUMER - Inserts items into target collection. Must accept superclasses of SecurityLog.</span>
<span class="keyword">public void</span> <span class="type">remediateThreats</span>(<span class="type">List</span><? <span class="keyword">super</span> <span class="type">SecurityLog</span>> targetCollection) {
targetCollection.add(<span class="keyword">new</span> <span class="type">SecurityLog</span>()); <span class="comment">// Perfectly safe compile-time write execution</span>
}
}</code></pre>
</div>
<!-- SECTION 6: MULTITHREADING & CONCURRENCY -->
<div class="section-card">
<h2>6. Multithreading & Concurrency</h2>
<h3>⚔️ Thread vs. Process</h3>
<p><strong>Process:</strong> A heavy, isolated execution environment provided by the operating system. It has its own private address space and heap memory. Inter-process communication (IPC) is highly complex and costly.</p>
<p><strong>Thread:</strong> A lightweight path of execution spawned <em>inside</em> a process. All threads of a process share the same Heap memory, but each thread manages its own private **Thread Stack** (storing local variables, method invocations) and **Program Counter (PC)**.</p>
<div class="text-diagram">
+-------------------------------------------------------------+
| JVM PROCESS (Dedicated OS Memory) |
| |
| [ Shared Heap Memory: Active Objects, Configs, Cache ] |
| [ Shared Metaspace: Static definitions, Class Metadata ] |
| |
| +--------------------+ +--------------------+ |
| | THREAD 1 | | THREAD 2 | |
| | - Program Counter | | - Program Counter | |
| | - Stack Frames | | - Stack Frames | |
| | (Local variables)| | (Local variables)| |
| +--------------------+ +--------------------+ |
+-------------------------------------------------------------+
</div>
<h3>🧭 Thread Schedulers</h3>
<p>An OS/JVM component that assigns executing CPU time to threads in the <code>RUNNABLE</code> state. Java scheduling is typically **preemptive and priority-based**. If a higher-priority thread requests resources, the scheduler suspends lower-priority threads. Because scheduling relies on native OS threads, it is inherently non-deterministic.</p>
<h3>🔗 The <code>join()</code> Method</h3>
<p>Tells the current executing thread to block and yield control until the target thread completes its execution.</p>
<pre><code><span class="keyword">public class</span> <span class="type">PipelineRunner</span> {
<span class="keyword">public static void</span> <span class="type">main</span>(<span class="type">String</span>[] args) <span class="keyword">throws</span> <span class="type">InterruptedException</span> {
<span class="type">Thread</span> identityVerificationTask = <span class="keyword">new</span> <span class="type">Thread</span>(() -> {
<span class="type">System</span>.out.println(<span class="string">"Verifying user identity via OAuth provider..."</span>);
<span class="keyword">try</span> { <span class="type">Thread</span>.sleep(<span class="string">2000</span>); } <span class="keyword">catch</span> (<span class="type">InterruptedException</span> e) {}
<span class="type">System</span>.out.println(<span class="string">"Identity verification completed securely."</span>);
});
identityVerificationTask.start();
<span class="comment">// Tells main thread: "Wait right here until identityVerificationTask finished execution"</span>
identityVerificationTask.join();
<span class="type">System</span>.out.println(<span class="string">"Proceeding to session token generation phase..."</span>);
}
}</code></pre>
<h3>📦 Executor Pools & ThreadPools</h3>
<p>Creating platform threads is expensive (requiring kernel allocation). In enterprise backends, we use thread pools managed by <code>ExecutorService</code> to reuse pre-allocated threads.</p>
<pre><code><span class="keyword">import</span> java.util.concurrent.<span class="type">ExecutorService</span>;
<span class="keyword">import</span> java.util.concurrent.<span class="type">Executors</span>;
<span class="keyword">public class</span> <span class="type">IdentityTokenProcessor</span> {
<span class="keyword">public void</span> <span class="type">processUserIdentities</span>() {
<span class="comment">// Creates a fixed-size pool of reusable system threads</span>
<span class="keyword">try</span> (<span class="type">ExecutorService</span> pool = <span class="type">Executors</span>.newFixedThreadPool(<span class="string">8</span>)) {
<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="string">0</span>; i < <span class="string">100</span>; i++) {
<span class="keyword">final int</span> userId = i;
pool.submit(() -> {
<span class="type">System</span>.out.println(<span class="string">"Processing identity token for user "</span> + userId + <span class="string">" on: "</span> + <span class="type">Thread</span>.currentThread().getName());
});
}
} <span class="comment">// Executor auto-closes and shutdowns here</span>
}
}</code></pre>
</div>
<!-- SECTION 7: JAVA 8 CORE FEATURES -->
<div class="section-card">
<h2>7. Java 8 Core Features</h2>
<p>Let's make sure you master functional programming structures alongside runtime resource protections.</p>
<h3>🧩 <a href="functionalinterface.html" target="_blank">Functional Interfaces</a> & Lambdas</h3>
<p>A <strong>Functional Interface</strong> is an interface with exactly *one* abstract method. Annotating it with <code>@FunctionalInterface</code> is optional but protects it from accidental method additions. <strong>Lambdas</strong> provide immediate inline implementations of functional contracts without the garbage of anonymous inner classes.</p>
<div class="microservice-box">
<h4>📡 Real-Life Backend Interface: Dynamic Identity Verification</h4>
<p>A custom functional interface designed to run custom identity verification checks against user credentials before granting access.</p>
<pre><code><span class="annotation">@FunctionalInterface</span>
<span class="keyword">public interface</span> <span class="type">IdentityValidator</span> {
<span class="keyword">boolean</span> <span class="type">validate</span>(<span class="type">String</span> username, <span class="type">String</span> password);
}
<span class="comment">// Inline usage in an authentication registry</span>
<span class="keyword">public class</span> <span class="type">AuthenticationRegistry</span> {
<span class="keyword">public void</span> <span class="type">executeValidation</span>() {
<span class="comment">// Expressing behavior immediately as a Lambda</span>
<span class="type">IdentityValidator</span> prodCheck = (user, pass) -> user.startsWith(<span class="string">"admin_"</span>) && pass.length() > <span class="string">12</span>;
<span class="type">boolean</span> result = prodCheck.validate(<span class="string">"admin_root"</span>, <span class="string">"SecurePassword123!"</span>);
<span class="type">System</span>.out.println(<span class="string">"Authentication validation passing status: "</span> + result);
}
}</code></pre>
</div>
<h3>🌊 The Streams API</h3>
<p>Streams provide a declarative, pipeline-based approach to collection processing. Intermediate operations are **lazy** and return another stream; terminal operations are **eager** and close the stream.</p>
<pre><code><span class="keyword">import</span> java.util.<span class="type">List</span>;
<span class="keyword">import</span> java.util.stream.<span class="type">Collectors</span>;
<span class="keyword">public class</span> <span class="type">VulnerabilityFilter</span> {
<span class="keyword">public record</span> <span class="type">UserCredential</span>(<span class="type">String</span> id, <span class="type">String</span> role, <span class="keyword">boolean</span> mfaRequired) {}
<span class="keyword">public</span> <span class="type">List</span><<span class="type">String</span>> <span class="type">findUnverifiedAdmins</span>(<span class="type">List</span><<span class="type">UserCredential</span>> inputList) {
<span class="keyword">return</span> inputList.stream()
.filter(u -> <span class="string">"ADMIN"</span>.equals(u.role())) <span class="comment">// Intermediate</span>
.filter(u -> u.mfaRequired()) <span class="comment">// Intermediate</span>
.map(<span class="type">UserCredential</span>::id) <span class="comment">// Intermediate</span>
.collect(<span class="type">Collectors</span>.toList()); <span class="comment">// Terminal execution</span>
}
}</code></pre>
<h3>🛑 Optional Class</h3>
<p>A wrapper class introduced to eliminate standard NullPointerExceptions by forcing developers to handle empty checks explicitly.</p>
<pre><code><span class="keyword">import</span> java.util.<span class="type">Optional</span>;
<span class="keyword">public class</span> <span class="type">IdentityVerificationService</span> {
<span class="keyword">public</span> <span class="type">Optional</span><<span class="type">String</span>> <span class="type">validateUserIdentity</span>(<span class="type">String</span> jwtToken) {
<span class="keyword">return</span> <span class="type">Optional</span>.ofNullable(verifyAndDecodeJwt(jwtToken));
}
<span class="keyword">private String</span> <span class="type">verifyAndDecodeJwt</span>(<span class="type">String</span> token) {
<span class="keyword">return null</span>; <span class="comment">// Simulated invalid token</span>
}
<span class="keyword">public void</span> <span class="type">executeTask</span>() {
<span class="type">String</span> userId = validateUserIdentity(<span class="string">"eyJhbGciOiJIUzI1NiIs..."</span>)
.map(<span class="type">String</span>::trim)
.orElseThrow(() -> <span class="keyword">new</span> <span class="type">IllegalArgumentException</span>(<span class="string">"Invalid JWT token"</span>));
}
}</code></pre>
<h3>♻️ Try-With-Resources</h3>
<p>Simplifies resource cleanup by automatically closing objects that implement <code>java.lang.AutoCloseable</code> at the end of the block, even if an exception is thrown.</p>