{
  "intro": {
    "title": "Java Introduction",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "What is Java?"
      },
      {
        "type": "paragraph",
        "text": "Java is a popular and powerful programming language, created in 1995."
      },
      {
        "type": "paragraph",
        "text": "It is owned by Oracle, and more than <strong>3 billion</strong> devices run Java."
      },
      {
        "type": "paragraph",
        "text": "It is used for:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "Mobile applications (specially Android apps)",
          "Desktop applications",
          "Web applications",
          "Web servers and application servers",
          "Games",
          "Database connection",
          "And much, much more!"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Why Use Java?"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)",
          "It is one of the most popular programming languages in the world",
          "It has a large demand in the current job market",
          "It is easy to learn and simple to use",
          "It is open-source and free",
          "It is secure, fast and powerful",
          "It has huge community support (tens of millions of developers)",
          "Java is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs",
          "As Java is close to <a href=\"../cpp/default.html\">C++</a> and <a href=\"../cs/index.html\">C#</a>, it makes it easy for programmers to switch to Java or vice versa"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "How Java Works — Write Once, Run Anywhere"
      },
      {
        "type": "paragraph",
        "text": "Java compiles your code to <strong>bytecode</strong> (a <code>.class</code> file), not directly to machine code. The <strong>JVM</strong> (Java Virtual Machine) then runs that bytecode on any device. This is Java's famous <em>Write Once, Run Anywhere</em> (WORA) promise."
      },
      {
        "type": "table",
        "headers": ["Tool", "What it does", "Handles"],
        "rows": [
          ["<strong>JDK</strong> — Java Development Kit", "Full developer toolkit — compiler, debugger, and JRE bundled together", "Writing &amp; compiling Java code"],
          ["<strong>JRE</strong> — Java Runtime Environment", "Runs Java programs — includes JVM and the standard class libraries", "Running existing Java apps"],
          ["<strong>JVM</strong> — Java Virtual Machine", "Executes bytecode on your operating system — makes WORA possible", "Cross-platform execution"]
        ]
      },
      {
        "type": "note",
        "text": "<strong>Rule of thumb:</strong> <strong>Develop</strong> with the JDK. <strong>Deploy</strong> with the JRE. The JVM lives inside the JRE."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Java Example"
      },
      {
        "type": "paragraph",
        "text": "Java is often used in everyday programming tasks, like saying hello to a user:"
      },
      {
        "type": "code",
        "language": "java",
        "code": "public class Main {\n    public static void main(String[] args) {\n        System.out.println(\"Hello, World!\");\n        System.out.println(\"Java is fun!\");\n    }\n}\n// Output:\n// Hello, World!\n// Java is fun!"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Get Started"
      },
      {
        "type": "paragraph",
        "text": "By the end of this tutorial, you will know how to write basic Java programs and apply your skills to real-life examples."
      },
      {
        "type": "paragraph",
        "text": "You don't need any prior programming experience - just curiosity and practice!"
      },
      {
        "type": "image",
        "src": "assets/images/java/yt_logo_rgb_dark.png",
        "alt": "Java Tutorial on YouTube"
      }
    ]
  },
  "get-started": {
    "title": "Java Getting Started",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Get Started With Java"
      },
      {
        "type": "paragraph",
        "text": "At Coding Tamilan, you can try Java without installing anything."
      },
      {
        "type": "paragraph",
        "text": "Our Online Java Editor runs directly in your browser, and shows both the code and the result:"
      },
      {
        "type": "paragraph",
        "text": "This editor will be used in the entire tutorial to demonstrate the different aspects of Java."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Java Install"
      },
      {
        "type": "paragraph",
        "text": "However, if you want to run Java on your own computer, follow the instructions below."
      },
      {
        "type": "paragraph",
        "text": "Some PCs might have Java already installed."
      },
      {
        "type": "paragraph",
        "text": "To check if you have Java installed on a Windows PC, search in the start bar for Java or type the following in Command Prompt (cmd.exe):"
      },
      {
        "type": "example",
        "title": "Example",
        "code": "C:\\Users\\Your Name>java -version"
      },
      {
        "type": "paragraph",
        "text": "If Java is installed, you will see something like this (depending on version):"
      },
      {
        "type": "paragraph",
        "text": "If you do not have Java installed on your computer, you can download it at <a href=\"https://www.oracle.com/java/technologies/downloads/\" target=\"_blank\">oracle.com</a>."
      },
      {
        "type": "paragraph",
        "text": "<strong>Note:</strong> In this tutorial, we will write Java code in a text editor. However, it is possible to write Java in an Integrated Development Environment, such as IntelliJ IDEA, Netbeans or Eclipse, which are particularly useful when managing larger collections of Java files."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Java Quickstart"
      },
      {
        "type": "paragraph",
        "text": "In Java, every application begins with a class name, and that class must match the filename."
      },
      {
        "type": "paragraph",
        "text": "Let's create our first Java file, called <code class=\"w3-codespan\">Main.java</code>, which can be done in any text editor \n(like Notepad)."
      },
      {
        "type": "paragraph",
        "text": "The file should contain a \"Hello World\" message, which is written with the \nfollowing code:"
      },
      {
        "type": "paragraph",
        "text": "Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. \nFor now, focus on <strong>how</strong> to run the code above."
      },
      {
        "type": "paragraph",
        "text": "Save the code in Notepad as \"Main.java\". Open Command Prompt (cmd.exe), navigate to the directory where you saved your file, and type \"javac \nMain.java\":"
      },
      {
        "type": "example",
        "title": "Example",
        "code": "C:\\Users\\Your Name>javac Main.java"
      },
      {
        "type": "paragraph",
        "text": "This will compile your code. If there are no errors in the code, the command prompt will take you to the next line. \nNow, type \"java Main\" to run the file:"
      },
      {
        "type": "example",
        "title": "Example",
        "code": "C:\\Users\\Your Name>java Main"
      },
      {
        "type": "paragraph",
        "text": "The output should read:"
      },
      {
        "type": "paragraph",
        "text": "<strong>Congratulations!</strong> You have written and executed your first Java program."
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Main.java — save this file, then compile and run\npublic class Main {\n    public static void main(String[] args) {\n        System.out.println(\"Hello World\");\n    }\n}\n// Compile: javac Main.java\n// Run:     java Main\n// Output:  Hello World"
      },
      {
        "type": "image",
        "src": "assets/images/java/yt_logo_rgb_dark.png",
        "alt": "Java Tutorial on YouTube"
      }
    ]
  },
  "syntax": {
    "title": "Java Syntax",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Syntax"
      },
      {
        "type": "paragraph",
        "text": "In the previous chapter, we created a Java file called <code class=\"w3-codespan\">Main.java</code>, and we used the following code to print \"Hello World\" to the screen:"
      },
      {
        "type": "header",
        "level": 3,
        "text": "Example explained"
      },
      {
        "type": "paragraph",
        "text": "Every line of code that runs in Java must be inside a <code class=\"w3-codespan\">class</code>.  \nThe class name should always start with an uppercase first letter. In our example, we named the class <strong>Main</strong>."
      },
      {
        "type": "paragraph",
        "text": "<strong>Note:</strong> Java is case-sensitive.  \n<code class=\"w3-codespan\">MyClass</code> and <code class=\"w3-codespan\">myclass</code> would be treated as two completely different names."
      },
      {
        "type": "paragraph",
        "text": "The name of the Java file <strong>must match</strong> the class name.  \nSo if your class is called <code class=\"w3-codespan\">Main</code>, the file must be saved as <code class=\"w3-codespan\">Main.java</code>.  \nThis is because Java uses the class name to find and run your code. If the names don't match, Java will give an error and the program will not run."
      },
      {
        "type": "paragraph",
        "text": "When saving the file, save it using the class name and add <code class=\"w3-codespan\">.java</code> to the end of the filename.  \nTo run the example above on your computer, make sure that Java is properly installed:  \nGo to the <a href=\"#/java/get-started\">Get Started Chapter</a> for how to install Java. The output should be:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The main Method"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">main()</code> method is required in every Java program. It is where the program starts running:"
      },
      {
        "type": "paragraph",
        "text": "Any code placed inside the <code class=\"w3-codespan\">main()</code> method will be executed."
      },
      {
        "type": "paragraph",
        "text": "For now, you don't need to understand the keywords <code class=\"w3-codespan\">public</code>, <code class=\"w3-codespan\">static</code>, and <code class=\"w3-codespan\">void</code>.  \nYou will learn about them later in this tutorial.  \nJust remember: <code class=\"w3-codespan\">main()</code> is the starting point of every Java program."
      },
      {
        "type": "header",
        "level": 2,
        "text": "System.out.println()"
      },
      {
        "type": "paragraph",
        "text": "Inside the <code class=\"w3-codespan\">main()</code> method, we can use the <code class=\"w3-codespan\">println()</code> \nmethod to print a line of text to the screen:"
      },
      {
        "type": "note",
        "text": "<p><strong>Note:</strong> The curly braces <code class=\"w3-codespan\">{}</code> mark the beginning and the end of a block of code.</p>\n\n<p><code class=\"w3-codespan\">System.out.println()</code> may look long, but you can think of it as a single command that means:  \n<strong>\"Send this text to the screen.\"</strong></p>\n\n<p>Here's what each part means (you will learn the details later):</p>\n<ul>\n  <li><code class=\"w3-codespan\">System</code> is a built-in Java class.</li>\n  <li><code class=\"w3-codespan\">out</code> is a member of <code class=\"w3-codespan\">System</code>, short for \"output\".</li>\n  <li><code class=\"w3-codespan\">println()</code> is a method, short for \"print line\".</li>\n</ul>\n\n<p>Finally, remember that each Java statement must end with a semicolon (<code class=\"w3-codespan\">;</code>).</p>"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "title": "Interactive Syntax Breakdown",
        "config": {
          "tokens": [
            {
              "text": "public",
              "type": "keyword",
              "explanation": "Access modifier. It means this class is visible to all other classes."
            },
            {
              "text": " "
            },
            {
              "text": "class",
              "type": "keyword",
              "explanation": "Keyword used to declare a class in Java."
            },
            {
              "text": " "
            },
            {
              "text": "Main",
              "type": "class",
              "explanation": "The name of the class. It must match the filename (Main.java)."
            },
            {
              "text": " {"
            },
            {
              "text": "\n  "
            },
            {
              "text": "public",
              "type": "keyword",
              "explanation": "Again, an access modifier. The main method must be public to be run by the JVM."
            },
            {
              "text": " "
            },
            {
              "text": "static",
              "type": "keyword",
              "explanation": "Means this method belongs to the Main class, not an object of the Main class."
            },
            {
              "text": " "
            },
            {
              "text": "void",
              "type": "keyword",
              "explanation": "The return type. It means this method doesn't return any value."
            },
            {
              "text": " "
            },
            {
              "text": "main",
              "type": "method",
              "explanation": "The name of the method. The 'main' method is the entry point of every Java program."
            },
            {
              "text": "(String[] args) {"
            },
            {
              "text": "\n    "
            },
            {
              "text": "System.out.println",
              "type": "method",
              "explanation": "A built-in method used to print text to the screen."
            },
            {
              "text": "(\"Hello World\");"
            },
            {
              "text": "\n  }"
            },
            {
              "text": "\n}"
            }
          ]
        }
      },
      {
        "type": "code",
        "language": "java",
        "code": "public class HelloWorld {\n    public static void main(String[] args) {\n        int age = 25;\n        String name = \"Alice\";\n        System.out.println(\"Name: \" + name + \", Age: \" + age);\n        // Output: Name: Alice, Age: 25\n    }\n}"
      },
      {
        "type": "image",
        "src": "assets/images/java/yt_logo_rgb_dark.png",
        "alt": "Java Tutorial on YouTube"
      }
    ]
  },
  "output": {
    "title": "Java Output / Print",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Print Text"
      },
      {
        "type": "paragraph",
        "text": "You learned from the previous chapter that you can use the <code class=\"w3-codespan\">println()</code> method to output values or print text in Java:"
      },
      {
        "type": "paragraph",
        "text": "You can add as many <code class=\"w3-codespan\">println()</code> methods as you want. Note that it will add a new line for each method:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Double Quotes"
      },
      {
        "type": "paragraph",
        "text": "Text must be wrapped inside double quotations marks <code class=\"w3-codespan\">\"\"</code>."
      },
      {
        "type": "paragraph",
        "text": "If you forget the double quotes, an error occurs:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The Print() Method"
      },
      {
        "type": "paragraph",
        "text": "There is also a <code class=\"w3-codespan\">print()</code> method, which is similar to <code class=\"w3-codespan\">println()</code>."
      },
      {
        "type": "paragraph",
        "text": "The only difference is that it does not insert a new line at the end of the output:"
      },
      {
        "type": "paragraph",
        "text": "Note that we add an extra space (after \"Hello World!\" in the example above) \nfor better readability."
      },
      {
        "type": "note",
        "text": "<p>In this tutorial, we will only use <code class=\"w3-codespan\">println()</code> \nas it makes the code output easier to read.</p>"
      },
      {
        "type": "playground",
        "subtype": "output",
        "title": "Interactive Output Lab",
        "config": {
          "rows": [
            {
              "type": "println",
              "value": "Coding Tamilan"
            },
            {
              "type": "print",
              "value": "Learning "
            },
            {
              "type": "println",
              "value": "Java"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "print vs println vs printf"
      },
      {
        "type": "table",
        "headers": ["Method", "Adds newline?", "Best for"],
        "rows": [
          ["<code>System.out.print()</code>", "No", "Output on the same line"],
          ["<code>System.out.println()</code>", "Yes", "One value per line (most common)"],
          ["<code>System.out.printf()</code>", "No (use <code>%n</code>)", "Formatted output with placeholders"]
        ]
      },
      {
        "type": "code",
        "language": "java",
        "code": "System.out.print(\"Hello \");       // no newline\nSystem.out.println(\"World!\");     // adds newline \u2192 Hello World!\nSystem.out.printf(\"Hi %s! You are %d years old.%n\", \"Alice\", 25);\n// Hi Alice! You are 25 years old.\n\nint x = 42;\nSystem.out.println(\"Value: \" + x);    // Value: 42  (concatenation)\nSystem.out.printf(\"Value: %d%n\", x);  // Value: 42  (formatted)"
      },
      {
        "type": "image",
        "src": "assets/images/java/yt_logo_rgb_dark.png",
        "alt": "Java Tutorial on YouTube"
      }
    ]
  },
  "comments": {
    "title": "Java Comments",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Comments"
      },
      {
        "type": "paragraph",
        "text": "Comments can be used to explain Java code, and to make it more readable. It can also be used to \nprevent execution when testing alternative code."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Single-line Comments"
      },
      {
        "type": "paragraph",
        "text": "Single-line comments start with two forward slashes (<code class=\"w3-codespan\">//</code>)."
      },
      {
        "type": "paragraph",
        "text": "Any text between <code class=\"w3-codespan\">//</code> and the end of the line \nis ignored by Java (will not be executed)."
      },
      {
        "type": "paragraph",
        "text": "This example uses a single-line comment before a line of code:"
      },
      {
        "type": "paragraph",
        "text": "This example uses a single-line comment at the end of a line of code:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Java Multi-line Comments"
      },
      {
        "type": "paragraph",
        "text": "Multi-line comments start with <code class=\"w3-codespan\">/*</code> and ends with <code class=\"w3-codespan\">*/</code>."
      },
      {
        "type": "paragraph",
        "text": "Any text between <code class=\"w3-codespan\">/*</code> and <code class=\"w3-codespan\">*/</code> will be ignored by Java."
      },
      {
        "type": "paragraph",
        "text": "This example uses a multi-line comment (a comment block) to explain the code:"
      },
      {
        "type": "note",
        "text": "<h4>Single or multi-line comments?</h4>\n<p>It's up to you which one you use. Normally, we use <code class=\"w3-codespan\">//</code> for short comments, and <code class=\"w3-codespan\">/* */</code> for longer.</p>"
      },
      {
        "type": "playground",
        "subtype": "output",
        "title": "Multi-line Comment Example",
        "config": {
          "rows": [
            {
              "type": "comment",
              "value": "/* This program prints a welcome message."
            },
            {
              "type": "comment",
              "value": "   Multi-line comments are ignored by Java."
            },
            {
              "type": "comment",
              "value": "   Only the code below will run. */"
            },
            {
              "type": "println",
              "value": "\"Welcome to Java!\""
            },
            {
              "type": "println",
              "value": "\"Comments help explain your code.\""
            }
          ]
        }
      },
      {
        "type": "image",
        "src": "assets/images/java/yt_logo_rgb_dark.png",
        "alt": "Java Tutorial on YouTube"
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Single-line comment: ignored by Java\nint x = 10;  // x stores the value 10\n\n/* Multi-line comment:\n   Explain multiple lines here.\n   Nothing inside runs. */\nSystem.out.println(x);  // 10\n\n// Tip: use comments to disable code temporarily\n// System.out.println(\"This line is skipped\");"
      }
    ]
  },
  "variables": {
    "title": "Java Variables",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Variables"
      },
      {
        "type": "paragraph",
        "text": "Variables are containers for storing data values."
      },
      {
        "type": "paragraph",
        "text": "In Java, there are different <strong>types</strong> of variables, for example:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<code class=\"w3-codespan\">String</code> - stores text, such as \"Hello\". String values are \n surrounded by double quotes",
          "<code class=\"w3-codespan\">int</code> - stores integers (whole numbers), without decimals, such as 123 or -123",
          "<code class=\"w3-codespan\">float</code> - stores floating point numbers, with decimals, such as 19.99 or -19.99",
          "<code class=\"w3-codespan\">char</code> - stores single characters, such as \n 'a' or 'B'. Char values are surrounded by single quotes",
          "<code class=\"w3-codespan\">boolean</code> - stores values with two states: \n true or false"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Declaring (Creating) Variables"
      },
      {
        "type": "paragraph",
        "text": "To create a variable in Java, you need to:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "Choose a <strong>type</strong> (like <code class=\"w3-codespan\">int</code> or <code class=\"w3-codespan\">String</code>)",
          "Give the variable a <strong>name</strong> (like <code class=\"w3-codespan\">x</code>, <code class=\"w3-codespan\">age</code>, or <code class=\"w3-codespan\">name</code>)",
          "Optionally assign it a <strong>value</strong> using <code class=\"w3-codespan\">=</code>"
        ]
      },
      {
        "type": "paragraph",
        "text": "Here's the basic syntax:"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "title": "Variable Syntax Breakdown",
        "config": {
          "tokens": [
            {
              "text": "int",
              "type": "keyword",
              "explanation": "The data type. It tells Java this variable will hold a whole number (integer)."
            },
            {
              "text": " "
            },
            {
              "text": "myAge",
              "type": "variable",
              "explanation": "The variable name. You choose this. It should describe what the value represents. Java uses camelCase by convention."
            },
            {
              "text": " "
            },
            {
              "text": "=",
              "type": "operator",
              "explanation": "The assignment operator. It assigns the value on the right to the variable on the left."
            },
            {
              "text": " "
            },
            {
              "text": "25",
              "type": "value",
              "explanation": "The value being stored in the variable. Since the type is int, this must be a whole number (no decimals)."
            },
            {
              "text": ";",
              "type": "operator",
              "explanation": "The semicolon ends the statement. Every Java statement must end with a semicolon."
            }
          ]
        }
      },
      {
        "type": "paragraph",
        "text": "For example, if you want to store some text, you can use a <code class=\"w3-codespan\">String</code>:"
      },
      {
        "type": "paragraph",
        "text": "To create a variable that should store a number, you can use <code class=\"w3-codespan\">int</code>:"
      },
      {
        "type": "paragraph",
        "text": "You can also declare a variable without assigning the value, and assign the value later:"
      },
      {
        "type": "paragraph",
        "text": "Note that if you assign a new value to an existing variable, it will overwrite the previous value:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Final Variables"
      },
      {
        "type": "paragraph",
        "text": "If you don't want others (or yourself) to overwrite existing values, use the <code class=\"w3-codespan\">final</code> keyword (this will declare the variable as \"final\" or \"constant\", which means unchangeable and read-only):"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Other Types"
      },
      {
        "type": "paragraph",
        "text": "A demonstration of how to declare variables of other types:"
      },
      {
        "type": "note",
        "text": "<p>You will learn more about <a href=\"#/java/data-types\">data types</a> in the next section.</p>"
      },
      {
        "type": "playground",
        "subtype": "variable",
        "title": "Interactive Variable Lab",
        "config": {
          "type": "int",
          "name": "myAge",
          "value": "25"
        }
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Declare then assign separately\nint age;\nage = 25;\n\n// Declare and initialize together\nString name = \"Alice\";\ndouble salary = 45000.50;\nboolean isActive = true;\nchar grade = 'A';\n\n// Multiple vars of same type\nint x = 10, y = 20, z = 30;\n\n// var keyword (Java 10+) \u2014 type inferred\nvar city = \"Chennai\";   // String\nvar count = 100;         // int\nSystem.out.println(city + \" \" + count);  // Chennai 100"
      },
      {
        "type": "image",
        "src": "assets/images/java/yt_logo_rgb_dark.png",
        "alt": "Java Tutorial on YouTube"
      }
    ]
  },
  "data-types": {
    "title": "Java Data Types",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Data Types"
      },
      {
        "type": "paragraph",
        "text": "Every variable in Java must have a <strong>data type</strong> — it tells Java what kind of value the variable can hold and how much memory to reserve."
      },
      {
        "type": "paragraph",
        "text": "Data types are divided into two groups:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<strong>Primitive data types</strong> — the 8 built-in types: <code class=\"w3-codespan\">byte</code>, <code class=\"w3-codespan\">short</code>, <code class=\"w3-codespan\">int</code>, <code class=\"w3-codespan\">long</code>, <code class=\"w3-codespan\">float</code>, <code class=\"w3-codespan\">double</code>, <code class=\"w3-codespan\">boolean</code> and <code class=\"w3-codespan\">char</code>",
          "<strong>Non-primitive data types</strong> — such as <code class=\"w3-codespan\">String</code>, Arrays, and Classes (you will learn these in later chapters)"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Primitive Data Types"
      },
      {
        "type": "paragraph",
        "text": "A <strong>primitive</strong> type stores a simple value directly in memory. There are exactly 8 of them in Java. Click each one below to explore its size, range, and usage:"
      },
      {
        "type": "playground",
        "subtype": "data-type-explorer"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Declaring Primitive Variables"
      },
      {
        "type": "paragraph",
        "text": "Here is how you declare variables for each of the common primitive types:"
      },
      {
        "type": "playground",
        "subtype": "output",
        "title": "Primitive Type Declarations",
        "config": {
          "rows": [
            {
              "type": "comment",
              "value": "// Integer types"
            },
            {
              "type": "println",
              "value": "\"byte:    \" + (byte) 100"
            },
            {
              "type": "println",
              "value": "\"int:     \" + 2147483647"
            },
            {
              "type": "println",
              "value": "\"long:    \" + 8000000000L"
            },
            {
              "type": "comment",
              "value": "// Decimal types"
            },
            {
              "type": "println",
              "value": "\"float:   \" + 3.14f"
            },
            {
              "type": "println",
              "value": "\"double:  \" + 19.99"
            },
            {
              "type": "comment",
              "value": "// Other primitives"
            },
            {
              "type": "println",
              "value": "\"boolean: \" + true"
            },
            {
              "type": "println",
              "value": "\"char:    \" + 'A'"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Primitive vs Non-Primitive"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<strong>Primitive types</strong> always have a value — they can never be <code class=\"w3-codespan\">null</code>",
          "<strong>Non-primitive types</strong> (like <code class=\"w3-codespan\">String</code>) can be <code class=\"w3-codespan\">null</code> — meaning they reference no object",
          "Primitives store values <strong>directly</strong>; non-primitives store a <strong>reference</strong> (memory address) to an object",
          "Non-primitive types have built-in <strong>methods</strong> you can call (e.g. <code class=\"w3-codespan\">\"hello\".length()</code>)"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Types Are Fixed"
      },
      {
        "type": "paragraph",
        "text": "Once a variable is declared with a type, it <strong>cannot change</strong> to another type. Java is a <em>statically typed</em> language — the type is checked at compile time, not at runtime."
      },
      {
        "type": "note",
        "text": "<p>If you need to convert a value from one type to another, use <strong>type casting</strong> — you will learn about this in the next chapter.</p>"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "title": "Type Declaration Anatomy",
        "config": {
          "tokens": [
            {
              "text": "double",
              "type": "keyword",
              "explanation": "The data type. Tells Java this variable holds a decimal number with high precision."
            },
            {
              "text": " "
            },
            {
              "text": "price",
              "type": "variable",
              "explanation": "The variable name. Choose a meaningful name that describes what the value represents."
            },
            {
              "text": " "
            },
            {
              "text": "=",
              "type": "operator",
              "explanation": "The assignment operator. Assigns the value on the right to the variable on the left."
            },
            {
              "text": " "
            },
            {
              "text": "19.99",
              "type": "value",
              "explanation": "The literal value being stored. Because the type is double, decimals are allowed."
            },
            {
              "text": ";",
              "type": "operator",
              "explanation": "Every Java statement ends with a semicolon."
            }
          ]
        }
      },
      {
        "type": "code",
        "language": "java",
        "code": "byte   small  = 127;              // -128 to 127\nshort  medium = 32767;            // -32,768 to 32,767\nint    num    = 2_000_000;        // underscores improve readability\nlong   big    = 9_876_543_210L;   // append L for long\nfloat  price  = 9.99f;            // append f for float\ndouble pi     = 3.14159265358979; // 15-16 decimal digits\nboolean flag  = true;\nchar   ch     = 'J';\n\nSystem.out.println(Integer.MAX_VALUE);        // 2147483647\nSystem.out.println(Double.MIN_VALUE);         // 4.9E-324\nSystem.out.println(Character.isLetter(ch));   // true"
      },
      {
        "type": "image",
        "src": "assets/images/java/yt_logo_rgb_dark.png",
        "alt": "Java Tutorial on YouTube"
      }
    ]
  },
  "type-casting": {
    "title": "Java Type Casting",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Type Casting"
      },
      {
        "type": "paragraph",
        "text": "<strong>Type casting</strong> means converting a value from one data type into another. Java has two kinds — one happens automatically, and one you must do yourself."
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<strong>Widening Casting</strong> (automatic) — smaller type → larger type. Java does this for you because no data can be lost.",
          "<strong>Narrowing Casting</strong> (manual) — larger type → smaller type. You must write it explicitly because data <em>may</em> be lost (e.g. decimals are truncated)."
        ]
      },
      {
        "type": "playground",
        "subtype": "type-casting"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Widening Casting"
      },
      {
        "type": "paragraph",
        "text": "Widening casting is <strong>automatic</strong> — Java converts the value without any extra syntax. It is safe because a larger type can always hold a smaller type's value without losing any information."
      },
      {
        "type": "playground",
        "subtype": "output",
        "title": "Widening: int → double",
        "config": {
          "rows": [
            {
              "type": "comment",
              "value": "// int is automatically widened to double"
            },
            {
              "type": "println",
              "value": "\"int value:    \" + 9"
            },
            {
              "type": "println",
              "value": "\"double value: \" + 9.0"
            }
          ]
        }
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "title": "Widening Cast Anatomy",
        "config": {
          "tokens": [
            {
              "text": "double",
              "type": "keyword",
              "explanation": "The target (larger) type. Java will automatically accept the int value here."
            },
            {
              "text": " "
            },
            {
              "text": "myDouble",
              "type": "variable",
              "explanation": "The new variable that will hold the widened value."
            },
            {
              "text": " "
            },
            {
              "text": "=",
              "type": "operator",
              "explanation": "Assignment operator. Java automatically converts the int on the right to double."
            },
            {
              "text": " "
            },
            {
              "text": "myInt",
              "type": "variable",
              "explanation": "The int variable being widened. No cast syntax needed — Java handles it automatically."
            },
            {
              "text": ";",
              "type": "operator",
              "explanation": "End of statement."
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Narrowing Casting"
      },
      {
        "type": "paragraph",
        "text": "Narrowing casting is <strong>manual</strong> — you must place the target type in parentheses <code class=\"w3-codespan\">(targetType)</code> before the value. This tells Java you are aware data might be lost."
      },
      {
        "type": "note",
        "text": "<p><strong>Data loss example:</strong> Casting <code class=\"w3-codespan\">9.78</code> (double) to <code class=\"w3-codespan\">int</code> gives <code class=\"w3-codespan\">9</code> — the decimal part <code class=\"w3-codespan\">.78</code> is silently dropped (truncated, not rounded).</p>"
      },
      {
        "type": "playground",
        "subtype": "output",
        "title": "Narrowing: double → int",
        "config": {
          "rows": [
            {
              "type": "comment",
              "value": "// Manual cast required: (int) truncates the decimal"
            },
            {
              "type": "println",
              "value": "\"double value: \" + 9.78"
            },
            {
              "type": "println",
              "value": "\"int value:    \" + 9"
            }
          ]
        }
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "title": "Narrowing Cast Anatomy",
        "config": {
          "tokens": [
            {
              "text": "int",
              "type": "keyword",
              "explanation": "The target (smaller) type we want to convert to."
            },
            {
              "text": " "
            },
            {
              "text": "myInt",
              "type": "variable",
              "explanation": "The new variable that will hold the narrowed value."
            },
            {
              "text": " "
            },
            {
              "text": "=",
              "type": "operator",
              "explanation": "Assignment operator."
            },
            {
              "text": " "
            },
            {
              "text": "(int)",
              "type": "keyword",
              "explanation": "The cast operator. Placed in parentheses before the value, it tells Java to convert to int — and that you accept any possible data loss."
            },
            {
              "text": " "
            },
            {
              "text": "myDouble",
              "type": "variable",
              "explanation": "The double variable being narrowed. The decimal part will be truncated (cut off), not rounded."
            },
            {
              "text": ";",
              "type": "operator",
              "explanation": "End of statement."
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Real-Life Example"
      },
      {
        "type": "paragraph",
        "text": "Imagine a game where a player scores <strong>700 points</strong> out of a maximum of <strong>1000</strong>. To display the score as a percentage with decimals, we need to cast to <code class=\"w3-codespan\">double</code> before dividing — otherwise Java performs integer division and drops the decimal:"
      },
      {
        "type": "playground",
        "subtype": "output",
        "title": "Score Percentage Calculator",
        "config": {
          "rows": [
            {
              "type": "comment",
              "value": "// Without cast: integer division loses the decimal"
            },
            {
              "type": "println",
              "value": "\"Without cast: \" + (700 / 1000 * 100) + \"%\""
            },
            {
              "type": "comment",
              "value": "// With cast: correct percentage"
            },
            {
              "type": "println",
              "value": "\"With cast:    \" + ((double) 700 / 1000 * 100) + \"%\""
            }
          ]
        }
      },
      {
        "type": "image",
        "src": "assets/images/java/yt_logo_rgb_dark.png",
        "alt": "Java Tutorial on YouTube"
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Widening (automatic): smaller → larger type\nint myInt = 9;\ndouble myDouble = myInt;   // int automatically becomes double\nSystem.out.println(myDouble);  // 9.0\n\n// Narrowing (manual): larger → smaller type (decimal truncated)\ndouble pi = 3.14159;\nint piInt = (int) pi;\nSystem.out.println(piInt);  // 3\n\n// Real-life use: percentage calculation\nint score = 700, maxScore = 1000;\ndouble pct = (double) score / maxScore * 100;\nSystem.out.println(pct + \"%\");  // 70.0%"
      }
    ]
  },
  "operators": {
    "title": "Java Operators",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Operators"
      },
      {
        "type": "paragraph",
        "text": "<strong>Operators</strong> are symbols that tell Java to perform an operation on variables or values. Java groups them into four main categories:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<strong>Arithmetic</strong> — perform math: <code class=\"w3-codespan\">+</code> <code class=\"w3-codespan\">-</code> <code class=\"w3-codespan\">*</code> <code class=\"w3-codespan\">/</code> <code class=\"w3-codespan\">%</code> <code class=\"w3-codespan\">++</code> <code class=\"w3-codespan\">--</code>",
          "<strong>Comparison</strong> — compare two values, always returns <code class=\"w3-codespan\">true</code> or <code class=\"w3-codespan\">false</code>: <code class=\"w3-codespan\">==</code> <code class=\"w3-codespan\">!=</code> <code class=\"w3-codespan\">&gt;</code> <code class=\"w3-codespan\">&lt;</code> <code class=\"w3-codespan\">&gt;=</code> <code class=\"w3-codespan\">&lt;=</code>",
          "<strong>Logical</strong> — combine boolean expressions: <code class=\"w3-codespan\">&amp;&amp;</code> <code class=\"w3-codespan\">||</code> <code class=\"w3-codespan\">!</code>",
          "<strong>Assignment</strong> — assign or update a variable's value: <code class=\"w3-codespan\">=</code> <code class=\"w3-codespan\">+=</code> <code class=\"w3-codespan\">-=</code> <code class=\"w3-codespan\">*=</code> <code class=\"w3-codespan\">/=</code> <code class=\"w3-codespan\">%=</code>"
        ]
      },
      {
        "type": "playground",
        "subtype": "operators"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Arithmetic Operators"
      },
      {
        "type": "paragraph",
        "text": "Arithmetic operators perform standard math operations between two values. The <code class=\"w3-codespan\">%</code> (modulus) operator returns the <strong>remainder</strong> after division — useful for checking if a number is even or odd."
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "title": "Arithmetic Expression Anatomy",
        "config": {
          "tokens": [
            {
              "text": "int",
              "type": "keyword",
              "explanation": "Data type. The result of adding two ints is also an int."
            },
            {
              "text": " "
            },
            {
              "text": "result",
              "type": "variable",
              "explanation": "Variable that stores the outcome of the expression."
            },
            {
              "text": " "
            },
            {
              "text": "=",
              "type": "operator",
              "explanation": "Assignment operator — stores the computed value into result."
            },
            {
              "text": " "
            },
            {
              "text": "a",
              "type": "variable",
              "explanation": "The left operand — the first number in the operation."
            },
            {
              "text": " "
            },
            {
              "text": "+",
              "type": "operator",
              "explanation": "The arithmetic operator. Here it adds the values of a and b together."
            },
            {
              "text": " "
            },
            {
              "text": "b",
              "type": "variable",
              "explanation": "The right operand — the second number in the operation."
            },
            {
              "text": ";",
              "type": "operator",
              "explanation": "Semicolon ends the statement."
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Comparison Operators"
      },
      {
        "type": "paragraph",
        "text": "Comparison operators compare two values and always produce a <code class=\"w3-codespan\">boolean</code> result — either <code class=\"w3-codespan\">true</code> or <code class=\"w3-codespan\">false</code>. They are the building blocks of conditions in <code class=\"w3-codespan\">if</code> statements and loops."
      },
      {
        "type": "note",
        "text": "<p>Don't confuse <code class=\"w3-codespan\">==</code> (compare) with <code class=\"w3-codespan\">=</code> (assign). Using <code class=\"w3-codespan\">=</code> where you meant <code class=\"w3-codespan\">==</code> is one of the most common beginner mistakes in Java.</p>"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Logical Operators"
      },
      {
        "type": "paragraph",
        "text": "Logical operators are used to combine or invert boolean expressions. They are essential for writing complex conditions:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<code class=\"w3-codespan\">&amp;&amp;</code> (AND) — <code class=\"w3-codespan\">true</code> only when <strong>both</strong> sides are true",
          "<code class=\"w3-codespan\">||</code> (OR) — <code class=\"w3-codespan\">true</code> when <strong>at least one</strong> side is true",
          "<code class=\"w3-codespan\">!</code> (NOT) — <strong>inverts</strong> the boolean value: <code class=\"w3-codespan\">!true</code> → <code class=\"w3-codespan\">false</code>"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Assignment Operators"
      },
      {
        "type": "paragraph",
        "text": "Assignment operators are shorthand for updating a variable. Instead of writing <code class=\"w3-codespan\">x = x + 5</code>, you can write <code class=\"w3-codespan\">x += 5</code>. They work for all arithmetic operations."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Compound Assignment Operators"
      },
      {
        "type": "table",
        "headers": ["Operator", "Example", "Equivalent to", "Meaning"],
        "rows": [
          ["<code>+=</code>", "<code>x += 5</code>", "<code>x = x + 5</code>", "Add and assign"],
          ["<code>-=</code>", "<code>x -= 3</code>", "<code>x = x - 3</code>", "Subtract and assign"],
          ["<code>*=</code>", "<code>x *= 2</code>", "<code>x = x * 2</code>", "Multiply and assign"],
          ["<code>/=</code>", "<code>x /= 4</code>", "<code>x = x / 4</code>", "Divide and assign"],
          ["<code>%=</code>", "<code>x %= 3</code>", "<code>x = x % 3</code>", "Modulus and assign"]
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Ternary Operator"
      },
      {
        "type": "paragraph",
        "text": "The <strong>ternary operator</strong> <code class=\"w3-codespan\">? :</code> is a one-line shorthand for a simple <code>if-else</code>. Syntax: <code>condition ? valueIfTrue : valueIfFalse</code>"
      },
      {
        "type": "code",
        "language": "java",
        "code": "int age = 20;\nString status = (age >= 18) ? \"Adult\" : \"Minor\";\nSystem.out.println(status);   // Adult\n\n// Same logic written as if-else:\nif (age >= 18) {\n    status = \"Adult\";\n} else {\n    status = \"Minor\";\n}\n\n// Another example — find the larger number\nint a = 10, b = 25;\nint max = (a > b) ? a : b;\nSystem.out.println(\"Max: \" + max);  // Max: 25"
      },
      {
        "type": "image",
        "src": "assets/images/java/yt_logo_rgb_dark.png",
        "alt": "Java Tutorial on YouTube"
      }
    ]
  },
  "strings": {
    "title": "Java Strings",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Strings"
      },
      {
        "type": "intro",
        "text": "A <code class=\"w3-codespan\">String</code> stores text — any sequence of characters surrounded by double quotes. Unlike primitive types, String is an <strong>object</strong> with built-in methods you can call on it."
      },
      {
        "type": "playground",
        "subtype": "strings"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Declaring a String"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "config": {
          "title": "String Declaration",
          "tokens": [
            {
              "text": "String",
              "type": "keyword",
              "tip": "The String class — note the capital S"
            },
            {
              "text": " name",
              "type": "variable",
              "tip": "Variable name"
            },
            {
              "text": " = ",
              "type": "operator"
            },
            {
              "text": "\"Hello, Java!\"",
              "type": "value",
              "tip": "The text value — always wrapped in double quotes"
            },
            {
              "text": ";",
              "type": "punctuation"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Common String Methods"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<code class=\"w3-codespan\">length()</code> — number of characters",
          "<code class=\"w3-codespan\">toUpperCase()</code> / <code class=\"w3-codespan\">toLowerCase()</code> — change case",
          "<code class=\"w3-codespan\">trim()</code> — remove leading/trailing whitespace",
          "<code class=\"w3-codespan\">charAt(i)</code> — character at index <code class=\"w3-codespan\">i</code>",
          "<code class=\"w3-codespan\">indexOf(s)</code> — position of first match, or -1",
          "<code class=\"w3-codespan\">contains(s)</code> — returns <code class=\"w3-codespan\">true</code> if match found",
          "<code class=\"w3-codespan\">substring(i)</code> — new string from index <code class=\"w3-codespan\">i</code> to end",
          "<code class=\"w3-codespan\">replace(a, b)</code> — swap all occurrences of <code class=\"w3-codespan\">a</code> with <code class=\"w3-codespan\">b</code>"
        ]
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "String methods in action",
          "rows": [
            {
              "code": "String txt = \"Hello, Java World!\";",
              "output": ""
            },
            {
              "code": "System.out.println(txt.length());",
              "output": "18"
            },
            {
              "code": "System.out.println(txt.toUpperCase());",
              "output": "HELLO, JAVA WORLD!"
            },
            {
              "code": "System.out.println(txt.indexOf(\"Java\"));",
              "output": "7"
            },
            {
              "code": "System.out.println(txt.replace(\"Java\", \"Tamil\"));",
              "output": "Hello, Tamil World!"
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "<strong>String indexes start at 0</strong>, just like arrays. The first character is at index 0, the second at index 1, and so on. Use <code>charAt(0)</code> to get the first character."
      },
      {
        "type": "code",
        "language": "java",
        "code": "String s = \"Hello, Java!\";\nSystem.out.println(s.length());           // 12\nSystem.out.println(s.toUpperCase());      // HELLO, JAVA!\nSystem.out.println(s.substring(7, 11));   // Java\nSystem.out.println(s.contains(\"Java\"));   // true\nSystem.out.println(s.replace(\"Java\", \"World\")); // Hello, World!\nSystem.out.println(s.charAt(0));          // H\n\n// Comparing \u2014 always use .equals()\nString a = \"hello\", b = \"hello\";\nSystem.out.println(a.equals(b));                  // true \u2713\nSystem.out.println(a.equalsIgnoreCase(\"HELLO\")); // true"
      }
    ]
  },
  "math": {
    "title": "Java Math",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Math Class"
      },
      {
        "type": "intro",
        "text": "The <code class=\"w3-codespan\">Math</code> class provides ready-to-use methods for common mathematical operations — no imports needed, just call <code class=\"w3-codespan\">Math.methodName()</code>."
      },
      {
        "type": "playground",
        "subtype": "math"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Key Math Methods"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<code class=\"w3-codespan\">Math.max(x, y)</code> — returns the larger value",
          "<code class=\"w3-codespan\">Math.min(x, y)</code> — returns the smaller value",
          "<code class=\"w3-codespan\">Math.abs(x)</code> — removes the sign, always returns positive",
          "<code class=\"w3-codespan\">Math.sqrt(x)</code> — square root of x",
          "<code class=\"w3-codespan\">Math.pow(base, exp)</code> — base raised to the power of exp",
          "<code class=\"w3-codespan\">Math.round(x)</code> — rounds to nearest integer",
          "<code class=\"w3-codespan\">Math.ceil(x)</code> — always rounds up",
          "<code class=\"w3-codespan\">Math.floor(x)</code> — always rounds down",
          "<code class=\"w3-codespan\">Math.random()</code> — random double between 0.0 and 1.0"
        ]
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Math methods",
          "rows": [
            {
              "code": "System.out.println(Math.max(15, 42));",
              "output": "42"
            },
            {
              "code": "System.out.println(Math.abs(-64));",
              "output": "64"
            },
            {
              "code": "System.out.println(Math.sqrt(144));",
              "output": "12.0"
            },
            {
              "code": "System.out.println(Math.pow(2, 8));",
              "output": "256.0"
            },
            {
              "code": "System.out.println(Math.round(4.6));",
              "output": "5"
            }
          ]
        }
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Random number 0–99",
          "rows": [
            {
              "code": "int rand = (int)(Math.random() * 100);",
              "output": ""
            },
            {
              "code": "System.out.println(rand);",
              "output": "73  ← changes every run"
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "<strong>Math.random()</strong> returns a different value every time the program runs. To get a random integer between 0 and N, use <code>(int)(Math.random() * N)</code>."
      },
      {
        "type": "code",
        "language": "java",
        "code": "System.out.println(Math.max(15, 42));   // 42\nSystem.out.println(Math.min(15, 42));   // 15\nSystem.out.println(Math.abs(-64));      // 64\nSystem.out.println(Math.sqrt(144));     // 12.0\nSystem.out.println(Math.pow(2, 10));    // 1024.0\nSystem.out.println(Math.round(4.6));    // 5\nSystem.out.println(Math.ceil(4.2));     // 5.0\nSystem.out.println(Math.floor(4.9));    // 4.0\n\n// Random integer 0–99\nint rand = (int)(Math.random() * 100);\nSystem.out.println(rand);  // e.g. 73 (changes every run)"
      }
    ]
  },
  "booleans": {
    "title": "Java Booleans",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Booleans"
      },
      {
        "type": "paragraph",
        "text": "A <code class=\"w3-codespan\">boolean</code> is the simplest data type in Java — it can only ever be <code class=\"w3-codespan\">true</code> or <code class=\"w3-codespan\">false</code>. Booleans are the foundation of every decision your program makes."
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "Is the user logged in? → <code class=\"w3-codespan\">boolean isLoggedIn = true;</code>",
          "Is the light on? → <code class=\"w3-codespan\">boolean isLightOn = false;</code>",
          "Is it raining? → <code class=\"w3-codespan\">boolean isRaining = true;</code>"
        ]
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "title": "Boolean Declaration Anatomy",
        "config": {
          "tokens": [
            {
              "text": "boolean",
              "type": "keyword",
              "explanation": "The data type. A boolean can only hold true or false — nothing else."
            },
            {
              "text": " "
            },
            {
              "text": "isLoggedIn",
              "type": "variable",
              "explanation": "The variable name. Boolean names usually start with 'is', 'has', or 'can' to make them read like a yes/no question."
            },
            {
              "text": " "
            },
            {
              "text": "=",
              "type": "operator",
              "explanation": "Assignment operator."
            },
            {
              "text": " "
            },
            {
              "text": "true",
              "type": "value",
              "explanation": "The boolean value. Only two options exist: true or false (always lowercase in Java)."
            },
            {
              "text": ";",
              "type": "operator",
              "explanation": "End of statement."
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Boolean Expressions"
      },
      {
        "type": "paragraph",
        "text": "In practice, booleans are rarely written as literals. They are almost always the <strong>result of an expression</strong> — a comparison that Java evaluates to <code class=\"w3-codespan\">true</code> or <code class=\"w3-codespan\">false</code>:"
      },
      {
        "type": "playground",
        "subtype": "output",
        "title": "Boolean Expressions",
        "config": {
          "rows": [
            {
              "type": "comment",
              "value": "// Direct boolean values"
            },
            {
              "type": "println",
              "value": "\"true:  \" + true"
            },
            {
              "type": "println",
              "value": "\"false: \" + false"
            },
            {
              "type": "comment",
              "value": "// Boolean from a comparison expression"
            },
            {
              "type": "println",
              "value": "\"10 > 5:  \" + (10 > 5)"
            },
            {
              "type": "println",
              "value": "\"10 < 5:  \" + (10 < 5)"
            },
            {
              "type": "println",
              "value": "\"10 == 10: \" + (10 == 10)"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Real-Life Example: Voting Age"
      },
      {
        "type": "paragraph",
        "text": "Booleans shine when you use them to make decisions. Here we check if a person is old enough to vote (age ≥ 18) and print a different message depending on the result:"
      },
      {
        "type": "playground",
        "subtype": "output",
        "title": "Voting Age Checker",
        "config": {
          "rows": [
            {
              "type": "comment",
              "value": "// Change the age and run again to see a different result"
            },
            {
              "type": "println",
              "value": "\"Age: 20\""
            },
            {
              "type": "println",
              "value": "\"Old enough to vote: \" + (20 >= 18)"
            },
            {
              "type": "println",
              "value": "\"---\""
            },
            {
              "type": "println",
              "value": "\"Age: 15\""
            },
            {
              "type": "println",
              "value": "\"Old enough to vote: \" + (15 >= 18)"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Combining Booleans"
      },
      {
        "type": "paragraph",
        "text": "You can combine boolean expressions using <strong>logical operators</strong> to build more complex conditions:"
      },
      {
        "type": "playground",
        "subtype": "output",
        "title": "Logical Operators with Booleans",
        "config": {
          "rows": [
            {
              "type": "comment",
              "value": "// AND (&&): both must be true"
            },
            {
              "type": "println",
              "value": "\"18 >= 18 && 18 < 65: \" + (18 >= 18 && 18 < 65)"
            },
            {
              "type": "comment",
              "value": "// OR (||): at least one must be true"
            },
            {
              "type": "println",
              "value": "\"isStudent || isSenior: \" + (true || false)"
            },
            {
              "type": "comment",
              "value": "// NOT (!): inverts the result"
            },
            {
              "type": "println",
              "value": "\"!false: \" + !false"
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "<p>Booleans are the foundation of <strong>all decision-making</strong> in Java. Every <code class=\"w3-codespan\">if</code> statement, every loop condition, every comparison — they all produce or consume a boolean value. You will learn how to use them in <a href=\"#/java/if-else\"><code class=\"w3-codespan\">if...else</code></a> in the next chapter.</p>"
      },
      {
        "type": "code",
        "language": "java",
        "code": "int age = 20;\nboolean isAdult   = (age >= 18);  // true\nboolean hasTicket = true;\n\n// Logical operators\nboolean canEnter = isAdult && hasTicket;  // true (both true)\nboolean eitherOr = isAdult || hasTicket;  // true (at least one)\nboolean notKid   = !isAdult;             // false (inverts true)\n\nSystem.out.println(isAdult);    // true\nSystem.out.println(canEnter);   // true\nSystem.out.println(notKid);     // false"
      }
    ]
  },
  "if-else": {
    "title": "Java If ... Else",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Conditions and If Statements"
      },
      {
        "type": "intro",
        "text": "Conditions let your program <strong>make decisions</strong> — running different code depending on whether something is true or false."
      },
      {
        "type": "paragraph",
        "text": "Think of it like real life: <em>\"If it rains, take an umbrella. Otherwise, wear sunglasses.\"</em> Your program does the same — it checks a condition, then takes the right path."
      },
      {
        "type": "playground",
        "subtype": "if-else"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The if Statement"
      },
      {
        "type": "paragraph",
        "text": "Use <code class=\"w3-codespan\">if</code> to run a block of code only when a condition is <code class=\"w3-codespan\">true</code>. If the condition is <code class=\"w3-codespan\">false</code>, the block is skipped entirely."
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "config": {
          "title": "if Statement",
          "tokens": [
            {
              "text": "if",
              "type": "keyword",
              "tip": "Keyword that starts a conditional check"
            },
            {
              "text": " ",
              "type": "plain"
            },
            {
              "text": "(",
              "type": "punctuation",
              "tip": "Opening parenthesis — condition goes inside"
            },
            {
              "text": "age",
              "type": "variable",
              "tip": "The variable being checked"
            },
            {
              "text": " >= ",
              "type": "operator",
              "tip": "Comparison operator: greater than or equal to"
            },
            {
              "text": "18",
              "type": "value",
              "tip": "The value to compare against"
            },
            {
              "text": ")",
              "type": "punctuation",
              "tip": "Closing parenthesis"
            },
            {
              "text": " {",
              "type": "punctuation",
              "tip": "Opening brace — code block starts here"
            },
            {
              "text": "\n  System.out.println(...);",
              "type": "plain"
            },
            {
              "text": "\n}",
              "type": "punctuation",
              "tip": "Closing brace — code block ends here"
            }
          ]
        }
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "if Statement",
          "rows": [
            {
              "code": "int age = 20;",
              "output": ""
            },
            {
              "code": "if (age >= 18) {",
              "output": ""
            },
            {
              "code": "  System.out.println(\"You can vote!\");",
              "output": "You can vote!"
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "The else Statement"
      },
      {
        "type": "paragraph",
        "text": "Add an <code class=\"w3-codespan\">else</code> block to handle the case when the condition is <code class=\"w3-codespan\">false</code>. Only one of the two blocks will ever run — never both."
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "if...else Statement",
          "rows": [
            {
              "code": "int age = 15;",
              "output": ""
            },
            {
              "code": "if (age >= 18) {",
              "output": ""
            },
            {
              "code": "  System.out.println(\"You can vote!\");",
              "output": ""
            },
            {
              "code": "} else {",
              "output": ""
            },
            {
              "code": "  System.out.println(\"Too young to vote.\");",
              "output": "Too young to vote."
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "The else if Statement"
      },
      {
        "type": "paragraph",
        "text": "When you need to check more than two possibilities, chain <code class=\"w3-codespan\">else if</code> blocks. Java checks each condition from top to bottom and runs the first one that is <code class=\"w3-codespan\">true</code>."
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "if...else if...else",
          "rows": [
            {
              "code": "int score = 82;",
              "output": ""
            },
            {
              "code": "if (score >= 90) {",
              "output": ""
            },
            {
              "code": "  System.out.println(\"Grade: A\");",
              "output": ""
            },
            {
              "code": "} else if (score >= 75) {",
              "output": ""
            },
            {
              "code": "  System.out.println(\"Grade: B\");",
              "output": "Grade: B"
            },
            {
              "code": "} else if (score >= 50) {",
              "output": ""
            },
            {
              "code": "  System.out.println(\"Grade: C\");",
              "output": ""
            },
            {
              "code": "} else {",
              "output": ""
            },
            {
              "code": "  System.out.println(\"Grade: F\");",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Conditions Use Comparison Operators"
      },
      {
        "type": "paragraph",
        "text": "Every <code class=\"w3-codespan\">if</code> condition evaluates to <code class=\"w3-codespan\">true</code> or <code class=\"w3-codespan\">false</code>. You build conditions using comparison operators:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<code class=\"w3-codespan\">a == b</code> — Equal to",
          "<code class=\"w3-codespan\">a != b</code> — Not equal to",
          "<code class=\"w3-codespan\">a &gt; b</code> — Greater than",
          "<code class=\"w3-codespan\">a &lt; b</code> — Less than",
          "<code class=\"w3-codespan\">a &gt;= b</code> — Greater than or equal to",
          "<code class=\"w3-codespan\">a &lt;= b</code> — Less than or equal to"
        ]
      },
      {
        "type": "note",
        "text": "<strong>Always use curly braces <code>{ }</code></strong> even for single-line if blocks. Without them, only the very next line belongs to the <code>if</code> — a common source of bugs."
      },
      {
        "type": "code",
        "language": "java",
        "code": "int score = 75;\nif (score &gt;= 90) {\n    System.out.println(\"A\");\n} else if (score &gt;= 80) {\n    System.out.println(\"B\");\n} else if (score &gt;= 70) {\n    System.out.println(\"C\");\n} else {\n    System.out.println(\"Below C\");\n}\n// Output: C\n\n// Ternary shorthand\nString result = (score &gt;= 50) ? \"Pass\" : \"Fail\";\nSystem.out.println(result);  // Pass"
      }
    ]
  },
  "switch": {
    "title": "Java Switch",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Switch Statements"
      },
      {
        "type": "intro",
        "text": "When you have <strong>many specific values</strong> to check, a <code class=\"w3-codespan\">switch</code> statement is cleaner and more readable than a long chain of <code class=\"w3-codespan\">if...else if</code>."
      },
      {
        "type": "paragraph",
        "text": "Think of it like a TV remote: press button <strong>1</strong> → Channel 1, press <strong>2</strong> → Channel 2, press anything else → nothing happens. Java evaluates the expression once, then jumps directly to the matching <code class=\"w3-codespan\">case</code>."
      },
      {
        "type": "playground",
        "subtype": "switch"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Switch Statement Syntax"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "config": {
          "title": "switch Statement",
          "tokens": [
            {
              "text": "switch",
              "type": "keyword",
              "tip": "Keyword that starts a switch statement"
            },
            {
              "text": " (",
              "type": "punctuation"
            },
            {
              "text": "day",
              "type": "variable",
              "tip": "The variable being matched against cases"
            },
            {
              "text": ") {",
              "type": "punctuation",
              "tip": "Opening brace — cases go inside"
            },
            {
              "text": "\n  case ",
              "type": "keyword",
              "tip": "Each case checks for a specific value"
            },
            {
              "text": "1",
              "type": "value",
              "tip": "The exact value this case matches"
            },
            {
              "text": ":",
              "type": "punctuation"
            },
            {
              "text": "\n    System.out.println(...);",
              "type": "plain"
            },
            {
              "text": "\n    break",
              "type": "keyword",
              "tip": "Exits the switch — prevents fall-through to the next case"
            },
            {
              "text": ";",
              "type": "punctuation"
            },
            {
              "text": "\n  default",
              "type": "keyword",
              "tip": "Runs if no case matches — like the final else"
            },
            {
              "text": ":",
              "type": "punctuation"
            },
            {
              "text": "\n    System.out.println(...);",
              "type": "plain"
            },
            {
              "text": "\n}",
              "type": "punctuation",
              "tip": "Closing brace — end of switch block"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "How It Works"
      },
      {
        "type": "list",
        "ordered": true,
        "items": [
          "Java evaluates the <code class=\"w3-codespan\">switch</code> expression <strong>once</strong>.",
          "It compares the result against each <code class=\"w3-codespan\">case</code> value from top to bottom.",
          "When a match is found, that block of code runs.",
          "<code class=\"w3-codespan\">break</code> exits the switch — without it, Java continues into the next case (<strong>fall-through</strong>).",
          "<code class=\"w3-codespan\">default</code> runs if no case matches — it is optional."
        ]
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Day of Week",
          "rows": [
            {
              "code": "int day = 3;",
              "output": ""
            },
            {
              "code": "switch (day) {",
              "output": ""
            },
            {
              "code": "  case 1: System.out.println(\"Monday\"); break;",
              "output": ""
            },
            {
              "code": "  case 2: System.out.println(\"Tuesday\"); break;",
              "output": ""
            },
            {
              "code": "  case 3: System.out.println(\"Wednesday\"); break;",
              "output": "Wednesday"
            },
            {
              "code": "  case 4: System.out.println(\"Thursday\"); break;",
              "output": ""
            },
            {
              "code": "  case 5: System.out.println(\"Friday\"); break;",
              "output": ""
            },
            {
              "code": "  default: System.out.println(\"Weekend!\");",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "The break Keyword"
      },
      {
        "type": "paragraph",
        "text": "Without <code class=\"w3-codespan\">break</code>, Java keeps running into the next <code class=\"w3-codespan\">case</code> block even after a match — this is called <strong>fall-through</strong>. This is rarely what you want."
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Fall-through (no break!)",
          "rows": [
            {
              "code": "int day = 2;",
              "output": ""
            },
            {
              "code": "switch (day) {",
              "output": ""
            },
            {
              "code": "  case 1: System.out.println(\"Monday\");",
              "output": ""
            },
            {
              "code": "  case 2: System.out.println(\"Tuesday\");",
              "output": "Tuesday"
            },
            {
              "code": "  case 3: System.out.println(\"Wednesday\");",
              "output": "Wednesday"
            },
            {
              "code": "  default: System.out.println(\"Other\");",
              "output": "Other"
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "Fall-through printed <strong>three lines</strong> instead of one because there were no <code>break</code> statements. Always add <code>break;</code> after each case unless you intentionally want fall-through."
      },
      {
        "type": "header",
        "level": 2,
        "text": "The default Keyword"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">default</code> block runs when no <code class=\"w3-codespan\">case</code> matches. It works like the final <code class=\"w3-codespan\">else</code> in an if-else chain and is optional but recommended."
      },
      {
        "type": "note",
        "text": "<strong>switch vs if-else:</strong> Use <code>switch</code> when you're comparing one variable against many <em>specific, known values</em>. Use <code>if-else</code> when your conditions involve ranges (e.g. <code>score &gt;= 90</code>) or complex expressions."
      },
      {
        "type": "code",
        "language": "java",
        "code": "int day = 3;\nswitch (day) {\n    case 1: System.out.println(\"Monday\");    break;\n    case 2: System.out.println(\"Tuesday\");   break;\n    case 3: System.out.println(\"Wednesday\"); break;\n    case 4: System.out.println(\"Thursday\");  break;\n    case 5: System.out.println(\"Friday\");    break;\n    default: System.out.println(\"Weekend!\");\n}\n// Output: Wednesday\n\n// Switch expression (Java 14+)\nString type = switch (day) {\n    case 1, 2, 3, 4, 5 -&gt; \"Weekday\";\n    default -&gt; \"Weekend\";\n};\nSystem.out.println(type);  // Weekday"
      }
    ]
  },
  "while-loop": {
    "title": "Java While Loop",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java While Loop"
      },
      {
        "type": "intro",
        "text": "A <code class=\"w3-codespan\">while</code> loop keeps running a block of code <strong>as long as a condition stays true</strong>. The moment the condition becomes false, the loop stops."
      },
      {
        "type": "paragraph",
        "text": "Think of it like a vending machine: keep dispensing items <em>while</em> there are items left. When the stock hits zero, stop."
      },
      {
        "type": "playground",
        "subtype": "while-loop"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Syntax"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "config": {
          "title": "while Loop",
          "tokens": [
            {
              "text": "while",
              "type": "keyword",
              "tip": "Keyword that starts the loop"
            },
            {
              "text": " (",
              "type": "punctuation"
            },
            {
              "text": "i < 5",
              "type": "operator",
              "tip": "Condition checked before every iteration — must evaluate to true or false"
            },
            {
              "text": ") {",
              "type": "punctuation",
              "tip": "Opening brace — loop body starts here"
            },
            {
              "text": "\n  System.out.println(i);",
              "type": "plain"
            },
            {
              "text": "\n  i",
              "type": "variable",
              "tip": "Counter variable"
            },
            {
              "text": "++",
              "type": "operator",
              "tip": "Update — without this the loop runs forever!"
            },
            {
              "text": ";",
              "type": "punctuation"
            },
            {
              "text": "\n}",
              "type": "punctuation",
              "tip": "Closing brace — loop body ends here"
            }
          ]
        }
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Count up while i < 5",
          "rows": [
            {
              "code": "int i = 0;",
              "output": ""
            },
            {
              "code": "while (i < 5) {",
              "output": ""
            },
            {
              "code": "  System.out.println(i);",
              "output": "0\n1\n2\n3\n4"
            },
            {
              "code": "  i++;",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Countdown Example"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Countdown from 3",
          "rows": [
            {
              "code": "int count = 3;",
              "output": ""
            },
            {
              "code": "while (count > 0) {",
              "output": ""
            },
            {
              "code": "  System.out.println(count + \"...\");",
              "output": "3...\n2...\n1..."
            },
            {
              "code": "  count--;",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "System.out.println(\"Go!\");",
              "output": "Go!"
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "<strong>Always update the variable inside the loop.</strong> If <code>i++</code> is missing, the condition never becomes false and the loop runs forever — an <strong>infinite loop</strong> that freezes the program."
      },
      {
        "type": "code",
        "language": "java",
        "code": "// while loop\nint i = 1;\nwhile (i &lt;= 5) {\n    System.out.print(i + \" \");  // 1 2 3 4 5\n    i++;\n}\n\n// do-while \u2014 executes at least once\nint n = 0;\ndo {\n    System.out.println(\"Attempt: \" + n);\n    n++;\n} while (n &lt; 3);\n\n// Sum using while\nint sum = 0, num = 1;\nwhile (num &lt;= 10) { sum += num; num++; }\nSystem.out.println(\"Sum 1-10: \" + sum);  // 55"
      }
    ]
  },
  "for-loop": {
    "title": "Java For Loop",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java For Loop"
      },
      {
        "type": "intro",
        "text": "Use a <code class=\"w3-codespan\">for</code> loop when you know <strong>exactly how many times</strong> the loop should run. It packs the init, condition, and update into one compact line."
      },
      {
        "type": "playground",
        "subtype": "for-loop"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The Three Parts of a for Loop"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "config": {
          "title": "for Loop",
          "tokens": [
            {
              "text": "for",
              "type": "keyword",
              "tip": "Keyword that starts the for loop"
            },
            {
              "text": " (",
              "type": "punctuation"
            },
            {
              "text": "int i = 0",
              "type": "variable",
              "tip": "Statement 1: runs once before the loop starts — initialise your counter"
            },
            {
              "text": "; ",
              "type": "punctuation"
            },
            {
              "text": "i < 5",
              "type": "operator",
              "tip": "Statement 2: checked before every iteration — loop runs while this is true"
            },
            {
              "text": "; ",
              "type": "punctuation"
            },
            {
              "text": "i++",
              "type": "keyword",
              "tip": "Statement 3: runs after every iteration — update the counter"
            },
            {
              "text": ") {",
              "type": "punctuation"
            },
            {
              "text": "\n  System.out.println(i);",
              "type": "plain"
            },
            {
              "text": "\n}",
              "type": "punctuation",
              "tip": "Closing brace — end of loop body"
            }
          ]
        }
      },
      {
        "type": "list",
        "ordered": true,
        "items": [
          "<strong>Init</strong> (<code class=\"w3-codespan\">int i = 0</code>) — runs <em>once</em> before the loop starts. Sets the starting value.",
          "<strong>Condition</strong> (<code class=\"w3-codespan\">i &lt; 5</code>) — checked <em>before every iteration</em>. If false, loop stops.",
          "<strong>Update</strong> (<code class=\"w3-codespan\">i++</code>) — runs <em>after every iteration</em>. Moves the counter forward."
        ]
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Print 0 to 4",
          "rows": [
            {
              "code": "for (int i = 0; i < 5; i++) {",
              "output": ""
            },
            {
              "code": "  System.out.println(i);",
              "output": "0\n1\n2\n3\n4"
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "More Examples"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Even numbers 2–10",
          "rows": [
            {
              "code": "for (int i = 2; i <= 10; i += 2) {",
              "output": ""
            },
            {
              "code": "  System.out.println(i);",
              "output": "2\n4\n6\n8\n10"
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Sum of 1 to 5",
          "rows": [
            {
              "code": "int sum = 0;",
              "output": ""
            },
            {
              "code": "for (int i = 1; i <= 5; i++) {",
              "output": ""
            },
            {
              "code": "  sum += i;",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "System.out.println(\"Sum = \" + sum);",
              "output": "Sum = 15"
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "<strong>for vs while:</strong> Use <code>for</code> when you know the number of iterations in advance. Use <code>while</code> when the loop count depends on a condition that can change unpredictably."
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Count from 1 to 5\nfor (int i = 1; i &lt;= 5; i++) {\n    System.out.print(i + \" \");   // 1 2 3 4 5\n}\n\n// Enhanced for-each \u2014 arrays\nint[] nums = {10, 20, 30, 40, 50};\nfor (int n : nums) {\n    System.out.print(n + \" \");   // 10 20 30 40 50\n}\n\n// Nested loops \u2014 times table\nfor (int i = 1; i &lt;= 3; i++) {\n    for (int j = 1; j &lt;= 3; j++) {\n        System.out.printf(\"%3d\", i * j);\n    }\n    System.out.println();\n}"
      }
    ]
  },
  "break-continue": {
    "title": "Java Break and Continue",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Controlling Loop Flow"
      },
      {
        "type": "intro",
        "text": "Sometimes you need to <strong>exit a loop early</strong> or <strong>skip one iteration</strong>. Java gives you two keywords for this: <code class=\"w3-codespan\">break</code> and <code class=\"w3-codespan\">continue</code>."
      },
      {
        "type": "playground",
        "subtype": "break-continue"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The break Statement"
      },
      {
        "type": "paragraph",
        "text": "<code class=\"w3-codespan\">break</code> immediately <strong>exits the entire loop</strong>. No more iterations run — execution jumps to the line after the closing brace."
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "break — stop at 5",
          "rows": [
            {
              "code": "for (int i = 1; i <= 9; i++) {",
              "output": ""
            },
            {
              "code": "  if (i == 5) { break; }",
              "output": ""
            },
            {
              "code": "  System.out.println(i);",
              "output": "1\n2\n3\n4"
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "The continue Statement"
      },
      {
        "type": "paragraph",
        "text": "<code class=\"w3-codespan\">continue</code> <strong>skips the rest of the current iteration</strong> and jumps straight to the next one. The loop itself keeps running."
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "continue — skip 4",
          "rows": [
            {
              "code": "for (int i = 1; i <= 7; i++) {",
              "output": ""
            },
            {
              "code": "  if (i == 4) { continue; }",
              "output": ""
            },
            {
              "code": "  System.out.println(i);",
              "output": "1\n2\n3\n5\n6\n7"
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Using Both Together"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "skip 3, stop at 7",
          "rows": [
            {
              "code": "for (int i = 1; i <= 9; i++) {",
              "output": ""
            },
            {
              "code": "  if (i == 3) { continue; }",
              "output": ""
            },
            {
              "code": "  if (i == 7) { break; }",
              "output": ""
            },
            {
              "code": "  System.out.println(i);",
              "output": "1\n2\n4\n5\n6"
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "<strong>break</strong> and <strong>continue</strong> work the same way in <code>while</code> loops. <code>break</code> always exits the nearest enclosing loop, and <code>continue</code> always skips to the next iteration of that same loop."
      },
      {
        "type": "code",
        "language": "java",
        "code": "// break \u2014 exit loop early\nfor (int i = 1; i &lt;= 9; i++) {\n    if (i == 5) break;\n    System.out.print(i + \" \");  // 1 2 3 4\n}\n\n// continue \u2014 skip one iteration\nfor (int i = 1; i &lt;= 9; i++) {\n    if (i % 2 == 0) continue;  // skip even\n    System.out.print(i + \" \");  // 1 3 5 7 9\n}\n\n// Labelled break \u2014 exit outer loop\nouter:\nfor (int i = 1; i &lt;= 3; i++) {\n    for (int j = 1; j &lt;= 3; j++) {\n        if (i == 2 && j == 2) break outer;\n        System.out.println(i + \",\" + j);\n    }\n}"
      }
    ]
  },
  "arrays": {
    "title": "Java Arrays",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Arrays"
      },
      {
        "type": "intro",
        "text": "An array stores <strong>multiple values of the same type</strong> in a single variable — like a row of numbered boxes, each holding one item."
      },
      {
        "type": "paragraph",
        "text": "Instead of writing <code class=\"w3-codespan\">String car1 = \"Volvo\"</code>, <code class=\"w3-codespan\">String car2 = \"BMW\"</code>... you store them all in one array and access each by its <strong>index</strong>."
      },
      {
        "type": "playground",
        "subtype": "arrays"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Declaring and Initialising an Array"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "config": {
          "title": "Array Declaration",
          "tokens": [
            {
              "text": "String",
              "type": "keyword",
              "tip": "The type of every element in the array"
            },
            {
              "text": "[]",
              "type": "punctuation",
              "tip": "Square brackets declare this as an array"
            },
            {
              "text": " cars",
              "type": "variable",
              "tip": "The array variable name"
            },
            {
              "text": " = ",
              "type": "operator"
            },
            {
              "text": "{",
              "type": "punctuation",
              "tip": "Opening brace — list your values inside"
            },
            {
              "text": "\"Volvo\"",
              "type": "value",
              "tip": "Element at index 0"
            },
            {
              "text": ", ",
              "type": "punctuation"
            },
            {
              "text": "\"BMW\"",
              "type": "value",
              "tip": "Element at index 1"
            },
            {
              "text": ", ",
              "type": "punctuation"
            },
            {
              "text": "\"Ford\"",
              "type": "value",
              "tip": "Element at index 2"
            },
            {
              "text": "}",
              "type": "punctuation",
              "tip": "Closing brace"
            },
            {
              "text": ";",
              "type": "punctuation"
            }
          ]
        }
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Access by index",
          "rows": [
            {
              "code": "String[] cars = {\"Volvo\", \"BMW\", \"Ford\"};",
              "output": ""
            },
            {
              "code": "System.out.println(cars[0]);",
              "output": "Volvo"
            },
            {
              "code": "System.out.println(cars[1]);",
              "output": "BMW"
            },
            {
              "code": "System.out.println(cars[2]);",
              "output": "Ford"
            },
            {
              "code": "System.out.println(cars.length);",
              "output": "3"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Loop Through an Array"
      },
      {
        "type": "paragraph",
        "text": "Use a <code class=\"w3-codespan\">for</code> loop with <code class=\"w3-codespan\">.length</code> to visit every element:"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Loop through array",
          "rows": [
            {
              "code": "int[] scores = {92, 78, 85, 61};",
              "output": ""
            },
            {
              "code": "for (int i = 0; i < scores.length; i++) {",
              "output": ""
            },
            {
              "code": "  System.out.println(scores[i]);",
              "output": "92\n78\n85\n61"
            },
            {
              "code": "}",
              "output": ""
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "<strong>Index starts at 0, not 1.</strong> An array of 4 elements has indexes 0, 1, 2, 3. Accessing index 4 throws an <code>ArrayIndexOutOfBoundsException</code>. Use <code>.length - 1</code> to safely reach the last element."
      },
      {
        "type": "code",
        "language": "java",
        "code": "int[] nums = {10, 20, 30, 40, 50};\nSystem.out.println(nums.length);      // 5\nSystem.out.println(nums[2]);          // 30\nnums[2] = 99;\n\n// for-each traversal\nfor (int n : nums) System.out.print(n + \" \");  // 10 20 99 40 50\n\n// Sort\njava.util.Arrays.sort(nums);\nSystem.out.println(java.util.Arrays.toString(nums));  // [10, 20, 40, 50, 99]\n\n// 2D array\nint[][] grid = {{1,2,3},{4,5,6},{7,8,9}};\nSystem.out.println(grid[1][2]);  // 6"
      }
    ]
  },
  "methods": {
    "title": "Java Methods",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Methods"
      },
      {
        "type": "intro",
        "text": "A <strong>method</strong> is a reusable block of code that runs only when called. Define it once, call it anywhere — as many times as you need."
      },
      {
        "type": "playground",
        "subtype": "methods"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Method Anatomy"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "config": {
          "title": "Method Definition",
          "tokens": [
            {
              "text": "static",
              "type": "keyword",
              "tip": "The method belongs to the class, not to an object"
            },
            {
              "text": " ",
              "type": "plain"
            },
            {
              "text": "int",
              "type": "keyword",
              "tip": "Return type — what the method gives back. Use void if it returns nothing."
            },
            {
              "text": " ",
              "type": "plain"
            },
            {
              "text": "add",
              "type": "variable",
              "tip": "Method name — use camelCase by convention"
            },
            {
              "text": "(",
              "type": "punctuation",
              "tip": "Opening parenthesis — parameters go inside"
            },
            {
              "text": "int a",
              "type": "variable",
              "tip": "First parameter: type then name"
            },
            {
              "text": ", ",
              "type": "punctuation"
            },
            {
              "text": "int b",
              "type": "variable",
              "tip": "Second parameter"
            },
            {
              "text": ") {",
              "type": "punctuation",
              "tip": "Opening brace — method body starts here"
            },
            {
              "text": "\n  return a + b;",
              "type": "plain"
            },
            {
              "text": "\n}",
              "type": "punctuation",
              "tip": "Closing brace — method body ends here"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Defining and Calling"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "void method — no return value",
          "rows": [
            {
              "code": "static void greet(String name) {",
              "output": ""
            },
            {
              "code": "  System.out.println(\"Hello, \" + name + \"!\");",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "// calling the method:",
              "output": ""
            },
            {
              "code": "greet(\"Sathish\");",
              "output": "Hello, Sathish!"
            },
            {
              "code": "greet(\"Java\");",
              "output": "Hello, Java!"
            }
          ]
        }
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "int method — with return value",
          "rows": [
            {
              "code": "static int add(int a, int b) {",
              "output": ""
            },
            {
              "code": "  return a + b;",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "int result = add(12, 8);",
              "output": ""
            },
            {
              "code": "System.out.println(result);",
              "output": "20"
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "<strong>void</strong> means the method does not return anything — it just performs an action. When you need the method to produce a value, replace <code>void</code> with the return type (<code>int</code>, <code>String</code>, <code>boolean</code>, etc.) and add a <code>return</code> statement."
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Return a value\nstatic int multiply(int a, int b) {\n    return a * b;\n}\n\n// Void \u2014 perform action, return nothing\nstatic void greet(String name) {\n    System.out.println(\"Hello, \" + name + \"!\");\n}\n\nSystem.out.println(\"4 \u00d7 7 = \" + multiply(4, 7));  // 4 \u00d7 7 = 28\ngreet(\"Alice\");                                    // Hello, Alice!\n\n// Overloading \u2014 same name, different params\nstatic double multiply(double a, double b) { return a * b; }\nSystem.out.println(multiply(2.5, 4.0));  // 10.0"
      }
    ]
  },
  "method-parameters": {
    "title": "Java Method Parameters",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Parameters and Arguments"
      },
      {
        "type": "intro",
        "text": "<strong>Parameters</strong> are the variables listed in the method definition. <strong>Arguments</strong> are the actual values you pass when calling the method."
      },
      {
        "type": "playground",
        "subtype": "methods"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "config": {
          "title": "Parameters vs Arguments",
          "tokens": [
            {
              "text": "static void",
              "type": "keyword"
            },
            {
              "text": " greet",
              "type": "variable",
              "tip": "Method name"
            },
            {
              "text": "(",
              "type": "punctuation"
            },
            {
              "text": "String",
              "type": "keyword",
              "tip": "Parameter type"
            },
            {
              "text": " name",
              "type": "variable",
              "tip": "Parameter — acts as a local variable inside the method"
            },
            {
              "text": ") {",
              "type": "punctuation"
            },
            {
              "text": "\n  System.out.println(\"Hello, \" + name);",
              "type": "plain"
            },
            {
              "text": "\n}",
              "type": "punctuation"
            },
            {
              "text": "\n\ngreet(",
              "type": "plain"
            },
            {
              "text": "\"Sathish\"",
              "type": "value",
              "tip": "Argument — the real value passed at call time"
            },
            {
              "text": ");",
              "type": "punctuation"
            }
          ]
        }
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Single parameter",
          "rows": [
            {
              "code": "static void greet(String name) {",
              "output": ""
            },
            {
              "code": "  System.out.println(\"Hello, \" + name + \"!\");",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "greet(\"Priya\");",
              "output": "Hello, Priya!"
            },
            {
              "code": "greet(\"Kumar\");",
              "output": "Hello, Kumar!"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Multiple Parameters"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Multiple parameters",
          "rows": [
            {
              "code": "static void printAge(String name, int age) {",
              "output": ""
            },
            {
              "code": "  System.out.println(name + \" is \" + age + \" years old.\");",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "printAge(\"Arun\", 22);",
              "output": "Arun is 22 years old."
            },
            {
              "code": "printAge(\"Meena\", 19);",
              "output": "Meena is 19 years old."
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Return Values"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Method with return value",
          "rows": [
            {
              "code": "static int multiply(int a, int b) {",
              "output": ""
            },
            {
              "code": "  return a * b;",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "System.out.println(multiply(6, 7));",
              "output": "42"
            },
            {
              "code": "System.out.println(multiply(3, 9));",
              "output": "27"
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "<strong>Parameter</strong> = variable in the definition. <strong>Argument</strong> = value at the call site. Arguments must match parameters in <em>number, order, and type</em>."
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Pass by value \u2014 original unchanged\nstatic void doubleIt(int n) { n = n * 2; }\nint x = 5;\ndoubleIt(x);\nSystem.out.println(x);  // 5 \u2014 not changed\n\n// Return a value\nstatic int square(int n) { return n * n; }\nSystem.out.println(square(7));  // 49\n\n// Varargs \u2014 variable number of args\nstatic int sum(int... nums) {\n    int total = 0;\n    for (int n : nums) total += n;\n    return total;\n}\nSystem.out.println(sum(1, 2, 3, 4, 5));  // 15"
      }
    ]
  },
  "method-overloading": {
    "title": "Java Method Overloading",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Method Overloading"
      },
      {
        "type": "paragraph",
        "text": "With<strong> method overloading</strong>, multiple methods can have the same name with different\nparameters:"
      },
      {
        "type": "paragraph",
        "text": "Consider the following example, which has two methods that add numbers of different type:"
      },
      {
        "type": "paragraph",
        "text": "Instead of defining two methods that should do the same thing, it is better to overload one."
      },
      {
        "type": "paragraph",
        "text": "In the example below, we overload the <code class=\"w3-codespan\">plusMethod</code> \nmethod to work for both <code class=\"w3-codespan\">int</code> \nand <code class=\"w3-codespan\">double</code>:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Overloading Rules"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "Methods must have the <strong>same name</strong>",
          "They must differ in <strong>number of parameters</strong>, <strong>type of parameters</strong>, or <strong>both</strong>",
          "Return type alone is <em>not enough</em> to distinguish overloaded methods",
          "Overloading is resolved at <strong>compile time</strong> (static dispatch)"
        ]
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Overloaded area() — same name, different parameters\nstatic double area(double r) {\n    return Math.PI * r * r;          // circle\n}\nstatic double area(double w, double h) {\n    return w * h;                    // rectangle\n}\nstatic double area(double b, double h, boolean triangle) {\n    return 0.5 * b * h;             // triangle\n}\n\n// Java picks the right version automatically\nSystem.out.println(area(5.0));           // 78.54 (circle)\nSystem.out.println(area(4.0, 6.0));      // 24.0  (rectangle)"
      },
      {
        "type": "playground",
        "subtype": "method-overloading"
      },
      {
        "type": "header",
        "level": 2,
        "text": "When to Use Method Overloading"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "When the <strong>same logical operation</strong> should work on different data types (e.g., <code>add(int)</code> vs <code>add(double)</code>)",
          "When varying numbers of arguments make sense for the same action (e.g., <code>draw(radius)</code> vs <code>draw(width, height)</code>)",
          "To provide <strong>convenience versions</strong> of a method with sensible defaults",
          "Avoid overloading when the methods do fundamentally different things — use distinct names instead"
        ]
      },
      {
        "type": "note",
        "text": "<p><strong>Note:</strong> Multiple methods can have the same name \n  as long as the number and/or type of parameters are different.</p>"
      }
    ]
  },
  "scope": {
    "title": "Java Scope",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Scope"
      },
      {
        "type": "paragraph",
        "text": "In Java, variables are only accessible inside the region where they are created. This is called\n<strong>scope</strong>."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Method Scope"
      },
      {
        "type": "paragraph",
        "text": "Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Block Scope"
      },
      {
        "type": "paragraph",
        "text": "A block of code refers to all of the code between curly braces <code class=\"w3-codespan\">{ }</code>."
      },
      {
        "type": "paragraph",
        "text": "Variables declared inside a block of code are only accessible by the code between the curly braces, and only after the line in which the variable was declared:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Loop Scope"
      },
      {
        "type": "paragraph",
        "text": "Variables declared inside a <code class=\"w3-codespan\">for</code> loop only exist inside the loop:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "The <code class=\"w3-codespan\">for</code> loop has its own block (<code class=\"w3-codespan\">{ ... }</code>).",
          "The variable <code class=\"w3-codespan\">i</code> declared in the loop header (<code class=\"w3-codespan\">int i = 0</code>) is only accessible inside that loop block.",
          "Once the loop ends, <code class=\"w3-codespan\">i</code> is destroyed, so you can't use it outside."
        ]
      },
      {
        "type": "header",
        "level": 3,
        "text": "Why this matters"
      },
      {
        "type": "paragraph",
        "text": "Loop variables are not available outside the loop."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Class Scope (Fields)"
      },
      {
        "type": "paragraph",
        "text": "Variables declared at the <strong>class level</strong> (outside any method) are called <em>fields</em>. They are accessible from <em>any</em> method in the class and persist as long as the object exists."
      },
      {
        "type": "code",
        "language": "java",
        "code": "class Counter {\n    int count = 0;   // class-scope field — visible in all methods\n\n    void increment() {\n        count++;        // accesses the field\n    }\n\n    void reset() {\n        count = 0;      // also accesses the same field\n    }\n\n    void show() {\n        System.out.println(\"Count: \" + count);\n    }\n}\n\nCounter c = new Counter();\nc.increment();\nc.increment();\nc.show();    // Count: 2\nc.reset();\nc.show();    // Count: 0"
      },
      {
        "type": "playground",
        "subtype": "scope"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Scope Summary"
      },
      {
        "type": "table",
        "headers": ["Scope Level", "Declared in", "Accessible in", "Lifespan"],
        "rows": [
          ["Class (field)", "Class body, outside methods", "All methods of the class", "As long as the object exists"],
          ["Method", "Directly inside a method", "Anywhere in that method (after declaration)", "Until method returns"],
          ["Block", "Inside <code>{ }</code> (if, for, while…)", "Only inside that block", "Until block ends"],
          ["Loop", "For-loop header (<code>int i = 0</code>)", "Only inside the loop body", "Each iteration; destroyed when loop ends"]
        ]
      },
      {
        "type": "paragraph",
        "text": "You can safely reuse the same variable name (<code class=\"w3-codespan\">i</code>, <code class=\"w3-codespan\">j</code>, etc.) in different loops in the same method:"
      }
    ]
  },
  "recursion": {
    "title": "Java Recursion",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Recursion"
      },
      {
        "type": "paragraph",
        "text": "Recursion is the technique of making a function call itself. This technique provides a way\nto break complicated problems down into simpler problems which are easier to solve."
      },
      {
        "type": "paragraph",
        "text": "Recursion may be a bit difficult to understand. The\nbest way to figure out how it works is to experiment with it."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Recursion Example"
      },
      {
        "type": "paragraph",
        "text": "Adding two numbers together is easy to do, but adding a range of numbers is more\ncomplicated. In the following example, recursion is used to add a range of numbers\ntogether by breaking it down into the simple task of adding two numbers:"
      },
      {
        "type": "header",
        "level": 3,
        "text": "Example Explained"
      },
      {
        "type": "paragraph",
        "text": "When the <code class=\"w3-codespan\">sum()</code> method is called, it adds parameter <code class=\"w3-codespan\">k</code> to the sum of all numbers smaller\nthan <code class=\"w3-codespan\">k</code> and returns the result. When <code class=\"w3-codespan\">k</code> becomes 0, the method just returns 0. When\nrunning, the program follows these steps:"
      },
      {
        "type": "note",
        "text": "10 + sum(9)<br>\n10 + ( 9 + sum(8) )<br>\n10 + ( 9 + ( 8 + sum(7) ) )<br>\n...<br>\n10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)<br>\n10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0"
      },
      {
        "type": "paragraph",
        "text": "Since the method does not call itself when <code class=\"w3-codespan\">k</code> is 0, the program stops there and returns the\nresult."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Halting Condition"
      },
      {
        "type": "paragraph",
        "text": "Just as loops can run into the problem of infinite looping, recursive methods can run into\nthe problem of infinite recursion. Infinite recursion is when the method never stops calling\nitself. Every recursive method should have a halting condition, which is the condition\nwhere the method stops calling itself. In the previous example, the halting condition is\nwhen the parameter <code class=\"w3-codespan\">k</code> becomes 0."
      },
      {
        "type": "paragraph",
        "text": "It is helpful to see a variety of different examples to better understand the concept. In this\nexample, the method adds a range of numbers between a start and an end. The halting\ncondition for this recursive method is when <strong>end</strong> is not greater than <strong>start</strong>:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Countdown with Recursion"
      },
      {
        "type": "paragraph",
        "text": "This example demonstrates how to use recursion to create a countdown function:"
      },
      {
        "type": "paragraph",
        "text": "The method calls itself with <code class=\"w3-codespan\">n - 1</code> until <code class=\"w3-codespan\">n</code> becomes <code class=\"w3-codespan\">0</code>."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Fibonacci Sequence with Recursion"
      },
      {
        "type": "paragraph",
        "text": "The Fibonacci sequence is a classic recursion example. Each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13 …"
      },
      {
        "type": "code",
        "language": "java",
        "code": "static int fibonacci(int n) {\n    if (n &lt;= 1) return n;           // base cases: fib(0)=0, fib(1)=1\n    return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\n// Print first 8 Fibonacci numbers\nfor (int i = 0; i &lt; 8; i++) {\n    System.out.print(fibonacci(i) + \" \");\n}\n// Output: 0 1 1 2 3 5 8 13"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Golden Rules of Recursion"
      },
      {
        "type": "list",
        "ordered": true,
        "items": [
          "<strong>Always have a base case</strong> — the condition that stops recursion (e.g., <code>if (n &lt;= 0) return</code>)",
          "<strong>Move toward the base case</strong> — every recursive call must bring you closer to stopping",
          "<strong>Trust the recursion</strong> — assume the recursive call correctly solves the smaller sub-problem",
          "<strong>Watch for stack overflow</strong> — deeply nested calls consume memory; consider iteration for large inputs"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Calculate Factorial with Recursion"
      },
      {
        "type": "playground",
        "subtype": "recursion"
      },
      {
        "type": "paragraph",
        "text": "This example uses a recursive method to calculate the factorial of 5:"
      }
    ]
  },
  "oop": {
    "title": "Java OOP",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "What is Object-Oriented Programming?"
      },
      {
        "type": "intro",
        "text": "<strong>OOP</strong> organises code around <em>objects</em> — bundles that combine <strong>data (attributes)</strong> and <strong>behaviour (methods)</strong> in one place, mirroring real-world things."
      },
      {
        "type": "paragraph",
        "text": "Think of a <strong>Car</strong>: it has attributes (brand, colour, speed) and methods (accelerate, brake). In OOP you define a <code class=\"w3-codespan\">Car</code> class once, then create as many car <em>objects</em> as you need from that blueprint."
      },
      {
        "type": "playground",
        "subtype": "class-object"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Class vs Object"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<strong>Class</strong> — the blueprint / template. Defined once. Describes what attributes and methods every object of that type will have.",
          "<strong>Object</strong> — a real instance created from the class using <code class=\"w3-codespan\">new</code>. Each object has its own copy of the attributes."
        ]
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Class → Object",
          "rows": [
            {
              "code": "// Class definition (blueprint)",
              "output": ""
            },
            {
              "code": "class Car { String brand; int speed; }",
              "output": ""
            },
            {
              "code": "",
              "output": ""
            },
            {
              "code": "// Creating objects (instances)",
              "output": ""
            },
            {
              "code": "Car car1 = new Car();",
              "output": ""
            },
            {
              "code": "car1.brand = \"Toyota\"; car1.speed = 80;",
              "output": ""
            },
            {
              "code": "Car car2 = new Car();",
              "output": ""
            },
            {
              "code": "car2.brand = \"BMW\"; car2.speed = 120;",
              "output": ""
            },
            {
              "code": "System.out.println(car1.brand);",
              "output": "Toyota"
            },
            {
              "code": "System.out.println(car2.brand);",
              "output": "BMW"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "The 4 Pillars of OOP"
      },
      {
        "type": "table",
        "headers": ["Pillar", "What it means", "Java feature"],
        "rows": [
          ["<strong>Encapsulation</strong>", "Bundle data + methods; hide internal details", "<code>private</code> fields + <code>public</code> getters/setters"],
          ["<strong>Inheritance</strong>", "A child class reuses and extends a parent class", "<code>extends</code> keyword"],
          ["<strong>Polymorphism</strong>", "Same method name behaves differently per object", "Method overriding (<code>@Override</code>)"],
          ["<strong>Abstraction</strong>", "Expose only what the caller needs; hide complexity", "Abstract classes &amp; interfaces"]
        ]
      },
      {
        "type": "note",
        "text": "<strong>Real-world analogy:</strong> A smartphone is a perfect OOP example — it <em>encapsulates</em> hardware, <em>inherits</em> common phone behaviour, supports <em>polymorphic</em> apps (one tap gesture, many app responses), and <em>abstracts</em> away battery management from the user."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Why OOP?"
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Define a class (blueprint)\nclass Car {\n    String brand;\n    int speed;\n\n    void drive() {\n        System.out.println(brand + \" driving at \" + speed + \" km/h\");\n    }\n}\n\n// Create objects (instances)\nCar car1 = new Car();\ncar1.brand = \"Toyota\"; car1.speed = 80;\ncar1.drive();  // Toyota driving at 80 km/h\n\nCar car2 = new Car();\ncar2.brand = \"BMW\"; car2.speed = 120;\ncar2.drive();  // BMW driving at 120 km/h"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<strong>Reusability</strong> — write a class once, create hundreds of objects from it",
          "<strong>Organisation</strong> — related data and behaviour stay together",
          "<strong>DRY principle</strong> — Don't Repeat Yourself: one place to change, all objects updated",
          "<strong>Modularity</strong> — each class can be built, tested, and maintained independently"
        ]
      }
    ]
  },
  "classes-objects": {
    "title": "Java Classes and Objects",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Classes and Objects"
      },
      {
        "type": "intro",
        "text": "A <strong>class</strong> is the blueprint. An <strong>object</strong> is the real thing built from that blueprint. One class can produce unlimited objects, each with its own data."
      },
      {
        "type": "playground",
        "subtype": "class-object"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Defining a Class"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "config": {
          "title": "Class Definition",
          "tokens": [
            {
              "text": "class",
              "type": "keyword",
              "tip": "Keyword that defines a class"
            },
            {
              "text": " Car",
              "type": "variable",
              "tip": "Class name — always start with an uppercase letter"
            },
            {
              "text": " {",
              "type": "punctuation",
              "tip": "Opening brace — class body starts here"
            },
            {
              "text": "\n  String",
              "type": "keyword",
              "tip": "Attribute type"
            },
            {
              "text": " brand",
              "type": "variable",
              "tip": "Attribute name — belongs to every Car object"
            },
            {
              "text": ";",
              "type": "punctuation"
            },
            {
              "text": "\n  int",
              "type": "keyword"
            },
            {
              "text": " speed",
              "type": "variable"
            },
            {
              "text": ";",
              "type": "punctuation"
            },
            {
              "text": "\n}",
              "type": "punctuation",
              "tip": "Closing brace — class body ends here"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Creating Objects"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Multiple objects from one class",
          "rows": [
            {
              "code": "Car myCar = new Car();",
              "output": ""
            },
            {
              "code": "myCar.brand = \"Toyota\";",
              "output": ""
            },
            {
              "code": "myCar.speed = 100;",
              "output": ""
            },
            {
              "code": "System.out.println(myCar.brand);",
              "output": "Toyota"
            },
            {
              "code": "System.out.println(myCar.speed);",
              "output": "100"
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "The <strong>class name must match the file name</strong> — a class called <code>Car</code> must live in a file called <code>Car.java</code>. Class names always start with an uppercase letter by Java convention."
      },
      {
        "type": "code",
        "language": "java",
        "code": "class Dog {\n    String breed;\n    int age;\n\n    void bark() {\n        System.out.println(breed + \" says: Woof!\");\n    }\n}\n\nDog d = new Dog();\nd.breed = \"Labrador\";\nd.age = 3;\nSystem.out.println(d.breed + \", age \" + d.age);  // Labrador, age 3\nd.bark();   // Labrador says: Woof!"
      }
    ]
  },
  "class-attributes": {
    "title": "Java Class Attributes",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Class Attributes"
      },
      {
        "type": "intro",
        "text": "<strong>Attributes</strong> (also called <em>fields</em>) are variables declared inside a class. Every object created from that class gets its own copy of those attributes."
      },
      {
        "type": "playground",
        "subtype": "class-object"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Declaring and Accessing Attributes"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Attributes in action",
          "rows": [
            {
              "code": "class Car {",
              "output": ""
            },
            {
              "code": "  String brand;",
              "output": ""
            },
            {
              "code": "  int speed;",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "Car myCar = new Car();",
              "output": ""
            },
            {
              "code": "myCar.brand = \"Toyota\";",
              "output": ""
            },
            {
              "code": "myCar.speed = 120;",
              "output": ""
            },
            {
              "code": "System.out.println(myCar.brand);",
              "output": "Toyota"
            },
            {
              "code": "System.out.println(myCar.speed);",
              "output": "120"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Independent Copies Per Object"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Two objects — independent data",
          "rows": [
            {
              "code": "Car car1 = new Car();  car1.brand = \"Toyota\";",
              "output": ""
            },
            {
              "code": "Car car2 = new Car();  car2.brand = \"BMW\";",
              "output": ""
            },
            {
              "code": "System.out.println(car1.brand);",
              "output": "Toyota"
            },
            {
              "code": "System.out.println(car2.brand);",
              "output": "BMW"
            }
          ]
        }
      },
      {
        "type": "header",
        "level": 2,
        "text": "Final Fields (Constants)"
      },
      {
        "type": "paragraph",
        "text": "Use the <code class=\"w3-codespan\">final</code> keyword to make an attribute a <strong>constant</strong> — its value is set once and can never be changed after that."
      },
      {
        "type": "code",
        "language": "java",
        "code": "class Circle {\n    final double PI = 3.14159;  // constant — cannot be changed\n    double radius;\n\n    double area() {\n        return PI * radius * radius;\n    }\n}\n\nCircle c = new Circle();\nc.radius = 5;\nSystem.out.println(c.area());  // 78.53975\n\n// c.PI = 3.0;  // ERROR: cannot assign a value to final variable PI"
      },
      {
        "type": "note",
        "text": "Use <code>final</code> to make an attribute constant — its value can never be changed after it is set: <code>final double PI = 3.14159;</code>"
      }
    ]
  },
  "class-methods": {
    "title": "Java Class Methods",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Class Methods"
      },
      {
        "type": "intro",
        "text": "Methods defined inside a class describe the <strong>behaviour</strong> of its objects. You call them using the dot operator: <code class=\"w3-codespan\">object.method()</code>."
      },
      {
        "type": "playground",
        "subtype": "class-object"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Calling methods on an object",
          "rows": [
            {
              "code": "class Car {",
              "output": ""
            },
            {
              "code": "  String brand = \"Toyota\";",
              "output": ""
            },
            {
              "code": "  void honk() { System.out.println(brand + \": Beep!\"); }",
              "output": ""
            },
            {
              "code": "  int doubleSpeed(int s) { return s * 2; }",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "Car myCar = new Car();",
              "output": ""
            },
            {
              "code": "myCar.honk();",
              "output": "Toyota: Beep!"
            },
            {
              "code": "System.out.println(myCar.doubleSpeed(60));",
              "output": "120"
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "Use the <strong>dot operator</strong> (<code>.</code>) to access both attributes (<code>obj.brand</code>) and methods (<code>obj.honk()</code>) on an object. Methods with <code>void</code> return type perform an action but return nothing; methods with a type like <code>int</code> give back a value."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Static vs Instance Methods"
      },
      {
        "type": "paragraph",
        "text": "A <strong>static</strong> method belongs to the class itself — you call it without creating an object. An <strong>instance</strong> method belongs to an object and can access its attributes."
      },
      {
        "type": "code",
        "language": "java",
        "code": "class MathHelper {\n    // Static — no object needed\n    static int square(int n) {\n        return n * n;\n    }\n}\n\nclass Car {\n    String brand;\n    // Instance — belongs to a specific Car object\n    void describe() {\n        System.out.println(\"I am a \" + brand);\n    }\n}\n\n// Calling each type\nSystem.out.println(MathHelper.square(4));  // 16  — no object\nCar c = new Car();\nc.brand = \"Toyota\";\nc.describe();                              // I am a Toyota"
      },
      {
        "type": "table",
        "headers": ["Feature", "Static Method", "Instance Method"],
        "rows": [
          ["Called on", "Class name: <code>MathHelper.square()</code>", "Object: <code>c.describe()</code>"],
          ["Access attributes?", "No (no <code>this</code>)", "Yes (has <code>this</code>)"],
          ["Keyword", "<code>static</code>", "(no keyword needed)"],
          ["Best for", "Utility / helper logic", "Object behaviour"]
        ]
      }
    ]
  },
  "constructors": {
    "title": "Java Constructors",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Constructors"
      },
      {
        "type": "intro",
        "text": "A <strong>constructor</strong> is a special method that runs automatically when an object is created with <code class=\"w3-codespan\">new</code>. It sets the object's initial state."
      },
      {
        "type": "playground",
        "subtype": "constructor"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Constructor Syntax"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "config": {
          "title": "Constructor Definition",
          "tokens": [
            {
              "text": "Car",
              "type": "variable",
              "tip": "Constructor name must exactly match the class name"
            },
            {
              "text": "(",
              "type": "punctuation"
            },
            {
              "text": "String",
              "type": "keyword",
              "tip": "Parameter type"
            },
            {
              "text": " brand",
              "type": "variable",
              "tip": "Parameter — used to initialise the attribute"
            },
            {
              "text": ", ",
              "type": "punctuation"
            },
            {
              "text": "int",
              "type": "keyword"
            },
            {
              "text": " speed",
              "type": "variable"
            },
            {
              "text": ") {",
              "type": "punctuation",
              "tip": "No return type — not even void"
            },
            {
              "text": "\n  this",
              "type": "keyword",
              "tip": "this refers to the current object being created"
            },
            {
              "text": ".brand = brand;",
              "type": "plain"
            },
            {
              "text": "\n  this.speed = speed;",
              "type": "plain"
            },
            {
              "text": "\n}",
              "type": "punctuation"
            }
          ]
        }
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Constructor in action",
          "rows": [
            {
              "code": "class Car {",
              "output": ""
            },
            {
              "code": "  String brand;  int speed;",
              "output": ""
            },
            {
              "code": "  Car(String brand, int speed) {",
              "output": ""
            },
            {
              "code": "    this.brand = brand;",
              "output": ""
            },
            {
              "code": "    this.speed = speed;",
              "output": ""
            },
            {
              "code": "  }",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "Car c = new Car(\"Toyota\", 120);",
              "output": ""
            },
            {
              "code": "System.out.println(c.brand);",
              "output": "Toyota"
            },
            {
              "code": "System.out.println(c.speed);",
              "output": "120"
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "The constructor name <strong>must match the class name</strong> exactly and has <strong>no return type</strong>. If you don't write one, Java silently provides an empty default constructor. Use <code>this.field = param</code> when the parameter name matches the field name."
      },
      {
        "type": "code",
        "language": "java",
        "code": "class Person {\n    String name;\n    int age;\n\n    // Constructor\n    Person(String name, int age) {\n        this.name = name;  // 'this' = current object\n        this.age = age;\n    }\n\n    void greet() {\n        System.out.println(\"Hi, I'm \" + name + \", age \" + age);\n    }\n}\n\nPerson p1 = new Person(\"Alice\", 25);\nPerson p2 = new Person(\"Bob\", 30);\np1.greet();  // Hi, I'm Alice, age 25\np2.greet();  // Hi, I'm Bob, age 30"
      }
    ]
  },
  "modifiers": {
    "title": "Java Modifiers",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Modifiers"
      },
      {
        "type": "paragraph",
        "text": "By now, you are quite familiar with the <code class=\"w3-codespan\">public</code> keyword that appears in almost \nall of our examples:"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">public</code> keyword is an <strong>access modifier</strong>, \nmeaning that it is used to set the access level for classes, attributes, methods and \nconstructors."
      },
      {
        "type": "paragraph",
        "text": "We divide modifiers into two groups:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<strong>Access Modifiers</strong> - controls the access level",
          "<strong><a href=\"java_non_modifiers.html\">Non-Access Modifiers</a></strong> - do not control access level, but provides other functionality"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Access Modifiers"
      },
      {
        "type": "paragraph",
        "text": "For <strong>classes</strong>, you can use either <code class=\"w3-codespan\">public</code> or <em>default</em>:"
      },
      {
        "type": "paragraph",
        "text": "For <strong>attributes, methods and constructors</strong>, you can use the one of the \nfollowing:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Public vs. Private Example"
      },
      {
        "type": "paragraph",
        "text": "In the example below, the class has one <code class=\"w3-codespan\">public</code> attribute and one <code class=\"w3-codespan\">private</code> \nattribute."
      },
      {
        "type": "paragraph",
        "text": "Think of it like real life:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<code class=\"w3-codespan\">public</code> - a public park, everyone can enter",
          "<code class=\"w3-codespan\">private</code> - your house key, only you can use it"
        ]
      },
      {
        "type": "header",
        "level": 3,
        "text": "Example explained"
      },
      {
        "type": "playground",
        "subtype": "modifiers"
      },
      {
        "type": "paragraph",
        "text": "Here, <code class=\"w3-codespan\">name</code> is declared as <code class=\"w3-codespan\">public</code>, so it can be accessed from outside the <code class=\"w3-codespan\">Person</code> class.  \nBut <code class=\"w3-codespan\">age</code> is declared as <code class=\"w3-codespan\">private</code>, so it can only be used inside the <code class=\"w3-codespan\">Person</code> class."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Non-Access Modifiers"
      },
      {
        "type": "paragraph",
        "text": "Non-access modifiers don't control visibility — they change <em>how</em> a member behaves."
      },
      {
        "type": "table",
        "headers": ["Modifier", "Applies to", "Effect"],
        "rows": [
          ["<code>static</code>", "Fields &amp; methods", "Belongs to the class, not to any object. Call it without creating an instance."],
          ["<code>final</code>", "Fields, methods, classes", "Field: value can't change. Method: can't be overridden. Class: can't be extended."],
          ["<code>abstract</code>", "Methods &amp; classes", "Method has no body — subclass must implement it. Class can't be instantiated."],
          ["<code>synchronized</code>", "Methods", "Only one thread can execute this method at a time (thread safety)."],
          ["<code>transient</code>", "Fields", "Field is skipped when serializing the object to a file/stream."],
          ["<code>volatile</code>", "Fields", "Value is always read from main memory, not from a thread's local cache."]
        ]
      },
      {
        "type": "code",
        "language": "java",
        "code": "class MathConst {\n    // static: shared by all instances, accessed via class name\n    static final double PI = 3.14159;\n\n    // static method: no object needed\n    static double circleArea(double r) {\n        return PI * r * r;\n    }\n}\n\n// abstract: class cannot be instantiated — must be subclassed\nabstract class Shape {\n    abstract double area();   // no body — subclass provides it\n}\n\nclass Square extends Shape {\n    double side;\n    Square(double s) { this.side = s; }\n\n    @Override\n    double area() { return side * side; }  // concrete implementation\n}\n\nSystem.out.println(MathConst.PI);               // 3.14159\nSystem.out.println(MathConst.circleArea(5));    // 78.53975\nSystem.out.println(new Square(4).area());       // 16.0"
      }
    ]
  },
  "encapsulation": {
    "title": "Java Encapsulation",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Encapsulation"
      },
      {
        "type": "paragraph",
        "text": "The meaning of <strong>Encapsulation</strong>, is to make sure that \"sensitive\" data is hidden \nfrom users. To achieve this, you must:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "declare class variables/attributes as <code class=\"w3-codespan\">private</code>",
          "provide public <strong>get</strong> \nand <strong>set</strong> methods to access and update the value of a <code class=\"w3-codespan\">private</code> \nvariable"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Get and Set"
      },
      {
        "type": "paragraph",
        "text": "You learned from the previous chapter that <code class=\"w3-codespan\">private</code> variables can only be \naccessed within the same class (an outside class has no access to it). However, \nit is possible to access them if we provide public <strong>get</strong> and <strong>set</strong> methods."
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">get</code> method returns the variable value, and the <code class=\"w3-codespan\">set</code> method sets the value."
      },
      {
        "type": "paragraph",
        "text": "Syntax for both is that they start with either <code class=\"w3-codespan\">get</code> or <code class=\"w3-codespan\">set</code>, followed by the \nname of the variable, with the first letter in upper case:"
      },
      {
        "type": "header",
        "level": 4,
        "text": "Example explained"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">get</code> method returns the value of the variable <code class=\"w3-codespan\">name</code>."
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">set</code> method takes a parameter (<code class=\"w3-codespan\">newName</code>) and assigns it to the\n<code class=\"w3-codespan\">name</code> variable. The <code class=\"w3-codespan\">this</code> keyword is used to refer to the current \nobject."
      },
      {
        "type": "paragraph",
        "text": "However, as the <code class=\"w3-codespan\">name</code> variable is declared as <code class=\"w3-codespan\">private</code>, we \n<strong>cannot</strong> access it from outside this class:"
      },
      {
        "type": "paragraph",
        "text": "If the variable was declared as <code class=\"w3-codespan\">public</code>, we would expect the following output:"
      },
      {
        "type": "paragraph",
        "text": "However, as we try to access a <code class=\"w3-codespan\">private</code> variable, we get an error:"
      },
      {
        "type": "paragraph",
        "text": "Instead, we use the <code class=\"w3-codespan\">getName()</code> and <code class=\"w3-codespan\">setName()</code> methods to access and update the variable:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Why Encapsulation?"
      },
      {
        "type": "playground",
        "subtype": "encapsulation"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "Better control of class attributes and methods",
          "Class attributes can be made <strong>read-only</strong> (if you only use the <code class=\"w3-codespan\">get</code> method), or <strong>write-only</strong> (if you only use the <code class=\"w3-codespan\">set</code> method)",
          "Flexible: the programmer can change one part of the code without affecting other parts",
          "Increased security of data"
        ]
      },
      {
        "type": "code",
        "language": "java",
        "code": "class BankAccount {\n    private double balance;  // hidden — direct access blocked\n\n    BankAccount(double initial) { this.balance = initial; }\n\n    public double getBalance()           { return balance; }\n    public void deposit(double amount)   { if (amount &gt; 0) balance += amount; }\n    public void withdraw(double amount)  { if (amount &lt;= balance) balance -= amount; }\n}\n\nBankAccount acc = new BankAccount(1000);\nacc.deposit(500);\nacc.withdraw(200);\nSystem.out.println(acc.getBalance());  // 1300.0\n// acc.balance = -9999;  // ERROR: balance is private"
      }
    ]
  },
  "packages": {
    "title": "Java Packages",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Packages & API"
      },
      {
        "type": "paragraph",
        "text": "A package in Java is used to group related classes. Think of it as\n<strong>a folder in a file directory</strong>. We use packages to avoid name conflicts, and \nto write a better maintainable code. Packages are divided into two categories:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "Built-in Packages (packages from the Java API)",
          "User-defined Packages (create your own packages)"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Built-in Packages"
      },
      {
        "type": "paragraph",
        "text": "The Java API is a library of prewritten classes, that are free to use, included in the\nJava Development Environment."
      },
      {
        "type": "paragraph",
        "text": "The library contains components for managing input, database programming, and much much \nmore. The complete list can be found at Oracles website: <a href=\"https://docs.oracle.com/javase/8/docs/api/\" target=\"_blank\">https://docs.oracle.com/javase/8/docs/api/</a>."
      },
      {
        "type": "paragraph",
        "text": "The library is divided into <strong>packages</strong> and <strong>classes</strong>. \nMeaning you can either import a single class (along with its methods and \nattributes), or a whole package that contain \nall the classes that belong to the specified package."
      },
      {
        "type": "paragraph",
        "text": "To use a class or a package from the library, you need to use the <code class=\"w3-codespan\">import</code> \nkeyword:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Import a Class"
      },
      {
        "type": "paragraph",
        "text": "If you find a class you want to use, for example, the <code class=\"w3-codespan\">Scanner</code> class, <strong>which is used to get \nuser input</strong>, write the following code:"
      },
      {
        "type": "paragraph",
        "text": "In the example above, <code class=\"w3-codespan\">java.util</code> is a package, while <code class=\"w3-codespan\">Scanner</code> is a class of \nthe <code class=\"w3-codespan\">java.util</code> package."
      },
      {
        "type": "paragraph",
        "text": "To use the <code class=\"w3-codespan\">Scanner</code> class, create an object of the class and use any of the available methods found in the <code class=\"w3-codespan\">Scanner</code> class documentation. \nIn our example, we will use the <code class=\"w3-codespan\">nextLine()</code> method, which is used to read a \ncomplete line:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Import a Package"
      },
      {
        "type": "paragraph",
        "text": "There are many packages to choose from. In the previous example, we used the <code class=\"w3-codespan\">Scanner</code> class from the <code class=\"w3-codespan\">java.util</code> package. This package also contains date and time \nfacilities, random-number generator and other utility classes."
      },
      {
        "type": "paragraph",
        "text": "To import a whole package, end the sentence with an asterisk sign (<code class=\"w3-codespan\">*</code>). \nThe following example \nwill import ALL the classes in the <code class=\"w3-codespan\">java.util</code> package:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Common Built-in Java Packages"
      },
      {
        "type": "table",
        "headers": ["Package", "What it provides", "Example classes"],
        "rows": [
          ["<code>java.lang</code>", "Core Java classes — imported automatically", "<code>String</code>, <code>Math</code>, <code>System</code>, <code>Integer</code>"],
          ["<code>java.util</code>", "Data structures, date/time, random numbers", "<code>ArrayList</code>, <code>HashMap</code>, <code>Scanner</code>, <code>Date</code>"],
          ["<code>java.io</code>", "Reading and writing files / streams", "<code>File</code>, <code>FileWriter</code>, <code>BufferedReader</code>"],
          ["<code>java.nio.file</code>", "Modern file &amp; path API (Java 7+)", "<code>Files</code>, <code>Path</code>, <code>Paths</code>"],
          ["<code>java.net</code>", "Networking — URLs, sockets, HTTP", "<code>URL</code>, <code>HttpURLConnection</code>"],
          ["<code>java.sql</code>", "Database connectivity (JDBC)", "<code>Connection</code>, <code>Statement</code>, <code>ResultSet</code>"]
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "User-defined Packages"
      },
      {
        "type": "paragraph",
        "text": "To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer:"
      },
      {
        "type": "paragraph",
        "text": "To create a package, use the <code class=\"w3-codespan\">package</code> keyword:"
      },
      {
        "type": "paragraph",
        "text": "Save the file as <b>MyPackageClass.java</b>, and compile it:"
      },
      {
        "type": "example",
        "title": "Example",
        "code": "C:\\Users\\Your Name>javac MyPackageClass.java"
      },
      {
        "type": "paragraph",
        "text": "Then compile the package:"
      },
      {
        "type": "example",
        "title": "Example",
        "code": "C:\\Users\\Your Name>javac -d . MyPackageClass.java"
      },
      {
        "type": "note",
        "text": "<p>This forces the compiler to create the \"mypack\" package.</p>\n  <p>The <code class=\"w3-codespan\">-d</code> keyword specifies the destination for where to save the class file. You \n  can use any directory name, like c:/user (windows), or, if you want to keep \n  the package within the same directory, you can use the dot sign \"<code class=\"w3-codespan\">.</code>\", like in \n  the example above.</p>\n<p><strong>Note:</strong> The package name should be written in lower case to avoid conflict with class names.</p>"
      },
      {
        "type": "paragraph",
        "text": "When we compiled the package in the example above, a new folder was created, called \"mypack\"."
      },
      {
        "type": "paragraph",
        "text": "To run the <b>MyPackageClass.java</b> file, write the following:"
      },
      {
        "type": "example",
        "title": "Example",
        "code": "C:\\Users\\Your Name>java mypack.MyPackageClass"
      },
      {
        "type": "paragraph",
        "text": "The output will be:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Creating Your Own Package — Quick Reference"
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Step 1 — Declare the package at the TOP of the file\npackage com.myapp.utils;\n\n// Step 2 — Define your class\npublic class StringHelper {\n    public static String shout(String s) {\n        return s.toUpperCase() + \"!\";\n    }\n}\n\n// Step 3 — Use it from another file\nimport com.myapp.utils.StringHelper;\n\npublic class Main {\n    public static void main(String[] args) {\n        System.out.println(StringHelper.shout(\"hello\"));\n        // Output: HELLO!\n    }\n}"
      },
      {
        "type": "note",
        "text": "<strong>Naming convention:</strong> Package names are always <strong>lowercase</strong> and use the reverse domain pattern: <code>com.companyname.projectname.module</code>. This guarantees globally unique package names across all Java projects."
      }
    ]
  },
  "inheritance": {
    "title": "Java Inheritance",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Inheritance"
      },
      {
        "type": "intro",
        "text": "<strong>Inheritance</strong> lets a child class automatically gain all the attributes and methods of a parent class. Write common code once in the parent — all children get it for free."
      },
      {
        "type": "playground",
        "subtype": "inheritance"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The extends Keyword"
      },
      {
        "type": "playground",
        "subtype": "syntax-anatomy",
        "config": {
          "title": "Inheritance with extends",
          "tokens": [
            {
              "text": "class",
              "type": "keyword"
            },
            {
              "text": " Dog",
              "type": "variable",
              "tip": "Child (subclass) — gets everything from Animal"
            },
            {
              "text": " extends",
              "type": "keyword",
              "tip": "Keyword that sets up inheritance"
            },
            {
              "text": " Animal",
              "type": "variable",
              "tip": "Parent (superclass) — the class being inherited from"
            },
            {
              "text": " {",
              "type": "punctuation"
            },
            {
              "text": "\n  // own fields and methods only",
              "type": "plain"
            },
            {
              "text": "\n}",
              "type": "punctuation"
            }
          ]
        }
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Child inherits parent methods",
          "rows": [
            {
              "code": "class Animal {",
              "output": ""
            },
            {
              "code": "  String name = \"Buddy\";",
              "output": ""
            },
            {
              "code": "  void eat() { System.out.println(name + \" is eating.\"); }",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "class Dog extends Animal {",
              "output": ""
            },
            {
              "code": "  void sound() { System.out.println(name + \" says: Woof!\"); }",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "Dog d = new Dog();",
              "output": ""
            },
            {
              "code": "d.eat();",
              "output": "Buddy is eating."
            },
            {
              "code": "d.sound();",
              "output": "Buddy says: Woof!"
            }
          ]
        }
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<strong>Subclass / child</strong> — the class that inherits. Uses <code class=\"w3-codespan\">extends</code>.",
          "<strong>Superclass / parent</strong> — the class being inherited from.",
          "Use <code class=\"w3-codespan\">protected</code> on parent attributes so child classes can access them.",
          "Use <code class=\"w3-codespan\">final class</code> to prevent any class from extending it."
        ]
      },
      {
        "type": "code",
        "language": "java",
        "code": "class Animal {\n    String name;\n    void eat() { System.out.println(name + \" eats.\"); }\n}\n\nclass Dog extends Animal {\n    @Override\n    void eat()  { System.out.println(name + \" eats dog food.\"); }\n    void bark() { System.out.println(name + \" says: Woof!\"); }\n}\n\nDog d = new Dog();\nd.name = \"Rex\";\nd.eat();   // Rex eats dog food.\nd.bark();  // Rex says: Woof!\n\n// Parent reference holds child object\nAnimal a = new Dog();\na.name = \"Buddy\";\na.eat();   // Buddy eats dog food. (runtime type = Dog)"
      }
    ]
  },
  "polymorphism": {
    "title": "Java Polymorphism",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Polymorphism"
      },
      {
        "type": "intro",
        "text": "<strong>Polymorphism</strong> means \"many forms\". The same method name behaves differently depending on which object calls it — each subclass provides its own implementation."
      },
      {
        "type": "playground",
        "subtype": "inheritance"
      },
      {
        "type": "playground",
        "subtype": "output",
        "config": {
          "title": "Same method — different behaviour",
          "rows": [
            {
              "code": "class Animal { void sound() { System.out.println(\"...\"); } }",
              "output": ""
            },
            {
              "code": "class Dog extends Animal {",
              "output": ""
            },
            {
              "code": "  @Override void sound() { System.out.println(\"Woof!\"); }",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "class Cat extends Animal {",
              "output": ""
            },
            {
              "code": "  @Override void sound() { System.out.println(\"Meow!\"); }",
              "output": ""
            },
            {
              "code": "}",
              "output": ""
            },
            {
              "code": "new Dog().sound();",
              "output": "Woof!"
            },
            {
              "code": "new Cat().sound();",
              "output": "Meow!"
            }
          ]
        }
      },
      {
        "type": "note",
        "text": "Use <code>@Override</code> when a child class replaces a parent method. It tells Java (and readers) that this method intentionally replaces the parent version — and the compiler will catch typos in the method signature."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Polymorphism in Action — List of Animals"
      },
      {
        "type": "paragraph",
        "text": "The real power of polymorphism is using a <strong>parent-type reference</strong> to hold any subclass object. You can loop over a list and call the same method — Java automatically calls the right version for each object."
      },
      {
        "type": "code",
        "language": "java",
        "code": "import java.util.ArrayList;\n\nArrayList&lt;Animal&gt; animals = new ArrayList&lt;&gt;();\nanimals.add(new Dog());\nanimals.add(new Cat());\nanimals.add(new Dog());\n\nfor (Animal a : animals) {\n    a.sound();   // Java calls Dog.sound() or Cat.sound() automatically\n}\n// Output:\n// Woof!\n// Meow!\n// Woof!"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Types of Polymorphism"
      },
      {
        "type": "table",
        "headers": ["Type", "When resolved", "Mechanism", "Example"],
        "rows": [
          ["Compile-time (static)", "At compile time", "Method overloading", "<code>area(r)</code> vs <code>area(w, h)</code>"],
          ["Runtime (dynamic)", "At run time", "Method overriding (<code>@Override</code>)", "<code>a.sound()</code> dispatches to <code>Dog</code> or <code>Cat</code>"]
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Why Polymorphism Matters"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<strong>Extensibility</strong> — add a new <code>Bird</code> subclass and existing loop code still works without changes",
          "<strong>Cleaner code</strong> — one variable type (<code>Animal</code>) handles all subtypes",
          "<strong>Loose coupling</strong> — callers don't need to know the exact subclass",
          "<strong>Open/Closed Principle</strong> — code is open for extension but closed for modification"
        ]
      }
    ]
  },
  "inner-classes": {
    "title": "Java Inner Classes",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Inner Classes"
      },
      {
        "type": "paragraph",
        "text": "In Java, it is also possible to nest classes (a class within a class). The purpose \nof nested classes is to group classes that belong together, which makes your code more readable and maintainable."
      },
      {
        "type": "paragraph",
        "text": "To access the inner class, create an object of the outer class, and then create an object of the inner class:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Private Inner Class"
      },
      {
        "type": "paragraph",
        "text": "Unlike a \"regular\" class, an inner class can be <code class=\"w3-codespan\">private</code> or <code class=\"w3-codespan\">protected</code>. \nIf you don't want outside objects to access the inner class, declare \nthe class as <code class=\"w3-codespan\">private</code>:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Static Inner Class"
      },
      {
        "type": "paragraph",
        "text": "An inner class can also be <code class=\"w3-codespan\">static</code>, which means that you can access it without \ncreating an object of the outer class:"
      },
      {
        "type": "note",
        "text": "<p><strong>Note:</strong> just like <code class=\"w3-codespan\">static</code> attributes and methods, a <code class=\"w3-codespan\">static</code> inner class does not have access to members of the outer class.</p>"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Access Outer Class From Inner Class"
      },
      {
        "type": "playground",
        "subtype": "inner-class"
      },
      {
        "type": "code",
        "language": "java",
        "code": "class OuterClass {\n    int x = 10;\n\n    class InnerClass {\n        void show() {\n            // Inner class accesses outer class field\n            System.out.println(\"Outer x = \" + x);\n        }\n    }\n\n    static class StaticInner {\n        void greet() {\n            System.out.println(\"Hello from static inner class!\");\n        }\n    }\n}\n\n// Regular inner class (needs outer instance)\nOuterClass outer = new OuterClass();\nOuterClass.InnerClass inner = outer.new InnerClass();\ninner.show();   // Outer x = 10\n\n// Static inner class (no outer instance needed)\nOuterClass.StaticInner si = new OuterClass.StaticInner();\nsi.greet();     // Hello from static inner class!"
      },
      {
        "type": "paragraph",
        "text": "One advantage of inner classes, is that they can access attributes and methods of the outer class:"
      }
    ]
  },
  "abstraction": {
    "title": "Java Abstraction",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Abstract Classes and Methods"
      },
      {
        "type": "paragraph",
        "text": "Data <strong>abstraction</strong> is the process of hiding certain details and showing only essential information to the user.<br>\nAbstraction can be achieved with either <strong>abstract classes</strong> or \n<a href=\"#/java/interface\"><strong>interfaces</strong></a> (which you will learn more about in the next chapter)."
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">abstract</code> keyword is a non-access modifier, used for classes and methods:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<strong>Abstract class:</strong> is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).",
          "<strong>Abstract method:</strong> can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from)."
        ]
      },
      {
        "type": "paragraph",
        "text": "An abstract class can have both abstract and regular methods:"
      },
      {
        "type": "paragraph",
        "text": "From the example above, it is not possible to create an object of the Animal class:"
      },
      {
        "type": "paragraph",
        "text": "To access the abstract class, it must be inherited from another class. Let's convert the Animal class we used in the <a href=\"#/java/polymorphism\">Polymorphism</a> chapter to an abstract class:"
      },
      {
        "type": "note",
        "text": "<p>Remember from the <a href=\"#/java/inheritance\">Inheritance chapter</a> that we use the <code class=\"w3-codespan\">extends</code> keyword to inherit from a class.</p>"
      },
      {
        "type": "playground",
        "subtype": "abstraction"
      },
      {
        "type": "note",
        "text": "<h4>Why And When To Use Abstract Classes and Methods?</h4>\n<p>To achieve security - hide certain details and only show the important \ndetails of an object.</p>\n<p><strong>Note:</strong> Abstraction can also be achieved with <a href=\"#/java/interface\">Interfaces</a>, which you will learn more about in the next chapter.</p>"
      },
      {
        "type": "code",
        "language": "java",
        "code": "abstract class Shape {\n    String color;\n    abstract double area();  // no body \u2014 subclasses must provide it\n\n    void describe() {\n        System.out.println(color + \" shape, area = \" + area());\n    }\n}\n\nclass Circle extends Shape {\n    double r;\n    Circle(String c, double r) { this.color = c; this.r = r; }\n    double area() { return 3.14159 * r * r; }\n}\n\nclass Rectangle extends Shape {\n    double w, h;\n    Rectangle(String c, double w, double h) { this.color = c; this.w = w; this.h = h; }\n    double area() { return w * h; }\n}\n\nnew Circle(\"red\", 5).describe();      // red shape, area = 78.53975\nnew Rectangle(\"blue\", 4, 6).describe(); // blue shape, area = 24.0"
      }
    ]
  },
  "interface": {
    "title": "Java Interface",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Interfaces"
      },
      {
        "type": "paragraph",
        "text": "Another way to achieve <a href=\"#/java/abstraction\">abstraction</a> in Java, is with interfaces."
      },
      {
        "type": "paragraph",
        "text": "An <code class=\"w3-codespan\">interface</code> is a completely \"<strong>abstract class</strong>\" \nthat is used to group related methods with empty bodies:"
      },
      {
        "type": "paragraph",
        "text": "To access the interface methods, the interface must be \"implemented\" \n(kinda like inherited) by another class with the <code class=\"w3-codespan\">implements</code> \nkeyword (instead of <code class=\"w3-codespan\">extends</code>). The body of the \ninterface method is provided by the \"implement\" class:"
      },
      {
        "type": "note",
        "text": "<h4>Notes on Interfaces:</h4>\n<ul>\n<li>Like <strong>abstract classes</strong>, interfaces <strong>cannot</strong> be used to create objects (in the example above, \nit is not possible to create an \"Animal\" object in the MyMainClass)</li>\n  <li>Interface methods do not have a body - the \nbody is provided by the \"implement\" class</li>\n  <li>On implementation of an interface, you must override all of its methods</li>\n  <li>Interface methods are by default <code class=\"w3-codespan\">abstract</code> and \n  <code class=\"w3-codespan\">public</code></li>\n  <li>Interface attributes are by default <code class=\"w3-codespan\">public</code>, \n  <code class=\"w3-codespan\">static</code> and <code class=\"w3-codespan\">final</code></li>\n  <li>An interface cannot contain a constructor (as it cannot be used to create objects)</li>\n</ul>\n\n<h4>Why And When To Use Interfaces?</h4>\n<p>1) To achieve security - hide certain details and only show the important \ndetails of an object (interface).</p>\n  <p>2) Java does not support \"multiple inheritance\" (a class can only inherit from one superclass). However, it can be achieved \n  with interfaces, because the class can <strong>implement</strong> multiple interfaces.\n  <strong>Note:</strong> To implement multiple interfaces, separate them with a comma (see example below).</p>"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Multiple Interfaces"
      },
      {
        "type": "playground",
        "subtype": "interface"
      },
      {
        "type": "paragraph",
        "text": "To implement multiple interfaces, separate them with a comma:"
      },
      {
        "type": "code",
        "language": "java",
        "code": "interface Drawable {\n    void draw();                             // abstract by default\n    default String type() { return \"2D\"; }  // default method\n}\n\ninterface Resizable {\n    void resize(int factor);\n}\n\nclass Square implements Drawable, Resizable {\n    int side;\n    Square(int s) { this.side = s; }\n    public void draw()        { System.out.println(\"Square \" + side + \"x\" + side); }\n    public void resize(int f) { side *= f; }\n}\n\nSquare sq = new Square(4);\nsq.draw();            // Square 4x4\nsq.resize(3);\nsq.draw();            // Square 12x12\nSystem.out.println(sq.type()); // 2D"
      }
    ]
  },
  "enums": {
    "title": "Java Enums",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Enums"
      },
      {
        "type": "paragraph",
        "text": "An <code class=\"w3-codespan\">enum</code> is a special \"class\" that represents a group of \n<strong>constants</strong> (unchangeable variables, like <code class=\"w3-codespan\">final</code> variables)."
      },
      {
        "type": "paragraph",
        "text": "To create an <code class=\"w3-codespan\">enum</code>, use the <code class=\"w3-codespan\">enum</code> keyword (instead of class or interface), and separate \nthe constants with a comma. Note that they should be in uppercase letters:"
      },
      {
        "type": "example",
        "title": "Example",
        "code": "Level myVar = Level.MEDIUM;"
      },
      {
        "type": "note",
        "text": "<p><strong>Enum</strong> is short for \"enumerations\", which means \"specifically listed\".</p>"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Enum inside a Class"
      },
      {
        "type": "paragraph",
        "text": "You can also have an <code class=\"w3-codespan\">enum</code> inside a class:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Enum in a Switch Statement"
      },
      {
        "type": "paragraph",
        "text": "Enums are often used in <code class=\"w3-codespan\">switch</code> statements to check for corresponding values:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Loop Through an Enum"
      },
      {
        "type": "paragraph",
        "text": "The enum type has a <code class=\"w3-codespan\">values()</code> method, which returns an array of all enum constants. This method is useful when you want to loop through the constants of an enum:"
      },
      {
        "type": "playground",
        "subtype": "enum"
      },
      {
        "type": "code",
        "language": "java",
        "code": "enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }\n\nDay today = Day.WED;\nSystem.out.println(today);           // WED\nSystem.out.println(today.name());    // WED\nSystem.out.println(today.ordinal()); // 2 (0-based index)\n\n// Enum in switch\nswitch (today) {\n    case SAT: case SUN:\n        System.out.println(\"Weekend!\"); break;\n    default:\n        System.out.println(\"Weekday\");\n}\n// Output: Weekday\n\n// Loop through all enum values\nfor (Day d : Day.values()) {\n    System.out.print(d + \" \");\n}\n// MON TUE WED THU FRI SAT SUN"
      },
      {
        "type": "note",
        "text": "<h4>Difference between Enums and Classes</h4>\n<p>An <code class=\"w3-codespan\">enum</code> can, just like a <code class=\"w3-codespan\">class</code>, have attributes and methods. The only \ndifference is that enum constants are <code class=\"w3-codespan\">public</code>, <code class=\"w3-codespan\">static</code> and <code class=\"w3-codespan\">final</code> \n(unchangeable - cannot be overridden).</p>\n<p>An <code class=\"w3-codespan\">enum</code> cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).</p>\n<h4>Why And When To Use Enums?</h4>\n\n<p>Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc.</p>"
      }
    ]
  },
  "user-input": {
    "title": "Java User Input (Scanner)",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java User Input"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">Scanner</code> class is used to get \nuser input, and it is found in the <code class=\"w3-codespan\">java.util</code> package."
      },
      {
        "type": "paragraph",
        "text": "To use the <code class=\"w3-codespan\">Scanner</code> class, create an object of the class and use any of the available methods found in the <code class=\"w3-codespan\">Scanner</code> class documentation. \nIn our example, we will use the <code class=\"w3-codespan\">nextLine()</code> method, which is used to read Strings:"
      },
      {
        "type": "note",
        "text": "<p>If you don't know what a package is, read our <a href=\"#/java/packages\">Java Packages Tutorial</a>.</p>"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Input Types"
      },
      {
        "type": "paragraph",
        "text": "In the example above, we used the <code class=\"w3-codespan\">nextLine()</code> method, which is used to read Strings. To read other types, look at the table below:"
      },
      {
        "type": "paragraph",
        "text": "In the example below, we use different methods to read data of various types:"
      },
      {
        "type": "playground",
        "subtype": "user-input"
      },
      {
        "type": "code",
        "language": "java",
        "code": "import java.util.Scanner;\n\nScanner sc = new Scanner(System.in);\n\nSystem.out.print(\"Enter your name: \");\nString name = sc.nextLine();     // reads a String\n\nSystem.out.print(\"Enter your age: \");\nint age = sc.nextInt();          // reads an int\n\nSystem.out.print(\"Enter your GPA: \");\ndouble gpa = sc.nextDouble();    // reads a double\n\nSystem.out.println(\"Hi \" + name + \"! Age: \" + age + \", GPA: \" + gpa);\nsc.close();\n// Sample output: Hi Alice! Age: 20, GPA: 3.8"
      },
      {
        "type": "note",
        "text": "<p><strong>Note:</strong> If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like \"InputMismatchException\").</p>\n<p>You can read more about exceptions and how to handle errors in the <a href=\"#/java/exceptions\">Exceptions chapter</a>.</p>"
      }
    ]
  },
  "date": {
    "title": "Java Date and Time",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Dates"
      },
      {
        "type": "paragraph",
        "text": "Java does not have a built-in Date class, but we can import the <code class=\"w3-codespan\">java.time</code> \npackage to work with the date and time API. The package includes many date and time classes. \nFor example:"
      },
      {
        "type": "note",
        "text": "<p>If you don't know what a package is, read our <a href=\"#/java/packages\">Java Packages Tutorial</a>.</p>"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Display Current Date"
      },
      {
        "type": "paragraph",
        "text": "To display the current date, import the <code class=\"w3-codespan\">java.time.LocalDate</code> class, and use its <code class=\"w3-codespan\">now()</code> method:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Display Current Time"
      },
      {
        "type": "paragraph",
        "text": "To display the current time (hour, minute, second, and nanoseconds), import the <code class=\"w3-codespan\">java.time.LocalTime</code> class, and use its <code class=\"w3-codespan\">now()</code> method:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Display Current Date and Time"
      },
      {
        "type": "paragraph",
        "text": "To display the current date and time, import the <code class=\"w3-codespan\">java.time.LocalDateTime</code> class, and use its <code class=\"w3-codespan\">now()</code> method:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Formatting Date and Time"
      },
      {
        "type": "paragraph",
        "text": "The \"T\" in the example above is used to separate the date from the time. You can use the <code class=\"w3-codespan\">DateTimeFormatter</code> class \nwith the <code class=\"w3-codespan\">ofPattern()</code> method in the same package to format or parse date-time objects. \nThe following example will remove both the \"T\" and nanoseconds from the date-time:"
      },
      {
        "type": "playground",
        "subtype": "date"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">ofPattern()</code> method accepts all sorts of values, if you want to display \nthe date and time in a different format. For example:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Common Date Format Patterns"
      },
      {
        "type": "table",
        "headers": ["Pattern", "Meaning", "Example output"],
        "rows": [
          ["<code>yyyy</code>", "4-digit year", "<code>2025</code>"],
          ["<code>MM</code>", "2-digit month (01–12)", "<code>04</code>"],
          ["<code>dd</code>", "2-digit day (01–31)", "<code>14</code>"],
          ["<code>HH</code>", "Hour in 24-hour format (00–23)", "<code>15</code>"],
          ["<code>mm</code>", "Minutes (00–59)", "<code>30</code>"],
          ["<code>ss</code>", "Seconds (00–59)", "<code>05</code>"],
          ["<code>EEEE</code>", "Full day name", "<code>Monday</code>"],
          ["<code>MMMM</code>", "Full month name", "<code>April</code>"]
        ]
      },
      {
        "type": "code",
        "language": "java",
        "code": "import java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\n\nLocalDateTime now = LocalDateTime.now();\n\n// Different format patterns\nDateTimeFormatter f1 = DateTimeFormatter.ofPattern(\"dd/MM/yyyy\");\nDateTimeFormatter f2 = DateTimeFormatter.ofPattern(\"EEEE, MMMM dd yyyy\");\nDateTimeFormatter f3 = DateTimeFormatter.ofPattern(\"hh:mm a\");  // 12-hour with AM/PM\nDateTimeFormatter f4 = DateTimeFormatter.ofPattern(\"dd-MM-yyyy HH:mm:ss\");\n\nSystem.out.println(now.format(f1));  // 14/04/2025\nSystem.out.println(now.format(f2));  // Monday, April 14 2025\nSystem.out.println(now.format(f3));  // 03:30 PM\nSystem.out.println(now.format(f4));  // 14-04-2025 15:30:05"
      },
      {
        "type": "note",
        "text": "<strong>Prefer <code>java.time</code> over <code>java.util.Date</code></strong>: The <code>java.time</code> package (introduced in Java 8) is immutable, thread-safe, and much easier to use than the older <code>Date</code> and <code>Calendar</code> classes."
      }
    ]
  },
  "arraylist": {
    "title": "Java ArrayList",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java ArrayList"
      },
      {
        "type": "paragraph",
        "text": "An <code class=\"w3-codespan\">ArrayList</code> is like a resizable <a href=\"#/java/arrays\">array</a>."
      },
      {
        "type": "paragraph",
        "text": "It is part of the <code class=\"w3-codespan\">java.util</code> package and implements the <a href=\"java_list.html\"><code class=\"w3-codespan\">List</code></a> interface."
      },
      {
        "type": "paragraph",
        "text": "The difference between a built-in <a href=\"#/java/arrays\">array</a> and an <code class=\"w3-codespan\">ArrayList</code> in Java, is that the size of an array cannot be modified (if you want to \nadd or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an <code class=\"w3-codespan\">ArrayList</code> whenever you want."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Create an ArrayList"
      },
      {
        "type": "paragraph",
        "text": "To use an <code class=\"w3-codespan\">ArrayList</code>, you must first import it from <code class=\"w3-codespan\">java.util</code>:"
      },
      {
        "type": "paragraph",
        "text": "Now you can use methods like <code class=\"w3-codespan\">add()</code>, <code class=\"w3-codespan\">get()</code>, <code class=\"w3-codespan\">set()</code>, and <code class=\"w3-codespan\">remove()</code> to manage your list of elements."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Add Elements"
      },
      {
        "type": "paragraph",
        "text": "To add elements to an \n<code class=\"w3-codespan\">ArrayList</code>, use the <code class=\"w3-codespan\">add()</code> method:"
      },
      {
        "type": "paragraph",
        "text": "You can also add an element at a specified position by referring to the index \nnumber:"
      },
      {
        "type": "note",
        "text": "<p>An <code class=\"w3-codespan\">ArrayList</code> keeps elements in the same order you add them, so the first item you add will be at index 0, the next at index 1, and so on.</p>"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Access an Element"
      },
      {
        "type": "paragraph",
        "text": "To access an element in the <code class=\"w3-codespan\">ArrayList</code>, use the <code class=\"w3-codespan\">get()</code> method and refer to the index number:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Change an Element"
      },
      {
        "type": "paragraph",
        "text": "To modify an element, use the <code class=\"w3-codespan\">set()</code> method \nand refer to the index number:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Remove an Element"
      },
      {
        "type": "paragraph",
        "text": "To remove an element, use the <code class=\"w3-codespan\">remove()</code> method \nand refer to the index number:"
      },
      {
        "type": "paragraph",
        "text": "To remove all the elements in the <code class=\"w3-codespan\">ArrayList</code>, use the <code class=\"w3-codespan\">clear()</code> method:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "ArrayList Size"
      },
      {
        "type": "paragraph",
        "text": "To find out how many elements an <code class=\"w3-codespan\">ArrayList</code> have, use the <code class=\"w3-codespan\">size</code> method:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Loop Through an ArrayList"
      },
      {
        "type": "paragraph",
        "text": "Loop through the elements of an <code class=\"w3-codespan\">ArrayList</code> with a <code class=\"w3-codespan\">for</code> loop, and use the <code class=\"w3-codespan\">\nsize()</code> method to specify how many times the loop should run:"
      },
      {
        "type": "paragraph",
        "text": "You can also loop through an <code class=\"w3-codespan\">ArrayList</code> with the <strong>for-each</strong> loop:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Other Types"
      },
      {
        "type": "paragraph",
        "text": "Elements in an <code class=\"w3-codespan\">ArrayList</code> are actually objects. In the examples above, we created elements \n(objects) of type \"String\". Remember that a <code class=\"w3-codespan\">String</code> in Java is an object (not a primitive type). To use other types, such as <code class=\"w3-codespan\">int</code>, you must specify an equivalent <a href=\"#/java/wrapper-classes\">wrapper class</a>: <code class=\"w3-codespan\">Integer</code>. For other primitive types, \nuse: <code class=\"w3-codespan\">Boolean</code> for boolean, <code class=\"w3-codespan\">Character</code> for char, <code class=\"w3-codespan\">Double</code> for double, \netc:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Sort an ArrayList"
      },
      {
        "type": "paragraph",
        "text": "Another useful class in the <code class=\"w3-codespan\">java.util</code> package is the <code class=\"w3-codespan\">Collections</code> class, which include the <code class=\"w3-codespan\">sort()</code> method for sorting lists \nalphabetically or numerically:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The var Keyword"
      },
      {
        "type": "paragraph",
        "text": "From Java 10, you can use the <code class=\"w3-codespan\">var</code> keyword to declare an <code class=\"w3-codespan\">ArrayList</code> variable without writing the type twice.  \nThe compiler figures out the type from the value you assign."
      },
      {
        "type": "paragraph",
        "text": "This makes code shorter, <strong>but many developers still use the full type for clarity</strong>.  \nSince <code class=\"w3-codespan\">var</code> is valid Java, you may see it in other code, so it's good to know that it exists:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The List Interface"
      },
      {
        "type": "paragraph",
        "text": "<strong>Note:</strong> Sometimes you will see both <code class=\"w3-codespan\">List</code> and <code class=\"w3-codespan\">ArrayList</code> in Java code, like this:"
      },
      {
        "type": "paragraph",
        "text": "This means the variable (cars) is declared as a <a href=\"java_list.html\"><code class=\"w3-codespan\">List</code></a> (the interface), but it stores an <code class=\"w3-codespan\">ArrayList</code> object (the actual list). Since <code class=\"w3-codespan\">ArrayList</code> implements the <code class=\"w3-codespan\">List</code> interface, this is possible."
      },
      {
        "type": "playground",
        "subtype": "arraylist"
      },
      {
        "type": "header",
        "level": 2,
        "text": "ArrayList Quick-Reference Methods"
      },
      {
        "type": "table",
        "headers": ["Method", "Description", "Example"],
        "rows": [
          ["<code>add(e)</code>", "Append element to end", "<code>list.add(\"Java\")</code>"],
          ["<code>add(i, e)</code>", "Insert at index", "<code>list.add(0, \"First\")</code>"],
          ["<code>get(i)</code>", "Retrieve element at index", "<code>list.get(2)</code>"],
          ["<code>set(i, e)</code>", "Replace element at index", "<code>list.set(1, \"New\")</code>"],
          ["<code>remove(i)</code>", "Remove element at index", "<code>list.remove(0)</code>"],
          ["<code>remove(obj)</code>", "Remove first occurrence of object", "<code>list.remove(\"Java\")</code>"],
          ["<code>size()</code>", "Number of elements", "<code>list.size()</code>"],
          ["<code>contains(e)</code>", "Check if element exists", "<code>list.contains(\"Python\")</code>"],
          ["<code>indexOf(e)</code>", "Index of first occurrence (−1 if absent)", "<code>list.indexOf(\"Java\")</code>"],
          ["<code>clear()</code>", "Remove all elements", "<code>list.clear()</code>"],
          ["<code>isEmpty()</code>", "True if no elements", "<code>list.isEmpty()</code>"]
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Sorting and Filtering with Streams"
      },
      {
        "type": "code",
        "language": "java",
        "code": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.stream.Collectors;\n\nArrayList&lt;String&gt; names = new ArrayList&lt;&gt;();\nnames.add(\"Charlie\"); names.add(\"Alice\"); names.add(\"Bob\"); names.add(\"Anna\");\n\n// Sort alphabetically\nCollections.sort(names);\nSystem.out.println(names);  // [Alice, Anna, Bob, Charlie]\n\n// Sort in reverse\nCollections.sort(names, Collections.reverseOrder());\nSystem.out.println(names);  // [Charlie, Bob, Anna, Alice]\n\n// Stream: filter names starting with 'A'\nvar filtered = names.stream()\n    .filter(n -&gt; n.startsWith(\"A\"))\n    .collect(Collectors.toList());\nSystem.out.println(filtered);  // [Anna, Alice]\n\n// Stream: uppercase all\nnames.stream()\n    .map(String::toUpperCase)\n    .forEach(System.out::println);"
      },
      {
        "type": "paragraph",
        "text": "It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later."
      }
    ]
  },
  "linkedlist": {
    "title": "Java LinkedList",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java LinkedList"
      },
      {
        "type": "paragraph",
        "text": "In the previous chapter, you learned about the <a href=\"#/java/arraylist\"><code class=\"w3-codespan\">ArrayList</code></a> class. The <code class=\"w3-codespan\">LinkedList</code> class is \nalmost identical to the \n<code class=\"w3-codespan\">ArrayList</code>:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "ArrayList vs. LinkedList"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">LinkedList</code> class is a collection which can contain many objects of the same type,\njust like the <code class=\"w3-codespan\">ArrayList</code>."
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">LinkedList</code> class has the same methods as <code class=\"w3-codespan\">ArrayList</code> because both follow the <a href=\"java_list.html\"><code class=\"w3-codespan\">List</code></a> interface.\nThis means you can add, change, remove, or clear elements in a <code class=\"w3-codespan\">LinkedList</code> just like you would with an <code class=\"w3-codespan\">ArrayList</code>."
      },
      {
        "type": "paragraph",
        "text": "However, while the <code class=\"w3-codespan\">ArrayList</code> class and the <code class=\"w3-codespan\">LinkedList</code> class can be used in the same way,\nthey are built very differently."
      },
      {
        "type": "header",
        "level": 3,
        "text": "How the ArrayList works"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">ArrayList</code> class has a regular array inside it. When an element is added, it is placed\ninto the array. If the array is not big enough, a new, larger array is created to replace the\nold one and the old one is removed."
      },
      {
        "type": "header",
        "level": 3,
        "text": "How the LinkedList works"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">LinkedList</code> stores its elements in \"containers.\" The list has a link to the first container\nand each container has a link to the next container in the list. To add an element to the list,\nthe element is placed into a new container and that container is linked to one of the other\ncontainers in the list."
      },
      {
        "type": "note",
        "text": "<h3>When To Use</h3>\n<p>Use an <code class=\"w3-codespan\">ArrayList</code> for storing and accessing data, and <code class=\"w3-codespan\">LinkedList</code>  to \nmanipulate data.</p>"
      },
      {
        "type": "header",
        "level": 2,
        "text": "LinkedList Methods"
      },
      {
        "type": "paragraph",
        "text": "For many cases, the <code class=\"w3-codespan\">ArrayList</code> is more efficient as it is common to need access to\nrandom elements in the list, but the <code class=\"w3-codespan\">LinkedList</code> provides several methods to do certain\noperations more efficiently:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The var Keyword"
      },
      {
        "type": "paragraph",
        "text": "From Java 10, you can use the <code class=\"w3-codespan\">var</code> keyword to declare a <code class=\"w3-codespan\">LinkedList</code> variable without writing the type twice.  \nThe compiler figures out the type from the value you assign."
      },
      {
        "type": "paragraph",
        "text": "This makes code shorter, <strong>but many developers still use the full type for clarity</strong>.  \nSince <code class=\"w3-codespan\">var</code> is valid Java, you may see it in other code, so it's good to know that it exists:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The List Interface"
      },
      {
        "type": "paragraph",
        "text": "<strong>Note:</strong> Sometimes you will see both <code class=\"w3-codespan\">List</code> and <code class=\"w3-codespan\">LinkedList</code> in Java code, like this:"
      },
      {
        "type": "paragraph",
        "text": "This means the variable (cars) is declared as a <a href=\"java_list.html\"><code class=\"w3-codespan\">List</code></a> (the interface), but it stores a <code class=\"w3-codespan\">LinkedList</code> object (the actual list). Since <code class=\"w3-codespan\">LinkedList</code> implements the <code class=\"w3-codespan\">List</code> interface, this is possible."
      },
      {
        "type": "playground",
        "subtype": "linkedlist"
      },
      {
        "type": "code",
        "language": "java",
        "code": "LinkedList&lt;String&gt; cars = new LinkedList&lt;&gt;();\ncars.add(\"Volvo\");\ncars.add(\"BMW\");\ncars.add(\"Ford\");\n\n// LinkedList-specific methods\ncars.addFirst(\"Mazda\");   // insert at start\ncars.addLast(\"Toyota\");   // insert at end\ncars.removeFirst();        // remove first element\ncars.removeLast();         // remove last element\n\nSystem.out.println(cars.getFirst()); // Volvo\nSystem.out.println(cars.getLast());  // Ford\nSystem.out.println(cars);            // [Volvo, BMW, Ford]"
      },
      {
        "type": "paragraph",
        "text": "It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later."
      }
    ]
  },
  "hashmap": {
    "title": "Java HashMap",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java HashMap"
      },
      {
        "type": "paragraph",
        "text": "A <code class=\"w3-codespan\">HashMap</code> stores items in <strong>key/value pairs</strong>, where each key maps to a specific value."
      },
      {
        "type": "paragraph",
        "text": "It is part of the <code class=\"w3-codespan\">java.util</code> package and implements the \n  <a href=\"java_map.html\"><code class=\"w3-codespan\">Map</code></a> interface."
      },
      {
        "type": "paragraph",
        "text": "Instead of accessing elements by an index (like with <a href=\"#/java/arraylist\">ArrayList</a>), you use a <strong>key</strong> to retrieve its associated <strong>value</strong>."
      },
      {
        "type": "paragraph",
        "text": "A <code class=\"w3-codespan\">HashMap</code> can store many different combinations, such as:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<code class=\"w3-codespan\">String</code> keys and <code class=\"w3-codespan\">Integer</code> values",
          "<code class=\"w3-codespan\">String</code> keys and <code class=\"w3-codespan\">String</code> values"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Create a HashMap"
      },
      {
        "type": "paragraph",
        "text": "Create a <code class=\"w3-codespan\">HashMap</code> object called <code class=\"w3-codespan\">capitalCities</code> that will store \n  <code class=\"w3-codespan\">String</code> keys and <code class=\"w3-codespan\">String</code> values:"
      },
      {
        "type": "paragraph",
        "text": "Now you can use methods like <code class=\"w3-codespan\">put()</code> to add key/value pairs, \n  <code class=\"w3-codespan\">get()</code> to retrieve a value by key, \n  and <code class=\"w3-codespan\">remove()</code> to delete an entry - all by using keys instead of index numbers."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Add Items"
      },
      {
        "type": "paragraph",
        "text": "To add items to a <code class=\"w3-codespan\">HashMap</code>, use the <code class=\"w3-codespan\">put()</code> method:"
      },
      {
        "type": "paragraph",
        "text": "<strong>Note:</strong> In the example above, if the same key (like \"Norway\") is added more than once, the <em>latest</em> value will overwrite the previous one, because keys in a <code class=\"w3-codespan\">HashMap</code> must be unique."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Access an Item"
      },
      {
        "type": "paragraph",
        "text": "To access a value in the <code class=\"w3-codespan\">HashMap</code>, use the <code class=\"w3-codespan\">get()</code> method and refer to \nits key:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Remove an Item"
      },
      {
        "type": "paragraph",
        "text": "To remove an item, use the <code class=\"w3-codespan\">remove()</code> method \nand refer to the key:"
      },
      {
        "type": "paragraph",
        "text": "To remove all items, use the <code class=\"w3-codespan\">clear()</code> method:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "HashMap Size"
      },
      {
        "type": "paragraph",
        "text": "To find out how many items there are, use the <code class=\"w3-codespan\">size()</code> method:"
      },
      {
        "type": "paragraph",
        "text": "<strong>Note:</strong> The size only counts unique keys. If a key is added more than once, only the latest value is kept."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Loop Through a HashMap"
      },
      {
        "type": "paragraph",
        "text": "Loop through the items of a <code class=\"w3-codespan\">HashMap</code> with a <strong>for-each</strong> loop."
      },
      {
        "type": "paragraph",
        "text": "<strong>Note:</strong> Use the <code class=\"w3-codespan\">keySet()</code> method if you only want the keys, and use the <code class=\"w3-codespan\">values()</code> method if you only want the values:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Other Types"
      },
      {
        "type": "paragraph",
        "text": "Keys and values in a <code class=\"w3-codespan\">HashMap</code> are actually objects. In the examples above, we used objects of type \"String\". Remember that a <code class=\"w3-codespan\">String</code> in Java is an object (not a primitive type). To use other types, such as <code class=\"w3-codespan\">int</code>, you must specify an equivalent <a href=\"#/java/wrapper-classes\">wrapper class</a>: <code class=\"w3-codespan\">Integer</code>. For other primitive types, \nuse: <code class=\"w3-codespan\">Boolean</code> for boolean, <code class=\"w3-codespan\">Character</code> for char, <code class=\"w3-codespan\">Double</code> for double, \netc:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "When Order Matters"
      },
      {
        "type": "paragraph",
        "text": "In the next chapter, you will learn about <a href=\"java_treemap.html\"><code class=\"w3-codespan\">TreeMap</code></a>, which stores key/value pairs <strong>in sorted order by key</strong>."
      },
      {
        "type": "header",
        "level": 2,
        "text": "The var Keyword"
      },
      {
        "type": "paragraph",
        "text": "From Java 10, you can use the <code class=\"w3-codespan\">var</code> keyword to declare a <code class=\"w3-codespan\">HashMap</code> variable without writing the type twice.  \nThe compiler figures out the type from the value you assign."
      },
      {
        "type": "paragraph",
        "text": "This makes code shorter, <strong>but many developers still use the full type for clarity</strong>.  \nSince <code class=\"w3-codespan\">var</code> is valid Java, you may see it in other code, so it's good to know that it exists:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The Map Interface"
      },
      {
        "type": "paragraph",
        "text": "<strong>Note:</strong> Sometimes you will see both <code class=\"w3-codespan\">Map</code> and <code class=\"w3-codespan\">HashMap</code> in Java code, like this:"
      },
      {
        "type": "paragraph",
        "text": "This means the variable (capitalCities) is declared as a <a href=\"java_map.html\"><code class=\"w3-codespan\">Map</code></a> (the interface), but it stores a <code class=\"w3-codespan\">HashMap</code> object (the actual map). Since <code class=\"w3-codespan\">HashMap</code> implements the <code class=\"w3-codespan\">Map</code> interface, this is possible."
      },
      {
        "type": "playground",
        "subtype": "hashmap"
      },
      {
        "type": "header",
        "level": 2,
        "text": "HashMap Time Complexity"
      },
      {
        "type": "table",
        "headers": ["Operation", "Average case", "Worst case", "Notes"],
        "rows": [
          ["<code>put(key, val)</code>", "O(1)", "O(n)", "O(n) only if many hash collisions"],
          ["<code>get(key)</code>", "O(1)", "O(n)", "Hash collisions degrade to O(n)"],
          ["<code>containsKey(key)</code>", "O(1)", "O(n)", "Same as get()"],
          ["<code>remove(key)</code>", "O(1)", "O(n)", "—"],
          ["Iteration (all entries)", "O(n)", "O(n)", "Must visit every bucket"]
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Iterating a HashMap"
      },
      {
        "type": "code",
        "language": "java",
        "code": "HashMap&lt;String, Integer&gt; scores = new HashMap&lt;&gt;();\nscores.put(\"Alice\", 95);\nscores.put(\"Bob\",   87);\nscores.put(\"Carol\", 92);\n\n// entrySet() — iterate over key+value pairs\nfor (Map.Entry&lt;String, Integer&gt; entry : scores.entrySet()) {\n    System.out.println(entry.getKey() + \" → \" + entry.getValue());\n}\n\n// forEach() — lambda shorthand (Java 8+)\nscores.forEach((name, score) ->\n    System.out.println(name + \" scored \" + score)\n);\n\n// getOrDefault() — safe access, no NullPointerException\nint davidScore = scores.getOrDefault(\"David\", 0);\nSystem.out.println(\"David: \" + davidScore);  // David: 0"
      },
      {
        "type": "paragraph",
        "text": "It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later."
      }
    ]
  },
  "hashset": {
    "title": "Java HashSet",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java HashSet"
      },
      {
        "type": "paragraph",
        "text": "A <code class=\"w3-codespan\">HashSet</code> is a collection of elements where every element is \n<strong>unique</strong>."
      },
      {
        "type": "paragraph",
        "text": "It is part of the <code class=\"w3-codespan\">java.util</code> package and implements the <a href=\"java_set.html\"><code class=\"w3-codespan\">Set</code></a> interface."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Create a HashSet"
      },
      {
        "type": "paragraph",
        "text": "Now you can use methods like <code class=\"w3-codespan\">add()</code>, <code class=\"w3-codespan\">contains()</code>, and <code class=\"w3-codespan\">remove()</code> to manage your collection of unique elements."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Add Elements"
      },
      {
        "type": "paragraph",
        "text": "To add elements to a <code class=\"w3-codespan\">HashSet</code>, use the <code class=\"w3-codespan\">add()</code> method:"
      },
      {
        "type": "paragraph",
        "text": "<strong>Note:</strong> In the example above, even though <code class=\"w3-codespan\">\"BMW\"</code> is added twice, it only appears once in the set because sets do not allow duplicate elements."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Check If an Element Exists"
      },
      {
        "type": "paragraph",
        "text": "To check whether an element exists in a <code class=\"w3-codespan\">HashSet</code>, use the <code class=\"w3-codespan\">contains()</code> method:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Remove an Element"
      },
      {
        "type": "paragraph",
        "text": "To remove an element, use the <code class=\"w3-codespan\">remove()</code> method:"
      },
      {
        "type": "paragraph",
        "text": "To remove all elements, use the <code class=\"w3-codespan\">clear()</code> method:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "HashSet Size"
      },
      {
        "type": "paragraph",
        "text": "Use <code class=\"w3-codespan\">size()</code> to count how many unique elements are in the set:"
      },
      {
        "type": "paragraph",
        "text": "<strong>Note:</strong> Duplicate values are not counted - only unique elements are included in the size."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Loop Through a HashSet"
      },
      {
        "type": "paragraph",
        "text": "Loop through the elements of an <code class=\"w3-codespan\">HashSet</code> with a <b>for-each</b> loop:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Other Types"
      },
      {
        "type": "paragraph",
        "text": "Elements in an <code class=\"w3-codespan\">HashSet</code> are actually objects. In the examples above, we created \nelements \n(objects) of type \"String\". Remember that a <code class=\"w3-codespan\">String</code> in Java is an object (not a primitive type). To use other types, such as <code class=\"w3-codespan\">int</code>, you must specify an equivalent <a href=\"#/java/wrapper-classes\">wrapper class</a>: <code class=\"w3-codespan\">Integer</code>. For other primitive types, \nuse: <code class=\"w3-codespan\">Boolean</code> for boolean, <code class=\"w3-codespan\">Character</code> for char, <code class=\"w3-codespan\">Double</code> for double, \netc:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The var Keyword"
      },
      {
        "type": "paragraph",
        "text": "From Java 10, you can use the <code class=\"w3-codespan\">var</code> keyword to declare a <code class=\"w3-codespan\">HashSet</code> variable without writing the type twice.  \nThe compiler figures out the type from the value you assign."
      },
      {
        "type": "paragraph",
        "text": "This makes code shorter, <strong>but many developers still use the full type for clarity</strong>.  \nSince <code class=\"w3-codespan\">var</code> is valid Java, you may see it in other code, so it's good to know that it exists:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The Set Interface"
      },
      {
        "type": "paragraph",
        "text": "<strong>Note:</strong> Sometimes you will see both <code class=\"w3-codespan\">Set</code> and <code class=\"w3-codespan\">HashSet</code> in Java code, like this:"
      },
      {
        "type": "paragraph",
        "text": "This means the variable (cars) is declared as a <a href=\"java_set.html\"><code class=\"w3-codespan\">Set</code></a> (the interface), but it stores a <code class=\"w3-codespan\">HashSet</code> object (the actual set). Since <code class=\"w3-codespan\">HashSet</code> implements the <code class=\"w3-codespan\">Set</code> interface, this is possible."
      },
      {
        "type": "paragraph",
        "text": "It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later."
      },
      {
        "type": "header",
        "level": 2,
        "text": "When Order Matters"
      },
      {
        "type": "playground",
        "subtype": "hashset"
      },
      {
        "type": "code",
        "language": "java",
        "code": "HashSet&lt;String&gt; cars = new HashSet&lt;&gt;();\ncars.add(\"Volvo\");\ncars.add(\"BMW\");\ncars.add(\"Ford\");\ncars.add(\"BMW\");  // duplicate — silently ignored\n\nSystem.out.println(cars.size());          // 3\nSystem.out.println(cars.contains(\"BMW\")); // true\n\ncars.remove(\"Ford\");\nSystem.out.println(cars);  // [Volvo, BMW] (order not guaranteed)\n\n// Loop through all elements\nfor (String c : cars) {\n    System.out.println(c);\n}"
      },
      {
        "type": "paragraph",
        "text": "In the next chapter, you will learn about <a href=\"java_treeset.html\"><code class=\"w3-codespan\">TreeSet</code></a>, which stores unique elements <strong>in sorted order</strong>."
      }
    ]
  },
  "iterator": {
    "title": "Java Iterator",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Iterator"
      },
      {
        "type": "paragraph",
        "text": "An <code class=\"w3-codespan\">Iterator</code> is an object that can be used to loop through <a href=\"java_collections.html\">collections</a>, like <a href=\"#/java/arraylist\"><code class=\"w3-codespan\">ArrayList</code></a>\nand <a href=\"#/java/hashset\"><code class=\"w3-codespan\">HashSet</code></a>."
      },
      {
        "type": "paragraph",
        "text": "It is called an \"iterator\" because \"iterating\" is the technical term for looping."
      },
      {
        "type": "paragraph",
        "text": "To use an Iterator, you must import it from the <code class=\"w3-codespan\">java.util</code> package."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Getting an Iterator"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">iterator()</code> method can be used to get an <code class=\"w3-codespan\">Iterator</code> for any collection:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Looping Through a Collection"
      },
      {
        "type": "paragraph",
        "text": "To loop through a collection, use the <code class=\"w3-codespan\">hasNext()</code> and <code class=\"w3-codespan\">next()</code> methods of the <code class=\"w3-codespan\">Iterator</code>:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Removing Items from a Collection"
      },
      {
        "type": "paragraph",
        "text": "Iterators are designed to easily change the collections that they loop through. The <code class=\"w3-codespan\">remove()</code> method can remove items from a collection while looping."
      },
      {
        "type": "note",
        "text": "<p><strong>Note:</strong> Trying to remove items using a <strong>for loop</strong> or a \n<strong>for-each loop</strong> would not work correctly\nbecause the collection is changing size at the same time that the code is trying to loop.</p>"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The var Keyword with Iterators"
      },
      {
        "type": "paragraph",
        "text": "You can also use the <code class=\"w3-codespan\">var</code> keyword with iterators.  \nThis avoids repeating the long type name <code class=\"w3-codespan\">Iterator&lt;String&gt;</code>, since the compiler already knows the type from the collection."
      },
      {
        "type": "paragraph",
        "text": "This makes code shorter, <strong>but many developers still use the full type for clarity</strong>.  \nSince <code class=\"w3-codespan\">var</code> is valid from Java version 10, you may see it in other code, so it's good to know that it exists:"
      },
      {
        "type": "playground",
        "subtype": "iterator"
      },
      {
        "type": "code",
        "language": "java",
        "code": "ArrayList&lt;String&gt; cars = new ArrayList&lt;&gt;();\ncars.add(\"Volvo\");\ncars.add(\"BMW\");\ncars.add(\"Ford\");\n\n// Get an iterator and loop\nIterator&lt;String&gt; it = cars.iterator();\nwhile (it.hasNext()) {\n    System.out.println(it.next());\n}\n// Volvo, BMW, Ford\n\n// Safe removal during iteration\nArrayList&lt;Integer&gt; nums = new ArrayList&lt;&gt;(List.of(1, 2, 3, 4, 5));\nIterator&lt;Integer&gt; iter = nums.iterator();\nwhile (iter.hasNext()) {\n    if (iter.next() &lt; 3) iter.remove();  // removes 1 and 2\n}\nSystem.out.println(nums);  // [3, 4, 5]"
      },
      {
        "type": "paragraph",
        "text": "Here, <code class=\"w3-codespan\">var</code> makes the iterator declaration shorter,  \nbut the actual type is still <code class=\"w3-codespan\">Iterator&lt;String&gt;</code>."
      }
    ]
  },
  "wrapper-classes": {
    "title": "Java Wrapper Classes",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Wrapper Classes"
      },
      {
        "type": "paragraph",
        "text": "Wrapper classes provide a way to use primitive data types (<code class=\"w3-codespan\">int</code>, <code class=\"w3-codespan\">boolean</code>, \netc..) as objects."
      },
      {
        "type": "paragraph",
        "text": "The table below shows the primitive type and the equivalent wrapper class:"
      },
      {
        "type": "table",
        "headers": [
          "Primitive Data Type",
          "Wrapper Class"
        ],
        "rows": [
          [
            "byte",
            "Byte"
          ],
          [
            "short",
            "Short"
          ],
          [
            "int",
            "Integer"
          ],
          [
            "long",
            "Long"
          ],
          [
            "float",
            "Float"
          ],
          [
            "double",
            "Double"
          ],
          [
            "boolean",
            "Boolean"
          ],
          [
            "char",
            "Character"
          ]
        ]
      },
      {
        "type": "paragraph",
        "text": "Sometimes you must use wrapper classes, for example when working with Collection objects, such \nas <code class=\"w3-codespan\">ArrayList</code>, where primitive types cannot be \nused (the list can only store objects):"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Creating Wrapper Objects"
      },
      {
        "type": "paragraph",
        "text": "To create a wrapper object, use the wrapper class instead of the primitive \ntype. To get the value, you can just print the object:"
      },
      {
        "type": "paragraph",
        "text": "Since you're now working with objects, you can use certain methods to get \ninformation about the specific object."
      },
      {
        "type": "paragraph",
        "text": "For example, the following methods are used to get the value associated with \nthe corresponding wrapper object: <code class=\"w3-codespan\">intValue()</code>, <code class=\"w3-codespan\">byteValue()</code>, <code class=\"w3-codespan\">shortValue()</code>, <code class=\"w3-codespan\">longValue()</code>, \n<code class=\"w3-codespan\">floatValue()</code>, <code class=\"w3-codespan\">doubleValue()</code>, <code class=\"w3-codespan\">charValue()</code>, <code class=\"w3-codespan\">\nbooleanValue()</code>."
      },
      {
        "type": "paragraph",
        "text": "This example will output the same result as the example above:"
      },
      {
        "type": "paragraph",
        "text": "Another useful method is the <code class=\"w3-codespan\">toString()</code> method, which is used to convert wrapper objects to strings."
      },
      {
        "type": "playground",
        "subtype": "wrapper-classes"
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Auto-boxing: primitive → wrapper (automatic)\nint num = 42;\nInteger boxed = num;   // autoboxing\nint unboxed = boxed;   // unboxing\n\n// Useful static methods\nSystem.out.println(Integer.MAX_VALUE);          // 2147483647\nSystem.out.println(Integer.MIN_VALUE);          // -2147483648\nSystem.out.println(Integer.parseInt(\"123\"));     // 123\nSystem.out.println(Double.parseDouble(\"3.14\")); // 3.14\nSystem.out.println(Integer.toBinaryString(10)); // 1010\n\n// Convert wrapper to String\nString s = Integer.toString(255);\nSystem.out.println(s.length()); // 3  (length of \"255\")"
      },
      {
        "type": "paragraph",
        "text": "In the following example, we convert an <code class=\"w3-codespan\">Integer</code> to a <code class=\"w3-codespan\">String</code>, and use the <code class=\"w3-codespan\">length()</code> method of the <code class=\"w3-codespan\">String</code> class to output the length of the \"string\":"
      }
    ]
  },
  "exceptions": {
    "title": "Java Exceptions - Try...Catch",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Exceptions"
      },
      {
        "type": "paragraph",
        "text": "As mentioned in the <a href=\"java_errors.html\">Errors chapter</a>, different types of errors can occur while running a program - such as coding mistakes, invalid input, or unexpected situations."
      },
      {
        "type": "paragraph",
        "text": "When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an <b>exception</b> (throw an error)."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Exception Handling (try and catch)"
      },
      {
        "type": "paragraph",
        "text": "Exception handling lets you catch and handle errors during runtime - so your program doesn't crash."
      },
      {
        "type": "paragraph",
        "text": "It uses different keywords:"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">try</code> statement allows you to define a block of code to be \ntested for errors while it is being executed."
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">catch</code> statement allows you to define a block of code to \nbe executed, if an error occurs in the try block."
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">try</code> and <code class=\"w3-codespan\">catch</code> keywords \ncome in pairs:"
      },
      {
        "type": "paragraph",
        "text": "Consider the following example:"
      },
      {
        "type": "paragraph",
        "text": "If an error occurs, we can use <code class=\"w3-codespan\">try...catch</code> to catch the error and execute some code to handle it:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Finally"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">finally</code> statement lets you execute code, after <code class=\"w3-codespan\">try...catch</code>, regardless of the result:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "The throw keyword"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">throw</code> statement allows you to create a custom error."
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">throw</code> statement is used together with an <strong>exception type</strong>. There are many exception types available in Java: <code class=\"w3-codespan\">ArithmeticException</code>, \n<code class=\"w3-codespan\">FileNotFoundException</code>, <code class=\"w3-codespan\">ArrayIndexOutOfBoundsException</code>, <code class=\"w3-codespan\">SecurityException</code>, etc:"
      },
      {
        "type": "paragraph",
        "text": "If <strong>age</strong> was 20, you would <strong>not</strong> get an exception:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Errors and Exception Types"
      },
      {
        "type": "paragraph",
        "text": "The table below shows some of the most common errors and exceptions in Java, with a short description of each:"
      },
      {
        "type": "playground",
        "subtype": "exceptions"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Exception Hierarchy"
      },
      {
        "type": "table",
        "headers": ["Exception Type", "Checked?", "Common cause", "Example"],
        "rows": [
          ["<code>ArithmeticException</code>", "Unchecked", "Division by zero", "<code>int x = 5 / 0;</code>"],
          ["<code>NullPointerException</code>", "Unchecked", "Using a null reference", "<code>str.length()</code> when str is null"],
          ["<code>ArrayIndexOutOfBoundsException</code>", "Unchecked", "Accessing invalid array index", "<code>arr[10]</code> on a 5-element array"],
          ["<code>NumberFormatException</code>", "Unchecked", "Invalid string-to-number parse", "<code>Integer.parseInt(\"abc\")</code>"],
          ["<code>IOException</code>", "Checked", "File not found / read error", "Reading a missing file"]
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "throw vs throws"
      },
      {
        "type": "code",
        "language": "java",
        "code": "// throw — explicitly throws an exception inside a method\nvoid setAge(int age) {\n    if (age &lt; 0 || age &gt; 150) {\n        throw new IllegalArgumentException(\"Invalid age: \" + age);\n    }\n    this.age = age;\n}\n\n// throws — declares that a method MAY throw a checked exception\nvoid readFile(String path) throws IOException {\n    BufferedReader reader = new BufferedReader(new FileReader(path));\n    System.out.println(reader.readLine());\n    reader.close();    // caller must handle or re-declare IOException\n}\n\n// Multi-catch — handle multiple exception types at once (Java 7+)\ntry {\n    int[] arr = new int[3];\n    arr[10] = 1;\n} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {\n    System.out.println(\"Caught: \" + e.getMessage());\n} finally {\n    System.out.println(\"Always runs\");\n}"
      },
      {
        "type": "note",
        "text": "<strong>Best practices:</strong> Catch the <em>most specific</em> exception first (e.g., <code>FileNotFoundException</code> before <code>IOException</code>). Always close resources in <code>finally</code> — or better, use <strong>try-with-resources</strong>: <code>try (var r = new FileReader(\"f.txt\")) { ... }</code> — it closes automatically."
      },
      {
        "type": "paragraph",
        "text": "<strong>Tip:</strong> For a list of all errors and exception types, go to our <a href=\"java_ref_errors.html\">Java Errors and Exception Types Reference</a>."
      }
    ]
  },
  "regex": {
    "title": "Java Regular Expressions",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "What is a Regular Expression?"
      },
      {
        "type": "paragraph",
        "text": "A regular expression is a sequence of characters that forms a search pattern.\nWhen you search for data in a text, you can use this search pattern to describe what you\nare searching for."
      },
      {
        "type": "paragraph",
        "text": "A regular expression can be a single character, or a more complicated pattern."
      },
      {
        "type": "paragraph",
        "text": "Regular expressions can be used to perform all types of <strong>text search</strong> and <strong>text replace</strong>\noperations."
      },
      {
        "type": "paragraph",
        "text": "Java does not have a built-in Regular Expression class, but we can import the <code class=\"w3-codespan\">java.util.regex</code> \npackage to work with regular expressions. The package includes the following \nclasses:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<code class=\"w3-codespan\">Pattern</code> Class - Defines a pattern (to be used in a search)",
          "<code class=\"w3-codespan\">Matcher</code> Class - Used to search for the \npattern",
          "<code class=\"w3-codespan\">PatternSyntaxException</code> Class - Indicates syntax error in a regular \nexpression pattern"
        ]
      },
      {
        "type": "header",
        "level": 3,
        "text": "Example Explained"
      },
      {
        "type": "paragraph",
        "text": "In this example, The word \"codingtamilan\" is being searched for in a sentence."
      },
      {
        "type": "paragraph",
        "text": "First, the pattern is created using the <code class=\"w3-codespan\">Pattern.compile()</code> method. The first parameter\nindicates which pattern is being searched for and the second parameter has a flag to\nindicates that the search should be case-insensitive. The second parameter is optional."
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">matcher()</code> method is used to search for the pattern in a string. It returns a Matcher\nobject which contains information about the search that was performed."
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">find()</code> method returns true if the pattern was found in the string and false if it was not\nfound."
      },
      {
        "type": "code",
        "language": "java",
        "code": "import java.util.regex.*;\n\n// Basic match\nPattern p = Pattern.compile(\"codingtamilan\", Pattern.CASE_INSENSITIVE);\nMatcher m = p.matcher(\"I love CodingTamilan!\");\nSystem.out.println(m.find());   // true\n\n// Full-string match\nSystem.out.println(\"Hello\".matches(\"[A-Z][a-z]+\"));  // true\n\n// Find all occurrences\nPattern pAll = Pattern.compile(\"cat\");\nMatcher mAll = pAll.matcher(\"cat and cats and catch\");\nwhile (mAll.find()) {\n    System.out.println(\"Found at index \" + mAll.start());\n}\n// Found at index 0\n// Found at index 8\n// Found at index 17"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Flags"
      },
      {
        "type": "paragraph",
        "text": "Flags in the <code class=\"w3-codespan\">compile()</code> method change how the search is performed. Here are a few of\nthem:"
      },
      {
        "type": "list",
        "ordered": false,
        "items": [
          "<code class=\"w3-codespan\">Pattern.CASE_INSENSITIVE</code> - The case of letters will be ignored when performing\na search.",
          "<code class=\"w3-codespan\">Pattern.LITERAL</code> - Special characters in the pattern will not have any special\nmeaning and will be treated as ordinary characters when performing a search.",
          "<code class=\"w3-codespan\">Pattern.UNICODE_CASE</code> - Use it together with the <code class=\"w3-codespan\">CASE_INSENSITIVE</code> flag to\nalso ignore the case of letters outside of the English alphabet"
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Regular Expression Patterns"
      },
      {
        "type": "paragraph",
        "text": "The first parameter of the <code class=\"w3-codespan\">Pattern.compile()</code> method is the pattern. It describes what\nis being searched for."
      },
      {
        "type": "paragraph",
        "text": "Brackets are used to find a range of characters:"
      },
      {
        "type": "table",
        "headers": [
          "Expression",
          "Description"
        ],
        "rows": [
          [
            "[abc]",
            "Find one character from the options between the brackets"
          ],
          [
            "[^abc]",
            "Find one character NOT between the brackets"
          ],
          [
            "[0-9]",
            "Find one character from the range 0 to 9"
          ]
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Metacharacters"
      },
      {
        "type": "paragraph",
        "text": "Metacharacters are characters with a special meaning:"
      },
      {
        "type": "table",
        "headers": [
          "Metacharacter",
          "Description"
        ],
        "rows": [
          [
            "|",
            "Find a match for any one of the patterns separated by | as in: cat|dog|fish"
          ],
          [
            ".",
            "Find just one instance of any character"
          ],
          [
            "^",
            "Finds a match as the beginning of a string as in: ^Hello"
          ],
          [
            "$",
            "Finds a match at the end of the string as in: World$"
          ],
          [
            "\\d",
            "Find a digit"
          ],
          [
            "\\s",
            "Find a whitespace character"
          ],
          [
            "\\b",
            "Find a match at the beginning of a word like this: \\bWORD, or at the end of a word like this: WORD\\b"
          ],
          [
            "\\uxxxx",
            "Find the Unicode character specified by the hexadecimal number xxxx"
          ]
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Quantifiers"
      },
      {
        "type": "paragraph",
        "text": "Quantifiers define quantities:"
      },
      {
        "type": "playground",
        "subtype": "regex"
      },
      {
        "type": "table",
        "headers": [
          "Quantifier",
          "Description"
        ],
        "rows": [
          [
            "n+",
            "Matches any string that contains at least one <em>n</em>"
          ],
          [
            "n*",
            "Matches any string that contains zero or more occurrences of <em>n</em>"
          ],
          [
            "n?",
            "Matches any string that contains zero or one occurrences of <em>n</em>"
          ],
          [
            "n{x}",
            "Matches any string that contains a sequence of <i>X</i> <i>n</i>'s"
          ],
          [
            "n{x,y}",
            "Matches any string that contains a sequence of X to Y <i>n</i>'s"
          ],
          [
            "n{x,}",
            "Matches any string that contains a sequence of at least X <i>n</i>'s"
          ]
        ]
      },
      {
        "type": "header",
        "level": 2,
        "text": "Real-World Regex Examples"
      },
      {
        "type": "table",
        "headers": ["Use case", "Pattern", "Notes"],
        "rows": [
          ["Email", "<code>[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}</code>", "Basic; use a library for production"],
          ["Indian phone", "<code>[6-9]\\d{9}</code>", "10-digit, starts 6–9"],
          ["Digits only", "<code>\\d+</code>", "One or more digits"],
          ["Alphanumeric", "<code>[a-zA-Z0-9]+</code>", "Letters and digits"],
          ["Date dd/mm/yyyy", "<code>(0[1-9]|[12]\\d|3[01])/(0[1-9]|1[0-2])/\\d{4}</code>", "Strict day/month range"]
        ]
      },
      {
        "type": "code",
        "language": "java",
        "code": "// String.matches() — full-string regex test\nString email = \"user@example.com\";\nSystem.out.println(email.matches(\"[\\\\w.-]+@[\\\\w.-]+\\\\.[a-zA-Z]{2,}\")); // true\n\n// replaceAll — remove all non-digits\nString cleaned = \"Phone: 98-765-43210\".replaceAll(\"\\\\D\", \"\");\nSystem.out.println(cleaned);   // 9876543210\n\n// split by whitespace\nString[] words = \"hello  world  java\".split(\"\\\\s+\");\nSystem.out.println(Arrays.toString(words)); // [hello, world, java]"
      }
    ]
  },
  "threads": {
    "title": "Java Threads",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Threads"
      },
      {
        "type": "paragraph",
        "text": "Threads allows a program to operate more efficiently by doing multiple things at the same\ntime."
      },
      {
        "type": "paragraph",
        "text": "Threads can be used to perform complicated tasks in the background without interrupting\nthe main program."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Creating a Thread"
      },
      {
        "type": "paragraph",
        "text": "There are two ways to create a thread."
      },
      {
        "type": "paragraph",
        "text": "It can be created by extending the <code class=\"w3-codespan\">Thread</code> class and overriding its <code class=\"w3-codespan\">run()</code> \nmethod:"
      },
      {
        "type": "paragraph",
        "text": "Another way to create a thread is to implement the <code class=\"w3-codespan\">Runnable</code> interface:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Running Threads"
      },
      {
        "type": "paragraph",
        "text": "If the class extends the <code class=\"w3-codespan\">Thread</code> class, the thread can be run by creating an instance of the\nclass and call its <code class=\"w3-codespan\">start()</code> method:"
      },
      {
        "type": "paragraph",
        "text": "If the class implements the <code class=\"w3-codespan\">Runnable</code> interface, the thread can be run by passing an\ninstance of the class to a <code class=\"w3-codespan\">Thread</code> object's constructor and then calling the thread's\n<code class=\"w3-codespan\">start()</code> method:"
      },
      {
        "type": "note",
        "text": "<p><strong>Differences between \"extending\" and \"implementing\" Threads</strong></p>\n<p>The major difference is that when a class extends the Thread class, you cannot extend any other class, but by implementing the Runnable interface, \nit is possible to extend from another class as well, like: class <code class=\"w3-codespan\">MyClass extends OtherClass implements Runnable</code>.</p>"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Concurrency Problems"
      },
      {
        "type": "paragraph",
        "text": "Because threads run at the same time as other parts of the program, there is no way to\nknow in which order the code will run. When the threads and main program are reading\nand writing the same variables, the values are unpredictable. The problems that result\nfrom this are called concurrency problems."
      },
      {
        "type": "playground",
        "subtype": "threads"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Three Ways to Create a Thread"
      },
      {
        "type": "code",
        "language": "java",
        "code": "// Way 1 — Extend Thread class\nclass MyThread extends Thread {\n    public void run() {\n        System.out.println(\"Thread running: \" + getName());\n    }\n}\nnew MyThread().start();\n\n// Way 2 — Implement Runnable (preferred — allows extending other classes)\nclass MyTask implements Runnable {\n    public void run() {\n        System.out.println(\"Runnable running: \" + Thread.currentThread().getName());\n    }\n}\nnew Thread(new MyTask()).start();\n\n// Way 3 — Lambda (Java 8+, most concise)\nnew Thread(() -&gt; System.out.println(\"Lambda thread!\")).start();"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Thread Lifecycle"
      },
      {
        "type": "table",
        "headers": ["State", "Description", "How to reach it"],
        "rows": [
          ["<strong>NEW</strong>", "Thread created but not yet started", "<code>new Thread(task)</code>"],
          ["<strong>RUNNABLE</strong>", "Ready to run (waiting for CPU time)", "<code>thread.start()</code>"],
          ["<strong>RUNNING</strong>", "Currently executing <code>run()</code>", "JVM scheduler selects it"],
          ["<strong>BLOCKED/WAITING</strong>", "Paused — waiting for lock or another thread", "<code>sleep()</code>, <code>wait()</code>, <code>join()</code>"],
          ["<strong>TERMINATED</strong>", "<code>run()</code> method has finished", "Normal completion or exception"]
        ]
      },
      {
        "type": "note",
        "text": "<strong><code>start()</code> vs <code>run()</code>:</strong> Always call <code>start()</code> — it creates a new thread and calls <code>run()</code> on it. Calling <code>run()</code> directly just executes the method on the <em>current</em> thread — no new thread is created."
      },
      {
        "type": "paragraph",
        "text": "To avoid concurrency problems, it is best to share as few attributes between threads as\npossible. If attributes need to be shared, one possible solution is to use the <code class=\"w3-codespan\">isAlive()</code>\nmethod of the thread to check whether the thread has finished running before using any \nattributes that the thread can change."
      }
    ]
  },
  "lambda": {
    "title": "Java Lambda Expressions",
    "blocks": [
      {
        "type": "header",
        "level": 2,
        "text": "Java Lambda Expressions"
      },
      {
        "type": "paragraph",
        "text": "Lambda Expressions were added in Java 8."
      },
      {
        "type": "paragraph",
        "text": "A <strong>lambda expression</strong> is a short block of code that takes in parameters and returns a value. \nLambdas look similar to methods, but they do not need a name, and they can be written right inside a method body."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Syntax"
      },
      {
        "type": "paragraph",
        "text": "The simplest lambda expression contains a single parameter and an expression:"
      },
      {
        "type": "paragraph",
        "text": "To use more than one parameter, wrap them in parentheses:"
      },
      {
        "type": "paragraph",
        "text": "Simple expressions must return a value immediately. They cannot contain multiple statements, such as loops or <code class=\"w3-codespan\">if</code> conditions. \nTo do more complex work, use a code block with curly braces. If the lambda should return a value, use the <code class=\"w3-codespan\">return</code> keyword:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Using Lambda Expressions"
      },
      {
        "type": "paragraph",
        "text": "Lambdas are often passed as arguments to methods. For example, you can use a lambda in the \n<code class=\"w3-codespan\">forEach()</code> method of an <code class=\"w3-codespan\">ArrayList</code>:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Lambdas in Variables"
      },
      {
        "type": "paragraph",
        "text": "A lambda expression can be stored in a variable. The variable's type must be an interface with exactly one method \n(a <strong>functional interface</strong>). The lambda must match that method's parameters and return type."
      },
      {
        "type": "paragraph",
        "text": "Java includes many built-in functional interfaces, such as <code class=\"w3-codespan\">Consumer</code> (from the <code class=\"w3-codespan\">java.util</code> package) used with lists."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Lambdas as Method Parameters"
      },
      {
        "type": "paragraph",
        "text": "You can also pass a lambda expression to a method. The method's parameter must be a functional interface. \nCalling the interface's method will then run the lambda expression:"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Anonymous Class vs. Lambda Expression"
      },
      {
        "type": "playground",
        "subtype": "lambda"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Lambdas with the Stream API"
      },
      {
        "type": "paragraph",
        "text": "Lambdas shine brightest with the <strong>Stream API</strong> — a powerful way to process collections with a pipeline of operations: filter, transform, and collect in one readable chain."
      },
      {
        "type": "code",
        "language": "java",
        "code": "import java.util.List;\nimport java.util.stream.Collectors;\n\nList&lt;Integer&gt; numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);\n\n// Pipeline: filter evens → square them → collect to list\nList&lt;Integer&gt; evenSquares = numbers.stream()\n    .filter(n -&gt; n % 2 == 0)         // keep even numbers\n    .map(n -&gt; n * n)                  // square each\n    .collect(Collectors.toList());\nSystem.out.println(evenSquares);  // [4, 16, 36, 64, 100]\n\n// Sum all numbers\nint total = numbers.stream()\n    .reduce(0, Integer::sum);\nSystem.out.println(\"Sum: \" + total);  // Sum: 55\n\n// Find any number greater than 7\nnumbers.stream()\n    .filter(n -&gt; n &gt; 7)\n    .findFirst()\n    .ifPresent(n -&gt; System.out.println(\"Found: \" + n));  // Found: 8"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Method References"
      },
      {
        "type": "paragraph",
        "text": "When a lambda just calls an existing method, you can replace it with a <strong>method reference</strong> using <code class=\"w3-codespan\">::</code> — more concise and easier to read."
      },
      {
        "type": "table",
        "headers": ["Type", "Syntax", "Lambda equivalent"],
        "rows": [
          ["Static method", "<code>ClassName::methodName</code>", "<code>n -&gt; Integer.parseInt(n)</code> → <code>Integer::parseInt</code>"],
          ["Instance method (specific object)", "<code>obj::methodName</code>", "<code>s -&gt; obj.startsWith(s)</code> → <code>obj::startsWith</code>"],
          ["Instance method (any object)", "<code>ClassName::methodName</code>", "<code>s -&gt; s.toUpperCase()</code> → <code>String::toUpperCase</code>"],
          ["Constructor", "<code>ClassName::new</code>", "<code>() -&gt; new StringBuilder()</code> → <code>StringBuilder::new</code>"]
        ]
      },
      {
        "type": "paragraph",
        "text": "In Java 8+, you can often replace an \n<a href=\"java_anonymous.html\">anonymous class</a> with a <strong>lambda expression</strong> - \nbut only if the interface is a <strong>functional interface</strong> (one abstract method)."
      }
    ]
  },
  "files": {
    "title": "Java Files",
    "blocks": [
      {
        "type": "intro",
        "text": "File handling is an important part of any application."
      },
      {
        "type": "intro",
        "text": "Java has several methods for creating, reading, updating, and \ndeleting files."
      },
      {
        "type": "header",
        "level": 2,
        "text": "Java File Handling"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">File</code> class from the <code class=\"w3-codespan\">java.io</code> package, allows \nus to work with files."
      },
      {
        "type": "paragraph",
        "text": "To use the <code class=\"w3-codespan\">File</code> class, create an object of \nthe class, and specify the filename or directory name:"
      },
      {
        "type": "note",
        "text": "<p>If you don't know what a package is, read our <a href=\"#/java/packages\">Java Packages Tutorial</a>.</p>"
      },
      {
        "type": "paragraph",
        "text": "The <code class=\"w3-codespan\">File</code> class has many useful methods for creating and getting information \nabout files. \nFor example:"
      },
      {
        "type": "playground",
        "subtype": "files"
      },
      {
        "type": "header",
        "level": 2,
        "text": "Modern File API — java.nio.file.Files"
      },
      {
        "type": "paragraph",
        "text": "Since Java 7, <code class=\"w3-codespan\">java.nio.file.Files</code> provides a cleaner, more powerful file API with less boilerplate than the old <code class=\"w3-codespan\">java.io</code> approach."
      },
      {
        "type": "code",
        "language": "java",
        "code": "import java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.List;\n\n// Write to a file (creates or overwrites)\nPath file = Path.of(\"notes.txt\");\nFiles.writeString(file, \"Hello from NIO!\");\n\n// Read entire file as a String\nString content = Files.readString(file);\nSystem.out.println(content);         // Hello from NIO!\n\n// Read all lines as a List\nList&lt;String&gt; lines = Files.readAllLines(file);\nlines.forEach(System.out::println);\n\n// Check if file exists\nif (Files.exists(file)) {\n    System.out.println(\"File size: \" + Files.size(file) + \" bytes\");\n}\n\n// Delete the file\nFiles.deleteIfExists(file);"
      },
      {
        "type": "table",
        "headers": ["Approach", "Package", "Best for", "Complexity"],
        "rows": [
          ["<code>Files.writeString()</code> / <code>readString()</code>", "<code>java.nio.file</code>", "Quick file read/write (Java 11+)", "Low"],
          ["<code>FileWriter</code> / <code>BufferedReader</code>", "<code>java.io</code>", "Fine-grained streaming, append mode", "Medium"],
          ["<code>Scanner</code>", "<code>java.util</code>", "Reading line-by-line interactively", "Low"],
          ["<code>Files.readAllLines()</code>", "<code>java.nio.file</code>", "Reading all lines into a List (Java 7+)", "Low"]
        ]
      },
      {
        "type": "paragraph",
        "text": "You will learn how to create, write, read and delete files in the next chapters:"
      }
    ]
  }
}