-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlessons.js
More file actions
2387 lines (2183 loc) · 112 KB
/
Copy pathlessons.js
File metadata and controls
2387 lines (2183 loc) · 112 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
// ============================================
// Java Learning Hub - Comprehensive Lessons
// Based on W3Schools Java Tutorial
// ============================================
const JAVA_CURRICULUM = {
modules: [
// ==========================================
// MODULE 1: GETTING STARTED
// ==========================================
{
id: "getting-started",
title: "Getting Started",
icon: "<i class='fa-solid fa-rocket'></i>",
lessons: [
{
id: "intro",
title: "Introduction",
duration: "15 min",
content: {
description: "Java is a powerful, high-level, object-oriented programming language designed to be platform-independent. Write once, run anywhere on any device with JVM.",
snippet: "System.out.println(\"Hello, World!\");",
keyPoints: [
"Owned by Oracle, developed by Sun Microsystems in 1995",
"Platform-independent through Java Virtual Machine (JVM)",
"Widely used in Android apps, enterprise and web applications",
"Syntax similar to C++ with automatic memory management",
"Strong static typing prevents many common errors"
]
},
example: `public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}`,
explanation: "Every Java program must contain at least one class, and that class must have a main method to serve as the entry point where program execution begins. The main method signature `public static void main(String[] args)` is fixed and tells the JVM where to start running your code. The `public` keyword makes it accessible from anywhere, `static` means it belongs to the class rather than an instance, `void` indicates it doesn't return a value, and `String[] args` allows command-line arguments to be passed to the program. When you run a Java program, the JVM looks for this exact method signature to begin execution."
},
{
id: "syntax",
title: "Java Syntax",
duration: "15 min",
content: {
description: "Java syntax is the set of rules defining how code must be written. Case-sensitive, uses semicolons to end statements and curly braces for code blocks.",
snippet: "int x = 5;\nint y = 6;\nSystem.out.println(x + y);",
keyPoints: [
"Java is case-sensitive - 'Main' and 'main' are different",
"Class names use PascalCase, method names use camelCase",
"main method required: public static void main(String[] args)",
"Statements end with semicolon (;)",
"Code blocks enclosed in curly braces { }"
]
},
example: `public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
int x = 5;
int y = 6;
System.out.println(x + y);
}
}`,
explanation: "The main method serves as the entry point for every Java application - it's where execution begins when you run the program. The method signature must be exactly `public static void main(String[] args)` for the JVM to recognize it. Inside the main method, `System.out.println()` is used to display output to the console, automatically adding a newline after each call. Variables in Java must be declared with a specific data type (like `int` for integers) before they can be used, and they can be assigned values using the equals sign. The `int x = 5;` statement both declares the variable and initializes it with the value 5. When you perform operations like `x + y`, Java evaluates the expression and can display the result."
},
{
id: "output",
title: "Output",
duration: "10 min",
content: {
description: "Output displays information to users via console. System.out.println() prints text with a newline. Use + to concatenate strings with variables.",
snippet: "System.out.println(\"Hello World\");\nSystem.out.println(\"Math: \" + (5 + 5));",
keyPoints: [
"System.out.println() prints with newline",
"System.out.print() prints without newline",
"System.out.printf() for formatted output",
"Use + to concatenate strings",
"Escape sequences: \\n (newline), \\t (tab)"
]
},
example: `public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
System.out.println("I am learning Java");
System.out.println("Math: " + (5 + 5));
}
}`,
explanation: "The System.out.println() method is your primary tool for displaying information in Java console applications. Each call to println() outputs its argument to the console and then moves the cursor to the next line, making it easy to create readable output. When you want to combine text with variable values or calculations, you use the + operator for string concatenation. Java automatically converts numbers and other types to strings when they're concatenated with strings. The parentheses around (5 + 5) in the example ensure that the mathematical addition happens before the result is converted to a string and concatenated with 'Math: '. Without the parentheses, Java would concatenate 'Math: ' + 5 first (resulting in 'Math: 5'), then add 5, giving 'Math: 55' instead of the intended 'Math: 10'."
},
{
id: "comments",
title: "Comments",
duration: "10 min",
content: {
description: "Comments are explanations ignored by the compiler. Use // for single-line and /* */ for multi-line comments to document code.",
snippet: "// This is a single-line comment\n/* This is a\n multi-line comment */",
keyPoints: [
"// for single-line comments",
"/* */ for multi-line comments",
"/** */ for documentation comments",
"Ignored by compiler - no effect on execution"
]
},
example: `public class Main {
public static void main(String[] args) {
// This is a single-line comment
System.out.println("Comments are ignored");
/* This is a
multi-line comment */
System.out.println("Hello World");
}
}`,
explanation: "Comments in Java serve as human-readable explanations embedded within your source code. The compiler treats them as whitespace and completely ignores them when generating bytecode. Single-line comments beginning with // are perfect for brief explanations or notes about individual lines of code. Multi-line comments enclosed in /* */ are ideal for longer explanations that span multiple lines, such as describing the purpose of a method or class. While comments don't affect how your program runs, they dramatically improve code maintainability. Good comments explain the 'why' behind complex logic rather than just the 'what'. During development, comments can also be used to temporarily disable problematic code sections by commenting them out, allowing you to isolate and test specific parts of your program."
}
]
},
// ==========================================
// MODULE 2: VARIABLES & DATA TYPES
// ==========================================
{
id: "variables-datatypes",
title: "Variables & Data Types",
icon: "<i class='fa-solid fa-box'></i>",
lessons: [
{
id: "variables",
title: "Variables",
duration: "15 min",
content: {
description: "Variables are named containers for storing data values. Java requires explicit type declaration - declare type before using.",
snippet: "String name = \"John\";\nint age = 25;\ndouble gpa = 3.5;\nboolean isStudent = true;",
keyPoints: [
"Syntax: dataType variableName; or dataType variableName = value;",
"Common types: int, double, boolean, char, String",
"Use final for constants: final int X = 10;",
"Names should be descriptive (camelCase)",
"Must be initialized before use"
]
},
example: `public class Main {
public static void main(String[] args) {
String name = "John";
int age = 25;
double gpa = 3.5;
boolean isStudent = true;
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("GPA: " + gpa);
System.out.println("Student: " + isStudent);
}
}`,
explanation: "In this example, we declare four variables of different types. The `String` type stores text data and can hold sequences of characters. The `int` type stores whole numbers without decimal points, perfect for counting items or representing ages. The `double` type stores floating-point numbers with decimal precision, ideal for calculations involving fractions like GPAs. The `boolean` type stores only two possible values: `true` or `false`, making it perfect for yes/no conditions. Each variable is declared with a specific type that determines what kind of data it can hold and what operations can be performed on it. Java's strong typing ensures type safety, preventing you from accidentally mixing incompatible data types."
},
{
id: "print-variables",
title: "Print Variables",
duration: "10 min",
content: {
description: "Display variable values using System.out.println(). Use + to concatenate text with variables or perform math.",
snippet: "String name = \"John\";\nint age = 25;\nSystem.out.println(\"Hello \" + name);\nSystem.out.println(\"Age: \" + age);",
keyPoints: [
"Use + to concatenate text and variables",
"System.out.println(x) prints variable value",
"Math: x + y adds numbers"
]
},
example: `public class Main {
public static void main(String[] args) {
String name = "John";
int age = 25;
System.out.println("Hello " + name);
System.out.println("Age: " + age);
int x = 10, y = 20;
System.out.println(x + y); // Prints 30
System.out.println("x + y = " + (x + y)); // Prints "x + y = 30"
}
}`,
explanation: "The + operator's behavior depends on context. When used between two numbers, it performs mathematical addition. When used between a string and any other type, it performs string concatenation, automatically converting the non-string operand to a string representation. In the example, `System.out.println(x + y);` adds 10 + 20 and prints 30. However, `System.out.println(\"x + y = \" + (x + y));` first evaluates (x + y) to get 30, then concatenates it with the string \"x + y = \" to produce \"x + y = 30\". The parentheses are crucial here - without them, Java would concatenate \"x + y = \" + x first (giving \"x + y = 10\"), then add y, resulting in \"x + y = 1020\" instead of the intended \"x + y = 30\". This demonstrates how operator precedence affects output."
},
{
id: "multiple-variables",
title: "Declare Multiple Variables",
duration: "10 min",
content: {
description: "Declare multiple variables of the same type in one statement using commas. Group related variables together.",
snippet: "int x = 5, y = 10, z = 15;\nString firstName = \"John\", lastName = \"Doe\";",
keyPoints: [
"Syntax: dataType var1, var2, var3;",
"With values: dataType var1 = val1, var2 = val2;",
"All must be same data type"
]
},
example: `public class Main {
public static void main(String[] args) {
int x = 5, y = 10, z = 15;
System.out.println(x + y + z);
String name = "John", lastName = "Doe";
System.out.println(name + " " + lastName);
}
}`,
explanation: "In the first line, we declare three integer variables (x, y, z) and initialize them with values 5, 10, and 15 respectively, all in a single statement. This is equivalent to writing three separate declarations but is more concise. The second example shows the same pattern with String variables, where both name and lastName are initialized with string literals. When printing, we concatenate the strings with a space to create a full name. This multiple declaration syntax is especially useful when working with coordinates (x, y, z), dimensions (width, height, depth), or any other related set of variables that should be grouped together. It makes the code more compact while maintaining clarity about which variables are related."
},
{
id: "identifiers",
title: "Identifiers",
duration: "10 min",
content: {
description: "Identifiers are names for variables, methods, classes. Must start with letter, underscore or $. Case-sensitive.",
snippet: "int myVariable = 5;\nint _age = 25;\nint $price = 99;",
keyPoints: [
"Start with letter, underscore (_), or dollar ($)",
"Cannot start with a number",
"Case-sensitive: myVar and MyVar are different",
"Cannot use Java keywords",
"Use camelCase for variables, PascalCase for classes"
]
},
example: `public class Main {
public static void main(String[] args) {
// Valid identifiers
int myVariable = 5;
int _age = 25;
int $price = 99;
int camelCase = 1;
// Invalid (would cause errors):
// int 1variable = 5; // starts with number
// int my-var = 5; // contains hyphen
// int class = 5; // is a keyword
System.out.println("Valid identifiers used!");
}
}`,
explanation: "Choosing good identifiers is fundamental to writing clear, maintainable code. Start each identifier with a letter, underscore, or dollar sign, then use any combination of those characters plus digits. Java treats uppercase and lowercase letters as different characters, so `age` and `Age` are completely different variables. Avoid using Java's reserved keywords as identifiers - these words have special meanings in the language and cannot be used for naming. Follow conventional naming patterns: variables and methods use camelCase (starting with lowercase), while classes use PascalCase (starting with uppercase). Meaningful names like `studentCount` or `calculateTotal` are much better than cryptic names like `x` or `temp`. While the rules allow unusual characters like underscores at the beginning or dollar signs, these are typically reserved for special cases and should be used judiciously to maintain code readability."
},
{
id: "data-types",
title: "Data Types",
duration: "15 min",
content: {
description: "Java has primitive types (int, double, boolean, char) and reference types (String, arrays, objects).",
snippet: "int i = 100000;\ndouble d = 19.99;\nboolean isFun = true;\nchar grade = 'A';\nString name = \"John\";",
keyPoints: [
"Primitives: byte, short, int, long, float, double, boolean, char",
"Reference types: String, arrays, objects",
"Integer: int (32-bit), long (64-bit)",
"Decimal: double (64-bit), float (32-bit)",
"boolean: true or false only"
]
},
example: `public class Main {
public static void main(String[] args) {
// Numbers
byte b = 100;
short s = 5000;
int i = 100000;
long l = 15000000000L;
float f = 5.99f;
double d = 19.99;
// Characters and booleans
char grade = 'A';
boolean isFun = true;
// Non-primitive
String name = "John";
System.out.println("Byte: " + b);
System.out.println("Float: " + f);
System.out.println("Char: " + grade);
System.out.println("Boolean: " + isFun);
}
}`,
explanation: "Primitive data types store their values directly in memory, making them efficient for simple data. When you declare `int i = 100000;`, the value 100000 is stored directly in the variable's memory location. Reference types like String work differently - they store a memory address that points to where the actual string data is stored elsewhere in memory. This indirection allows reference types to handle complex data structures but requires the JVM to perform additional work when accessing the data. The choice between primitive and reference types affects both performance and functionality. Primitives are faster and use less memory for simple values, while reference types provide more flexibility for complex data manipulation."
},
{
id: "numbers",
title: "Numbers",
duration: "15 min",
content: {
description: "Numeric types: int for integers, double for decimals. Use L suffix for long, f for float.",
snippet: "int i = 1000000;\nlong bigNum = 15000000000L;\ndouble price = 19.99;\nfloat tax = 0.08f;\ndouble exp = 35e3; // 35000",
keyPoints: [
"int: most common integer (32-bit)",
"long: very large integers, use L suffix",
"double: default decimal (64-bit)",
"float: less precise, use f suffix",
"Scientific: 35e3 = 35000"
]
},
example: `public class Main {
public static void main(String[] args) {
// Integers
int i = 1000000;
long bigNum = 15000000000L;
// Decimals
double price = 19.99;
float tax = 0.08f;
// Scientific numbers
double exp = 35e3; // 35 * 10^3 = 35000
double exp2 = 12e-3; // 12 * 10^-3 = 0.012
System.out.println("Price: " + price);
System.out.println("Tax: " + tax);
System.out.println("Scientific: " + exp);
}
}`,
explanation: "When working with numbers in Java, double is the go-to choice for decimal values because of its precision and ease of use. Float requires the 'f' suffix on literals to distinguish it from double, and while it uses less memory, its reduced precision makes it less suitable for most applications. Scientific notation provides a compact way to represent very large or very small numbers using exponential notation. The 'e' represents 'times 10 to the power of', so 35e3 is 35 multiplied by 10 cubed (1,000), resulting in 35,000. For critical financial calculations where precision is paramount, Java's BigDecimal class offers arbitrary precision arithmetic that avoids the rounding errors inherent in floating-point math."
},
{
id: "booleans",
title: "Booleans",
duration: "10 min",
content: {
description: "boolean stores true or false. Used for conditions, comparisons, and logical operations.",
snippet: "boolean isJavaFun = true;\nSystem.out.println(x > y); // true/false\nif (isJavaFun) { ... }",
keyPoints: [
"boolean stores true or false",
"Comparison operators return boolean",
"Logical operators: && (and), || (or), ! (not)",
"Used in if/while statements"
]
},
example: `public class Main {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // true
System.out.println(isFishTasty); // false
// Boolean in conditions
int x = 10;
int y = 9;
System.out.println(x > y); // true
// if-else example
if (isJavaFun) {
System.out.println("Java is fun!");
} else {
System.out.println("Java is not fun.");
}
}
}`,
explanation: "Booleans form the backbone of decision-making in Java programs. Every comparison operation produces a boolean result that can be used to control program execution. The if-else statement demonstrates how boolean values determine which code block runs. When `isJavaFun` is true, the first message prints; when false, the else block executes. Comparison operators like `x > y` evaluate relationships between values and return boolean results. Logical operators allow combining multiple conditions: `&&` requires both conditions to be true, `||` requires at least one to be true, and `!` negates a boolean value. This boolean logic enables complex decision trees and conditional execution patterns essential for responsive programs."
},
{
id: "characters",
title: "Characters",
duration: "10 min",
content: {
description: "char stores single characters in single quotes. Supports Unicode - any language character.",
snippet: "char grade = 'A';\nchar symbol = '!';\nchar unicode = '\\u0041'; // 'A'",
keyPoints: [
"Use single quotes: 'A', 'x', '!'",
"16-bit Unicode support",
"Escape sequences: \\n, \\t, \\\\",
"Different from String (double quotes)"
]
},
example: `public class Main {
public static void main(String[] args) {
char grade = 'A';
char symbol = '!';
char unicode = '\\u0041'; // Unicode for 'A'
System.out.println("Grade: " + grade);
System.out.println("Symbol: " + symbol);
System.out.println("Unicode: " + unicode);
// Escape sequences
System.out.println("New\\nLine"); // New line
System.out.println("Tab\\tHere"); // Tab
System.out.println("Quote: \\\""); // Quote
}
}`,
explanation: "Characters in Java are more powerful than they might appear at first glance. The single quotes distinguish char literals from String literals (which use double quotes). Unicode support means you can work with characters from any language, making Java applications truly global. The escape sequences allow you to include special characters that would otherwise be difficult to type or that have special meaning in code. For example, '\\n' inserts a newline character, '\\t' creates a tab space, and '\\\\' allows you to include a literal backslash. Unicode escapes like '\\u0041' let you specify any character by its Unicode code point, which is especially useful for characters that aren't easily typed on a keyboard."
},
{
id: "non-primitive",
title: "Non-Primitive Types",
duration: "10 min",
content: {
description: "Reference types store references to objects (not values). String, arrays, and custom classes are reference types.",
snippet: "String text = \"Hello\";\ntext.length();\ntext.toUpperCase();\nString[] cars = {\"Volvo\", \"BMW\"};",
keyPoints: [
"Store memory addresses, not values",
"String: text methods like length(), toUpperCase()",
"Arrays: multiple values of same type",
"Can be null",
"Have built-in methods"
]
},
example: `public class Main {
public static void main(String[] args) {
// String methods
String text = "Hello World";
System.out.println(text.length()); // 11
System.out.println(text.toUpperCase()); // HELLO WORLD
System.out.println(text.toLowerCase()); // hello world
System.out.println(text.indexOf("World")); // 6
// Arrays
String[] cars = {"Volvo", "BMW", "Ford"};
System.out.println(cars[0]); // Volvo
// Can be null
String name = null;
System.out.println(name); // null
}
}`,
explanation: "Reference types provide powerful functionality that primitives can't match. Strings come with numerous built-in methods for text manipulation - length() tells you how many characters are in the string, toUpperCase() and toLowerCase() change case, and indexOf() finds the position of substrings. Arrays allow you to store collections of data efficiently, accessed by index. The ability to be null is both powerful and dangerous - it allows you to represent 'no value' but requires careful null checking to avoid NullPointerException errors. When you assign one reference variable to another, you're copying the memory address, not the object itself, which is why changes to the object are visible through both references."
}
]
},
// ==========================================
// MODULE 3: OPERATORS & CASTING
// ==========================================
{
id: "operators-casting",
title: "Operators & Casting",
icon: "<i class='fa-solid fa-1'></i>",
lessons: [
{
id: "type-casting",
title: "Type Casting",
duration: "15 min",
content: {
description: "Type casting converts between data types. Widening (int to double) is automatic. Narrowing requires explicit (double to int).",
snippet: "int myInt = 9;\ndouble myDouble = myInt; // auto\ndouble d = 9.78;\nint i = (int) d; // manual, 9",
keyPoints: [
"Widening: smaller to larger (automatic)",
"Narrowing: larger to smaller (manual with (type))",
"Syntax: (targetType) value",
"Precision may be lost in narrowing"
]
},
example: `public class Main {
public static void main(String[] args) {
// Widening (automatic)
int myInt = 9;
double myDouble = myInt;
System.out.println(myInt); // 9
System.out.println(myDouble); // 9.0
// Narrowing (manual)
double myDouble2 = 9.78;
int myInt2 = (int) myDouble2;
System.out.println(myDouble2); // 9.78
System.out.println(myInt2); // 9
// Type promotion in expressions
double result = (5 + 3.0) * 2;
System.out.println(result); // 16.0
}
}`,
explanation: "Type casting is a fundamental concept in Java that allows you to convert between compatible data types. Widening conversions happen automatically because they are guaranteed to be safe - converting an int to a double simply adds decimal places with zeros. Narrowing conversions require explicit casting because they can lose information. When you cast 9.78 to an int, the decimal part (.78) is truncated, not rounded, resulting in 9. The casting operator (targetType) tells the compiler you understand the potential data loss and accept responsibility for it. In expressions like (5 + 3.0) * 2, Java automatically promotes the int 5 to double 3.0 for the addition, then the entire expression evaluates to a double. Understanding these rules helps you write more predictable code and avoid unexpected type conversion behaviors."
}
]
},
// ==========================================
// MODULE 4: CONTROL FLOW
// ==========================================
{
id: "control-flow",
title: "Control Flow",
icon: "<i class='fa-solid fa-shuffle'></i>",
lessons: [
{
id: "operators",
title: "Operators",
duration: "15 min",
content: {
description: "Operators perform operations: arithmetic (+ - * / %), comparison (== != < >), logical (&& || !), ternary (?:).",
snippet: "int x = 10, y = 5;\nx + y; // 15\nx == y; // false\nx > 3 && y < 10; // true\nString r = (x > 5) ? \"Big\" : \"Small\";",
keyPoints: [
"Arithmetic: + - * / % ++ --",
"Comparison: == != < > <= >=",
"Logical: && (and), || (or), ! (not)",
"Ternary: condition ? true : false",
"Assignment: += -= *= /="
]
},
example: `public class Main {
public static void main(String[] args) {
int x = 10, y = 5;
// Arithmetic
System.out.println("Add: " + (x + y)); // 15
System.out.println("Sub: " + (x - y)); // 5
System.out.println("Mul: " + (x * y)); // 50
System.out.println("Div: " + (x / y)); // 2
System.out.println("Mod: " + (x % y)); // 0
// Comparison
System.out.println(x == y); // false
System.out.println(x > y); // true
// Logical
System.out.println(x > 3 && y < 10); // true
System.out.println(x > 3 || y > 10); // true
System.out.println(!(x > 3)); // false
// Ternary
int age = 20;
String result = (age >= 18) ? "Adult" : "Minor";
System.out.println(result); // Adult
}
}`,
explanation: "Operators are the workhorses of Java expressions, enabling everything from simple calculations to complex decision-making. Arithmetic operators handle mathematical operations, with modulo (%) giving remainders from division and increment/decrement providing convenient counting mechanisms. Comparison operators always produce boolean results, making them perfect for conditions. Logical operators combine boolean values, with short-circuit evaluation optimizing performance by stopping evaluation when the result is determined. The ternary operator offers a compact way to choose between two values based on a condition. Understanding these operators and their precedence rules allows you to write clear, efficient expressions that behave predictably."
},
{
id: "strings",
title: "Strings",
duration: "15 min",
content: {
description: "Strings are objects with built-in methods. Use double quotes. Immutable - methods return new strings.",
snippet: "String s = \"Hello\";\ns.length();\ns.toUpperCase();\ns.indexOf(\"o\");\ns.substring(0, 5);",
keyPoints: [
"Use double quotes: \"Hello\"",
"Methods: length(), toUpperCase(), toLowerCase()",
"indexOf(), substring() for searching",
"equals() for comparison (not ==)",
"Immutable - creates new strings"
]
},
example: `public class Main {
public static void main(String[] args) {
String greeting = "Hello World";
// Length and case manipulation
System.out.println("Length: " + greeting.length()); // 11
System.out.println("Upper: " + greeting.toUpperCase()); // HELLO WORLD
System.out.println("Lower: " + greeting.toLowerCase()); // hello world
// Finding and extracting substrings
System.out.println("Index of World: " + greeting.indexOf("World")); // 6
System.out.println("Substring: " + greeting.substring(0, 5)); // Hello
System.out.println("Substring from index: " + greeting.substring(6)); // World
// Concatenation methods
String firstName = "John";
String lastName = "Doe";
System.out.println("Full name: " + firstName + " " + lastName);
System.out.println("Concat method: " + firstName.concat(" ").concat(lastName));
// String comparison
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println("s1 == s2: " + (s1 == s2)); // true (same reference)
System.out.println("s1 == s3: " + (s1 == s3)); // false (different references)
System.out.println("s1.equals(s3): " + s1.equals(s3)); // true (same content)
// Special characters and escaping
System.out.println("Hello\\nWorld"); // New line
System.out.println("Hello\\tWorld"); // Tab
System.out.println("Quote: \\\"Hello\\\""); // Escaped quotes
System.out.println("Path: C:\\\\Users\\\\file.txt"); // Windows path
}
}`,
explanation: "Java strings are powerful objects with extensive functionality for text processing. The immutability of strings means that operations like toUpperCase() create new string objects rather than modifying the existing one, which is why you need to assign the result back to a variable or use it directly. String concatenation with the + operator is convenient but can be inefficient in loops due to creating many temporary objects - StringBuilder is preferred for such cases. The equals() method compares actual string content, while == compares object references, which is crucial for correct string comparisons. Understanding these concepts enables robust text manipulation in Java applications."
},
{
id: "math",
title: "Math",
duration: "15 min",
content: {
description: "Math class provides static methods for math operations: max, min, abs, sqrt, pow, random.",
snippet: "Math.PI;\nMath.max(5, 10);\nMath.min(3, 8);\nMath.abs(-5);\nMath.sqrt(64); // 8\nMath.pow(2, 3); // 8\nMath.random(); // 0.0 to 1.0",
keyPoints: [
"Static class - no instantiation needed",
"Math.PI, Math.E for constants",
"Math.max(), Math.min() for comparison",
"Math.abs() for absolute value",
"Math.sqrt(), Math.pow() for powers",
"Math.random() for random 0.0-1.0"
]
},
example: `public class Main {
public static void main(String[] args) {
// Constants
System.out.println("PI: " + Math.PI); // 3.141592653589793
System.out.println("E: " + Math.E); // 2.718281828459045
// Comparison operations
System.out.println("Max of 5, 10: " + Math.max(5, 10)); // 10
System.out.println("Min of 5, 10: " + Math.min(5, 10)); // 5
System.out.println("Max of doubles: " + Math.max(3.14, 2.71)); // 3.14
// Absolute value and square root
System.out.println("Absolute value: " + Math.abs(-4.7)); // 4.7
System.out.println("Square root of 64: " + Math.sqrt(64)); // 8.0
System.out.println("Square root of 2: " + Math.sqrt(2)); // 1.414...
// Powers and exponents
System.out.println("2^3: " + Math.pow(2, 3)); // 8.0
System.out.println("10^2: " + Math.pow(10, 2)); // 100.0
System.out.println("Square root via pow: " + Math.pow(16, 0.5)); // 4.0
// Random numbers
System.out.println("Random (0.0-1.0): " + Math.random());
System.out.println("Random integer 0-9: " + (int)(Math.random() * 10));
System.out.println("Random integer 1-6: " + ((int)(Math.random() * 6) + 1));
// Rounding functions
double num = 5.7;
System.out.println("Round: " + Math.round(num)); // 6 (rounds to nearest)
System.out.println("Floor: " + Math.floor(num)); // 5.0 (rounds down)
System.out.println("Ceil: " + Math.ceil(num)); // 6.0 (rounds up)
// Trigonometric functions (angles in radians)
double angle = Math.PI / 4; // 45 degrees
System.out.println("Sin(45°): " + Math.sin(angle)); // 0.707...
System.out.println("Cos(45°): " + Math.cos(angle)); // 0.707...
System.out.println("Tan(45°): " + Math.tan(angle)); // 1.0
// Advanced functions
System.out.println("e^2: " + Math.exp(2)); // 7.389...
System.out.println("Natural log of e: " + Math.log(Math.E)); // 1.0
System.out.println("Log base 10 of 100: " + Math.log10(100)); // 2.0
}
}`,
explanation: "The Math class serves as Java's mathematical powerhouse, providing precise implementations of essential mathematical functions that would be cumbersome to implement manually. All methods are static, eliminating the need for object creation and making them readily accessible throughout your programs. The random() method uses a pseudorandom number generator suitable for most applications, though java.security.SecureRandom should be used for cryptographic purposes. Trigonometric functions expect angles in radians rather than degrees, so conversion may be necessary when working with degree-based measurements. Understanding these mathematical utilities enables the creation of sophisticated applications involving calculations, simulations, and data analysis."
},
{
id: "if-else",
title: "If-Else",
duration: "15 min",
content: {
description: "if-else executes code based on boolean conditions. Use else if for multiple conditions.",
snippet: "if (score >= 90) {\n grade = \"A\";\n} else if (score >= 80) {\n grade = \"B\";\n} else {\n grade = \"F\";\n}",
keyPoints: [
"if (condition) { code }",
"else { code } for alternative",
"else if for multiple conditions",
"Ternary: condition ? true : false"
]
},
example: `public class Main {
public static void main(String[] args) {
int score = 85;
String grade;
// Basic if-else structure
if (score >= 90) {
grade = "A";
System.out.println("Excellent work!");
} else if (score >= 80) {
grade = "B";
System.out.println("Good job!");
} else if (score >= 70) {
grade = "C";
System.out.println("Satisfactory");
} else if (score >= 60) {
grade = "D";
System.out.println("Needs improvement");
} else {
grade = "F";
System.out.println("Failed - try again");
}
System.out.println("Final grade: " + grade);
// Ternary operator for simple assignments
String passFail = (score >= 60) ? "PASS" : "FAIL";
System.out.println("Result: " + passFail);
// Nested conditions for complex logic
int age = 20;
boolean hasLicense = true;
double gpa = 3.5;
if (age >= 18) {
if (hasLicense) {
if (gpa >= 3.0) {
System.out.println("Eligible for premium driving discount");
} else {
System.out.println("Eligible for standard driving discount");
}
} else {
System.out.println("Must obtain license first");
}
} else {
System.out.println("Too young to drive");
}
// Complex boolean expressions
boolean isEligible = (age >= 18) && hasLicense && (gpa >= 2.0);
System.out.println("Scholarship eligible: " + isEligible);
// Short-circuit evaluation example
int x = 5;
if ((x > 3) && (x++ < 10)) { // x++ not executed if first condition false
System.out.println("Both conditions true");
}
System.out.println("x is now: " + x); // x = 6 (increment occurred)
}
}`,
explanation: "If-else statements form the foundation of decision-making in Java, enabling programs to execute different code paths based on runtime conditions. The structure allows for simple binary decisions, multi-way branching with else-if chains, and complex nested logic for sophisticated decision trees. Boolean expressions combine multiple conditions using logical operators, with short-circuit evaluation providing performance benefits by avoiding unnecessary computations. The ternary operator offers a concise alternative for simple conditional assignments, while proper indentation and brace usage ensures code clarity and prevents common logic errors. Mastering these constructs enables the creation of responsive, intelligent applications that can handle diverse scenarios and user inputs."
},
{
id: "switch",
title: "Switch",
duration: "15 min",
content: {
description: "Switch executes code based on variable value. Compare against multiple case labels. Use break to prevent fall-through.",
snippet: "switch(day) {\n case 1: dayName = \"Mon\"; break;\n case 2: dayName = \"Tue\"; break;\n default: dayName = \"Unknown\";\n}",
keyPoints: [
"switch(variable) { case value: }",
"break prevents fall-through",
"default for unmatched values",
"Supports int, char, String, enum",
"Java 14+: arrow syntax (->)"
]
},
example: `public class Main {
public static void main(String[] args) {
// Traditional switch with break statements
int dayOfWeek = 3;
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("Day: " + dayName);
// Enhanced switch with arrow syntax (Java 14+)
int month = 7;
String season = switch (month) {
case 12, 1, 2 -> "Winter";
case 3, 4, 5 -> "Spring";
case 6, 7, 8 -> "Summer";
case 9, 10, 11 -> "Autumn";
default -> "Invalid month";
};
System.out.println("Season: " + season);
// Switch with String values
String grade = "B";
String description;
switch (grade) {
case "A":
description = "Excellent work!";
break;
case "B":
description = "Good job!";
break;
case "C":
description = "Satisfactory performance";
break;
case "D":
description = "Needs improvement";
break;
case "F":
description = "Failed - must retake";
break;
default:
description = "Invalid grade";
break;
}
System.out.println("Grade description: " + description);
// Switch with fall-through (multiple cases share code)
int number = 2;
switch (number) {
case 1:
System.out.println("One");
break;
case 2:
case 3:
System.out.println("Two or Three"); // Both 2 and 3 execute this
break;
case 4:
System.out.println("Four");
break;
default:
System.out.println("Other number");
}
// Switch expression returning a value
int day = 5;
boolean isWeekend = switch (day) {
case 1, 2, 3, 4, 5 -> false; // Monday to Friday
case 6, 7 -> true; // Saturday, Sunday
default -> false;
};
System.out.println("Is weekend: " + isWeekend);
}
}`,
explanation: "Switch statements excel when you need to branch based on a single variable's discrete values, offering cleaner code than lengthy if-else chains. The traditional syntax requires break statements to prevent fall-through, where execution continues to subsequent cases. Modern Java's enhanced switch with arrow syntax eliminates this issue and supports more concise expressions. Multiple case labels can share the same code block, and switch expressions can directly return values. While powerful for menu systems and state-based logic, switches work best when the number of possible values is reasonable and the comparisons are equality-based."
},
{
id: "while-loop",
title: "While Loop",
duration: "15 min",
content: {
description: "While loops repeat while condition is true. do-while runs at least once. Modify condition inside loop!",
snippet: "while (i > 0) {\n System.out.println(i);\n i--;\n}\n\n// do-while: runs at least once\ndo {\n System.out.println(i);\n i--;\n} while (i > 0);",
keyPoints: [
"while (condition) { code }",
"do { code } while (condition); - runs once minimum",
"Modify condition inside loop",
"break exits, continue skips iteration"
]
},
example: `public class Main {
public static void main(String[] args) {
// Basic while loop - countdown
int countdown = 5;
while (countdown > 0) {
System.out.println("Countdown: " + countdown);
countdown--; // Decrement to eventually make condition false
}
System.out.println("Blast off!");
// Sum calculation with while loop
int sum = 0;
int number = 1;
while (number <= 10) {
sum += number;
number++;
}
System.out.println("Sum of 1-10: " + sum);
// Input validation using while loop
java.util.Scanner scanner = new java.util.Scanner(System.in);
int userInput = 0;
while (userInput <= 0) {
System.out.print("Enter a positive number: ");
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
if (userInput <= 0) {
System.out.println("Number must be positive. Try again.");
}
} else {
System.out.println("Invalid input. Please enter a number.");
scanner.next(); // Clear invalid input
}
}
System.out.println("You entered: " + userInput);
// Do-while loop - menu system (executes at least once)
int choice;
do {
System.out.println("\\nMenu:");
System.out.println("1. Start game");
System.out.println("2. Load game");
System.out.println("3. Quit");
System.out.print("Choose option: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Starting new game...");
break;
case 2:
System.out.println("Loading game...");
break;
case 3:
System.out.println("Goodbye!");
break;
default:
System.out.println("Invalid choice. Please select 1-3.");
}
} while (choice != 3); // Continue until user chooses to quit
// Infinite loop with break condition
int attempts = 0;
while (true) { // Infinite loop
attempts++;
System.out.println("Attempt #" + attempts);
if (attempts >= 3) {
System.out.println("Maximum attempts reached. Exiting.");
break; // Exit the infinite loop
}
// Simulate some work
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// Handle interruption
}
}
// While loop with continue - skip even numbers
int counter = 0;
while (counter < 10) {
counter++;
if (counter % 2 == 0) {
continue; // Skip even numbers, go to next iteration
}
System.out.println("Odd number: " + counter);
}
scanner.close();
}
}`,
explanation: "While loops provide flexible iteration when the number of repetitions cannot be predetermined, making them essential for interactive programs and dynamic data processing. The key difference from for loops is that while loops separate the condition checking from the iteration logic, offering more control over loop execution. Do-while loops guarantee execution, making them perfect for menus and input validation. Careful management of loop variables is crucial to prevent infinite loops, and break/continue statements provide additional control flow options. Understanding these patterns enables the creation of responsive applications that can handle varying amounts of data and user interactions."
},
{
id: "for-loop",
title: "For Loop",
duration: "15 min",
content: {
description: "For loops repeat a fixed number of times. Syntax: init; condition; increment. Ideal for counting and arrays.",
snippet: "for (int i = 1; i <= 5; i++) {\n System.out.println(i);\n}\n\n// For-each\nfor (String car : cars) {\n System.out.println(car);\n}",
keyPoints: [
"for (init; condition; increment)",
"Init: int i = 1",
"Condition: i <= 5",
"Increment: i++",
"For-each: for (type item : collection)"
]
},
example: `public class Main {
public static void main(String[] args) {
// Basic counting for loop
System.out.println("Counting up:");
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
// Countdown with different increment
System.out.println("\\nCounting down:");
for (int i = 10; i >= 1; i--) {
System.out.println("Count: " + i);
}
// Sum calculation
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("\\nSum of 1-100: " + sum);
// Multiple variables in initialization
System.out.println("\\nFibonacci sequence:");
for (int a = 0, b = 1, count = 1; count <= 10; a = b, b = a + b, count++) {
System.out.print(a + " ");
}
// Nested loops - multiplication table
System.out.println("\\n\\nMultiplication Table:");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.printf("%2d ", i * j); // Right-aligned formatting
}
System.out.println();
}
// Loop with complex condition
System.out.println("\\nEven numbers with complex condition:");
for (int i = 0; i < 20 && i * i < 100; i += 2) {
System.out.print(i + " ");
}
// Loop without initialization (variable declared outside)
int counter = 0;
for (; counter < 5; counter++) {
System.out.println("\\nIteration: " + counter);
}
// Infinite loop with break condition
System.out.println("\\nSimulating work with break:");
for (int attempts = 1; ; attempts++) {
System.out.println("Attempt " + attempts);
if (attempts >= 3) {
System.out.println("Success after " + attempts + " attempts!");
break;
}