### Java Inheritance and Polymorphism Example Source: https://context7.com/exercism/java/llms.txt Demonstrates inheritance and polymorphism in Java. Subclasses override parent methods to provide specialized behavior. Usage examples show polymorphic calls. ```java class Fighter { boolean isVulnerable() { return true; } int getDamagePoints(Fighter fighter) { return 1; } } class Warrior extends Fighter { @Override public String toString() { return "Fighter is a Warrior"; } @Override public boolean isVulnerable() { return false; // Warriors are never vulnerable } @Override int getDamagePoints(Fighter target) { return target.isVulnerable() ? 10 : 6; } } class Wizard extends Fighter { boolean isSpellPrepared = false; @Override public String toString() { return "Fighter is a Wizard"; } @Override boolean isVulnerable() { return !isSpellPrepared; // Vulnerable when spell not prepared } @Override int getDamagePoints(Fighter target) { return isSpellPrepared ? 12 : 3; } void prepareSpell() { isSpellPrepared = true; } } // Usage demonstrating polymorphism Warrior warrior = new Warrior(); Wizard wizard = new Wizard(); warrior.isVulnerable(); // => false wizard.isVulnerable(); // => true warrior.getDamagePoints(wizard); // => 10 (wizard is vulnerable) wizard.getDamagePoints(warrior); // => 3 (spell not prepared) wizard.prepareSpell(); wizard.isVulnerable(); // => false wizard.getDamagePoints(warrior); // => 12 (spell prepared) ``` -------------------------------- ### Clean and Rebuild Project with Gradle Source: https://context7.com/exercism/java/llms.txt Use this command to clean the project build artifacts and then rebuild the project. Ensure Gradle is installed and accessible in your PATH. ```bash ./gradlew clean build ``` -------------------------------- ### Create a HashMap Instance Source: https://github.com/exercism/java/blob/main/concepts/maps/introduction.md Instantiate a HashMap to store String keys and Integer values. This is the starting point for using map functionalities. ```java // Make an instance Map fruitPrices = new HashMap<>(); ``` -------------------------------- ### Define a Constructor with Parameters in Java Source: https://github.com/exercism/java/blob/main/concepts/constructors/introduction.md Create constructors that accept parameters to customize object initialization. This example uses parameters to set the number of stories and calculate the total height of a building. ```java class Building { private int numberOfStories; private int totalHeight; public Building(int numberOfStories, double storyHeight) { this.numberOfStories = numberOfStories; this.totalHeight = numberOfStories * storyHeight; } } // Call a constructor with two arguments var largeBuilding = new Building(55, 6.2); ``` -------------------------------- ### Get Keys and Values from a Map Source: https://github.com/exercism/java/blob/main/concepts/maps/introduction.md Obtain a Set of all keys using keySet() or a Collection of all values using values(). ```java fruitPrices.keySet(); // Returns "apple" and "pear" in a set fruitPrices.values(); // Returns 100 and 80, in a Collection ``` -------------------------------- ### Java Composition Example Source: https://github.com/exercism/java/blob/main/concepts/inheritance/about.md Illustrates composition in Java, where a class contains an instance of another class. The 'Car' class has an 'Engine' object. ```java interface Engine { } class Car { private Engine engine; } ``` -------------------------------- ### Java Class Inheritance Example Source: https://github.com/exercism/java/blob/main/concepts/inheritance/about.md Demonstrates how a class can implement an interface in Java. The 'Dog' class inherits the 'bark' method from the 'Animal' interface. ```java interface Animal() { public void bark(); } class Dog implements Animal { public void bark() { System.out.println("Bark"); } } ``` -------------------------------- ### Java For Loop Printing Squares Source: https://github.com/exercism/java/blob/main/concepts/for-loops/introduction.md A practical example of a for loop that calculates and prints the squares of numbers from 1 to 4. ```java for (int i = 1; i <= 4; i++) { System.out.println("square of " + i + " is " + i * i); } ``` -------------------------------- ### Java For Loop for Printing Squares Source: https://github.com/exercism/java/blob/main/concepts/for-loops/about.md An example demonstrating a for loop to calculate and print the squares of numbers from 1 to 4. Note the output comment. ```java for (int i = 1; i <= 4; i++) { System.out.println(i * i); } /* => 1 4 9 16 */ ``` -------------------------------- ### Overload Methods with Different Types of Parameters in Java Source: https://github.com/exercism/java/blob/main/concepts/method-overloading/introduction.md Illustrates method overloading using methods with the same name but different parameter types. This example shows 'show' methods accepting either an integer or a String, enabling flexibility in input handling. ```java public class Display { public void show(int x) { System.out.println("Show with int: " + x); } public void show(String s) { System.out.println("Show with String: " + s); } } ``` -------------------------------- ### Java Interface and Implementation Example Source: https://context7.com/exercism/java/llms.txt Illustrates Java interfaces and class implementation. A class implements an interface to adhere to a contract and can also implement Comparable for sorting. ```java // Interface defining the contract public interface RemoteControlCar { void drive(); int getDistanceTravelled(); } // Class implementing interface and Comparable for sorting class ProductionRemoteControlCar implements RemoteControlCar, Comparable { private int distanceTravelled; private int numberOfVictories; @Override public void drive() { distanceTravelled += 10; } @Override public int getDistanceTravelled() { return distanceTravelled; } public int getNumberOfVictories() { return numberOfVictories; } public void setNumberOfVictories(int numberOfVictories) { this.numberOfVictories = numberOfVictories; } @Override public int compareTo(ProductionRemoteControlCar other) { return Integer.compare(other.getNumberOfVictories(), this.getNumberOfVictories()); } } // Utility class working with the interface class TestTrack { public static void race(RemoteControlCar car) { car.drive(); } public static List getRankedCars( List cars) { Collections.sort(cars); return cars; } } // Usage example ProductionRemoteControlCar car1 = new ProductionRemoteControlCar(); ProductionRemoteControlCar car2 = new ProductionRemoteControlCar(); car1.drive(); car1.drive(); car1.getDistanceTravelled(); // => 20 car1.setNumberOfVictories(3); car2.setNumberOfVictories(5); // car2 ranks higher due to more victories ``` -------------------------------- ### Triangle Exception Example Source: https://github.com/exercism/java/blob/main/POLICIES.md Define a custom exception for specific error scenarios in an exercise. This forces users to handle potential issues. ```java package org.example; public class TriangleException extends IllegalArgumentException { public TriangleException(String message) { super(message); } } ``` -------------------------------- ### Format Strings with String.format in Java Source: https://github.com/exercism/java/blob/main/concepts/strings/about.md For more complex string formatting than simple concatenation, use the `String.format` method. This example formats a greeting string. ```java String name = "Jane"; String.format("Hello %s!",name); // => "Hello Jane!" ``` -------------------------------- ### Java Method Overloading Example Source: https://github.com/exercism/java/blob/main/concepts/method-overloading/about.md Demonstrates method overloading in Java with a Calculator class. It shows how to define multiple `add` methods with different parameter types and counts. ```java public class Calculator { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } public int add(int a, int b, int c) { return a + b + c; } } ``` -------------------------------- ### Iterating Over a Character Array with For-Each Loop in Java Source: https://github.com/exercism/java/blob/main/concepts/foreach-loops/introduction.md Example demonstrating how to iterate over a character array using a for-each loop and print each character. Ensure the collection is properly initialized before iteration. ```java char[] vowels = {'a', 'e', 'i', 'o', 'u'}; for(char vowel: vowels) { System.out.println(vowel); } ``` -------------------------------- ### Define a Default Constructor in Java Source: https://github.com/exercism/java/blob/main/concepts/constructors/introduction.md Use a default constructor to initialize fields when an object is created. This example initializes the 'books' field to 10. ```java class Library { private int books; public Library() { // Initialize the books field this.books = 10; } } // This will call the constructor var library = new Library(); ``` -------------------------------- ### Java Arithmetic and Comparison Operations Source: https://github.com/exercism/java/blob/main/concepts/numbers/about.md Shows examples of basic arithmetic operations (multiplication) and comparison operations (greater than, equality, inequality) between numeric literals in Java. The results are boolean for comparisons. ```java 5 * 6 // => 30 1.2 > 0.8 // => true 120 == 100 // => false 2 != 4 // => true ``` -------------------------------- ### Collatz Conjecture Test Example Source: https://github.com/exercism/java/blob/main/POLICIES.md Demonstrates using a predefined exception for error handling within exercise tests. This approach requires users to handle the thrown exception. ```java import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CollatzCalculatorTest { @Test void testInvalidInput() { assertThatThrownBy(() -> new CollatzCalculator().compute(0)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only positive numbers are allowed"); } @Test void testAlreadyIn1000000() { assertThat(new CollatzCalculator().compute(1000000)).isEqualTo(0); } @Test void testSimpleSequence() { assertThat(new CollatzCalculator().compute(3)).isEqualTo(7); } @Test void testLongerSequence() { assertThat(new CollatzCalculator().compute(37)).isEqualTo(152); } @Test void testMaxSequence() { assertThat(new CollatzCalculator().compute(11111)).isEqualTo(207); } @Test void testMaxNumber() { assertThat(new CollatzCalculator().compute(999999)).isEqualTo(524); } } ``` -------------------------------- ### Word Search Optional Example Source: https://github.com/exercism/java/blob/main/POLICIES.md Illustrates using Java's Optional class to handle cases where a search method might not find a result. This avoids returning null and clearly indicates a potential absence of a value. ```java import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import java.util.Optional; public class WordSearcherTest { @Test void shouldFindWordInGrid() { String[] grid = {"abc", "def", "ghi"}; Optional result = new WordSearcher().search("abc", grid); assertThat(result).hasValue(0); } @Test void shouldNotFindWordInGrid() { String[] grid = {"abc", "def", "ghi"}; Optional result = new WordSearcher().search("xyz", grid); assertThat(result).isEmpty(); } } ``` -------------------------------- ### Generate Random Integer in Java Source: https://github.com/exercism/java/blob/main/concepts/randomness/introduction.md Use `nextInt()` to generate a random integer within the full range of `Integer.MIN_VALUE` to `Integer.MAX_VALUE`. No specific setup is required beyond instantiating the `Random` class. ```java Random random = new Random(); random.nextInt(); // => -1169335537 ``` -------------------------------- ### Java Switch Statement Example Source: https://github.com/exercism/java/blob/main/concepts/switch-statement/introduction.md Use a switch statement to execute different code blocks based on the value of a string variable. Ensure to use 'break' to exit the switch after a match, otherwise, execution will fall through to the next case. ```java String direction = getDirection(); switch (direction) { case "left": goLeft(); break; case "right": goRight(); break; default: // otherwise markTime(); break; } ``` -------------------------------- ### Generate Introduction with Configlet Source: https://github.com/exercism/java/blob/main/reference/implementing-a-concept-exercise.md Run this command to generate or update the exercise's `.docs/introduction.md` file from the template. ```shell bin/configlet generate ``` -------------------------------- ### Get the Size of a Map Source: https://github.com/exercism/java/blob/main/concepts/maps/introduction.md The size method returns the number of key-value mappings currently in the map. ```java fruitPrices.size(); // Returns 2 ``` -------------------------------- ### Compile Starter Implementation with Tests Source: https://github.com/exercism/java/blob/main/CONTRIBUTING.md Use this command to ensure the starter implementation can successfully compile with the provided tests. Run from the exercise's root directory. ```sh ./gradlew compileStarterTestJava ``` -------------------------------- ### Run Java Tests with Gradle Source: https://context7.com/exercism/java/llms.txt These bash commands demonstrate how to download an Exercism exercise, navigate to its directory, and run tests using Gradle. Options for detailed output and running specific test classes are included. ```bash # Download an exercise from Exercism exercism download --exercise hello-world --track java # Navigate to the exercise directory cd ~/exercism/java/hello-world # Run all tests ./gradlew test # Run tests with detailed output ./gradlew test --info # Run a specific test class ./gradlew test --tests "GreeterTest" ``` -------------------------------- ### Get day of month from LocalDate Source: https://github.com/exercism/java/blob/main/concepts/datetime/introduction.md Use getDayOfMonth() to retrieve the day of the month from a LocalDate object. ```java LocalDate date = LocalDate.of(2007, 12, 3); date.getDayOfMonth(); // => 3 ``` -------------------------------- ### Download Java Exercise Source: https://github.com/exercism/java/blob/main/docs/TESTS.md Use this command to download a specific Java exercise. Replace 'hello-world' with the desired exercise name and 'java' with the track if different. ```batchfile C:\Users\JohnDoe>exercism download --exercise hello-world --track java ``` ```sh exercism download --exercise hello-world --track java ``` -------------------------------- ### Get Array Length in Java Source: https://github.com/exercism/java/blob/main/concepts/arrays/about.md Access the `length` property of an array to determine the number of elements it holds. ```java int arrayLength = someArray.length; ``` -------------------------------- ### Test Solution with Gradle Source: https://github.com/exercism/java/blob/main/reference/implementing-a-concept-exercise.md Run this command from the `exercises` folder to test the solution of a specific concept exercise. ```shell ./gradlew concept::test ``` -------------------------------- ### Navigate to Exercise Directory Source: https://github.com/exercism/java/blob/main/docs/TESTS.md Change to the downloaded exercise's directory to begin working on it. Adjust the path according to your system and username. ```batchfile C:\Users\JohnDoe>cd C:\Users\JohnDoe\exercism\java\hello-world ``` ```sh cd /Users/johndoe/exercism/java/hello-world ``` ```sh cd /home/johndoe/exercism/java/hello-world ``` -------------------------------- ### Java Boolean Operator Examples Source: https://github.com/exercism/java/blob/main/concepts/booleans/introduction.md Demonstrates the usage of NOT, AND, and OR operators with boolean values in Java. These operators are fundamental for conditional logic. ```java !true // => false ``` ```java !false // => true ``` ```java true && false // => false ``` ```java true && true // => true ``` ```java false || false // => false ``` ```java false || true // => true ``` -------------------------------- ### Define a Java Class and Create Instances Source: https://github.com/exercism/java/blob/main/concepts/classes/introduction.md Demonstrates how to define a simple Java class and create multiple instances of it using the 'new' keyword. ```java class Car { } // Create two car instances Car myCar = new Car(); Car yourCar = new Car(); ``` -------------------------------- ### Java Fundamentals: Variables, Methods, and Classes Source: https://context7.com/exercism/java/llms.txt Demonstrates basic Java class structure, method definitions with parameters and return values, and object instantiation for calculations. ```java public class Lasagna { // Method returning a constant value public int expectedMinutesInOven() { return 40; } // Method with parameter and calculation public int remainingMinutesInOven(int actualMinutesInOven) { return expectedMinutesInOven() - actualMinutesInOven; } // Method using multiplication public int preparationTimeInMinutes(int numberOfLayers) { return numberOfLayers * 2; } // Method combining multiple calculations public int totalTimeInMinutes(int numberOfLayers, int actualMinutesInOven) { return preparationTimeInMinutes(numberOfLayers) + actualMinutesInOven; } } // Usage example Lasagna lasagna = new Lasagna(); int remaining = lasagna.remainingMinutesInOven(30); // => 10 int prepTime = lasagna.preparationTimeInMinutes(3); // => 6 int totalTime = lasagna.totalTimeInMinutes(3, 30); // => 36 ``` -------------------------------- ### Create a New Practice Exercise Source: https://github.com/exercism/java/blob/main/reference/contributing-to-practice-exercises.md Use this command to generate the necessary scaffolding for a new practice exercise, including configuration files and pulling documentation from the problem specifications repository. ```sh configlet create --practice-exercise ``` -------------------------------- ### Instantiate a Class and Call a Method in Java Source: https://github.com/exercism/java/blob/main/concepts/basics/about.md Create an instance of a class and invoke one of its methods by passing the required arguments. The result is assigned to a variable. ```java int sum = new Calculator().add(1, 2); ``` -------------------------------- ### Retrieve a Value from a Map Source: https://github.com/exercism/java/blob/main/concepts/maps/introduction.md Use the get method to retrieve the value associated with a specific key. Returns null if the key is not found. ```java fruitPrices.get("apple"); // => 100 ``` -------------------------------- ### Run Java Exercise Tests Source: https://github.com/exercism/java/blob/main/docs/TESTS.md Execute the Gradle wrapper to run the tests for the current Java exercise. Initial test failures are expected. ```batchfile C:\Users\JohnDoe>gradlew.bat test ``` ```sh ./gradlew test ``` -------------------------------- ### Sync Documentation and Metadata Source: https://github.com/exercism/java/blob/main/reference/contributing-to-practice-exercises.md Run this command from the repository root to regenerate documentation files and update metadata based on changes in the problem specifications. This is primarily for exercises sourced from the problem specifications repository. ```sh bin/configlet sync --docs --metadata --update --exercise ``` -------------------------------- ### Concept Exercise Introduction Template Source: https://github.com/exercism/java/blob/main/reference/implementing-a-concept-exercise.md This is a template for the `.docs/introduction.md.tpl` file. It uses a special tag to include concept information. ```markdown # Introduction %{concept:concept-slug} ``` -------------------------------- ### Instantiate and Call Method in Java Source: https://github.com/exercism/java/blob/main/concepts/inheritance/introduction.md Demonstrates creating an instance of the 'Animal' class typed as 'Lion' and calling the overridden 'bark()' method. The output reflects the behavior defined in the child class. ```java Animal animal = new Lion(); //creating instance of Animal, of type Lion animal.bark(); ``` -------------------------------- ### Convert String to char array in Java Source: https://github.com/exercism/java/blob/main/concepts/chars/about.md Use the `toCharArray()` method to get an array of chars from a String. Iterate over this array to process individual characters. ```java String text = "Hello"; char[] asArray = text.toCharArray(); for (char ch: asArray) { System.out.println(ch); } ``` -------------------------------- ### Run Gradle Tests Source: https://github.com/exercism/java/blob/main/CONTRIBUTING.md Execute this command to check if the reference implementation passes all tests. Ensure you are in the root of the exercise directory. ```sh ./gradlew test ``` -------------------------------- ### Initialize and Access Class Fields Source: https://github.com/exercism/java/blob/main/concepts/classes/introduction.md Illustrates initializing fields with specific values or relying on default values, and accessing/updating them using dot notation. ```java class Car { // Will be set to specified value public int weight = 2500; // Will be set to default value (0) public int year; } Car newCar = new Car(); newCar.weight; // => 2500 newCar.year; // => 0 // Update value of the field newCar.year = 2018; ``` -------------------------------- ### Run Gradle Checkstyle Validations Source: https://github.com/exercism/java/blob/main/CONTRIBUTING.md Run this command to verify that the reference implementation adheres to Checkstyle validations. This should be executed from the exercise's root directory. ```sh ./gradlew check ``` -------------------------------- ### Concatenate Strings with the '+' Operator in Java Source: https://github.com/exercism/java/blob/main/concepts/strings/about.md The '+' operator is the simplest way to concatenate strings in Java. This example demonstrates combining a literal string with a variable. ```java String name = "Jane"; "Hello " + name + "!"; // => "Hello Jane!" ``` -------------------------------- ### Get date components from LocalDate Source: https://github.com/exercism/java/blob/main/concepts/datetime/about.md Access year, month, and day of the month from a `LocalDate` instance using getter methods like `getYear()`, `getMonthValue()`, and `getDayOfMonth()`. ```java LocalDate date = LocalDate.of(2007, 12, 3); date.getYear(); // => 2007 date.getMonthValue(); // => 12 date.getDayOfMonth(); // => 3 ``` -------------------------------- ### Java For Loop Curly Bracket Placement Source: https://github.com/exercism/java/blob/main/POLICIES.md Place the opening curly bracket for for loops on the same line as the loop declaration, following Oracle's style guide. ```java // Please do this for (int i = 0; i < 10; i++) { ... } // Please don't do this for (int i = 0; i < 10; i++) { ... } ``` -------------------------------- ### Append to exercises/settings.gradle Source: https://github.com/exercism/java/blob/main/reference/implementing-a-concept-exercise.md Add this line to your `exercises/settings.gradle` file to include the new concept exercise. ```gradle include 'concept:' ``` -------------------------------- ### Overload Methods with Different Number of Parameters in Java Source: https://github.com/exercism/java/blob/main/concepts/method-overloading/introduction.md Demonstrates method overloading by defining multiple 'show' methods with the same name but varying numbers of integer parameters. This allows calling the appropriate method based on the arguments provided. ```java public class Display { public void show(int x) { System.out.println("Show with int: " + x); } public void show(int x, int y) { System.out.println("Show with two ints: " + x + ", " + y); } } ``` -------------------------------- ### Define an Enum with Fields and Methods in Java Source: https://github.com/exercism/java/blob/main/concepts/enums/about.md Enum types in Java can have constructors, fields, and methods. This example defines a 'Rating' enum with a 'numberOfStars' field and a getter method. ```java public enum Rating { GREAT(5), GOOD(4), OK(3), BAD(2), TERRIBLE(1); private final int numberOfStars; Rating(int numberOfStars) { this.numberOfStars = numberOfStars; } public int getNumberOfStars() { return this.numberOfStars; } } ``` -------------------------------- ### Instantiate and Call Method Using Enum in Java Source: https://github.com/exercism/java/blob/main/concepts/enums/about.md Shows how to create an instance of a class that uses an enum and call a method with an enum constant as an argument. The result is based on the enum value passed. ```java var shop = new Shop(); shop.getOpeningHours(DayOfWeek.WEDNESDAY); // => "9am - 5pm" ``` -------------------------------- ### Define a Java Enum with Methods and Fields Source: https://github.com/exercism/java/blob/main/concepts/enums/introduction.md Enum types in Java are classes and can have constructors, fields, and methods. This example shows an enum with a private field and a getter method. ```java public enum Rating { GREAT(5), GOOD(4), OK(3), BAD(2), TERRIBLE(1); private final int numberOfStars; Rating(int numberOfStars) { this.numberOfStars = numberOfStars; } public int getNumberOfStars() { return this.numberOfStars; } } ``` ```java Rating.GOOD.getNumberOfStars(); // => 4 ``` -------------------------------- ### Update All Exercise Gradle Wrappers Source: https://github.com/exercism/java/blob/main/reference/how-to-update-gradle.md After updating the root Gradle wrapper, run this command to synchronize the Gradle wrappers for all exercises to match the root version. ```sh ./gradlew allWrappers ``` -------------------------------- ### Sync Exercise Tests Source: https://github.com/exercism/java/blob/main/reference/contributing-to-practice-exercises.md Execute this command from the repository root to update the `.meta/tests.toml` file with the latest test cases from the canonical data. This command only affects the `.meta/tests.toml` file; any new or updated tests must still be implemented in the exercise's unit tests. ```sh bin/configlet sync --tests --update --exercise ``` -------------------------------- ### Declare and Initialize Array using Shortcut Notation in Java Source: https://github.com/exercism/java/blob/main/concepts/arrays/introduction.md Use shortcut notation to declare and initialize an array with values. The compiler infers the size. ```java // Two equivalent ways to declare and initialize an array (size is 3) int[] threeIntsV1 = new int[] { 4, 9, 7 }; int[] threeIntsV2 = { 4, 9, 7 }; ``` -------------------------------- ### Define and Implement a Java Interface Source: https://github.com/exercism/java/blob/main/concepts/interfaces/introduction.md Demonstrates the definition of a `Language` interface and its implementation in an `ItalianTraveller` class. Ensure all interface methods are implemented in the class. ```java public interface Language { String getLanguageName(); String speak(); } public class ItalianTraveller implements Language, Cloneable { // from Language interface public String getLanguageName() { return "Italiano"; } // from Language interface public String speak() { return "Ciao mondo"; } // from Cloneable interface public Object clone() { ItalianTraveller it = new ItalianTraveller(); return it; } } ``` -------------------------------- ### Create a HashMap Copy Source: https://github.com/exercism/java/blob/main/concepts/maps/about.md Initialize a new HashMap by copying an existing one using its copy constructor. ```java Map copy = new HashMap<>(fruitPrices); ``` -------------------------------- ### Java Ternary Operator Example Source: https://github.com/exercism/java/blob/main/concepts/ternary-operators/introduction.md Use the ternary operator for simple if/else assignments. It evaluates an expression and returns the value before the colon if true, or the value after the colon if false. Ensure the expression is a boolean. ```java boolean expr = 0 != 200; // Ternary statement int value = expr ? 22 : 33; // => 22 ``` -------------------------------- ### Escape Special Characters in Java Strings Source: https://github.com/exercism/java/blob/main/concepts/strings/about.md Certain characters like double quotes and backslashes must be escaped using a backslash when defining a Java string. This example shows escaping a backslash for a file path. ```java String escaped = "c:\\test.txt"; // => c:\test.txt ``` -------------------------------- ### Create a HashMap Instance Source: https://github.com/exercism/java/blob/main/concepts/maps/about.md Instantiate a HashMap. It's recommended to declare the variable as the `Map` interface type for flexibility. ```java Map fruitPrices = new HashMap<>(); ``` -------------------------------- ### Create Java Lists with List.of() Source: https://github.com/exercism/java/blob/main/concepts/lists/introduction.md Demonstrates creating immutable lists of various types using the `List.of()` method. Useful for initializing small, fixed collections. ```java List emptyListOfStrings = List.of(); List singleInteger = List.of(1); List threeBooleans = List.of(true, false, true); List listWithMultipleTypes = List.of("hello", 1, true); ``` -------------------------------- ### Java Stub Implementation Source: https://github.com/exercism/java/blob/main/POLICIES.md For exercises of difficulty 4 or lower, provide stubs for required constructors and methods. These stubs should include a placeholder to be replaced by the user's implementation. ```java throw new UnsupportedOperationException("Delete this statement and write your own implementation."); ``` -------------------------------- ### Generate Random Integer within an Offset Range in Java Source: https://github.com/exercism/java/blob/main/concepts/randomness/introduction.md To generate a random integer within a specific range that does not start at 0, add an offset to the result of `nextInt(int bound)`. The offset determines the lower bound of the generated numbers. ```java Random random = new Random(); 10 + random.nextInt(10); // => 11 ``` -------------------------------- ### Call a Method in Java Source: https://github.com/exercism/java/blob/main/concepts/basics/introduction.md Invoke a method by specifying its class and method name, followed by arguments for its parameters. Instantiate the class using 'new'. ```java int sum = new Calculator().add(1, 2); // here the "add" method has been called to perform the task of addition ``` -------------------------------- ### Java List Operations with ArrayList Source: https://github.com/exercism/java/blob/main/concepts/lists/introduction.md Shows common operations on a mutable `ArrayList`, including getting its size, adding elements, retrieving elements by index, removing elements, and checking for element presence. Note that `remove()` removes the first occurrence of the specified element. ```java List vowels = new ArrayList<>(List.of('a', 'e', 'i', 'o', 'i', 'e', 'a')); int startingSize = vowels.size(); // 7 vowels.add('u'); // vowels is now ['a', 'e', 'i', 'o', 'i', 'e', 'a', 'u'] char a = vowels.get(0); // 'a' boolean hadI = vowels.remove('i'); // true and vowels is now ['a', 'e', 'o', 'i', 'e', 'a', 'u'] boolean hasI = vowels.contains('i'); // true (still have one more left) ``` -------------------------------- ### Validate Coding Style with Gradle Source: https://github.com/exercism/java/blob/main/reference/implementing-a-concept-exercise.md Run this command from the `exercises` folder to validate the coding style of a specific concept exercise. ```shell ./gradlew concept::check ``` -------------------------------- ### Working with Arrays and Loops in Java Source: https://context7.com/exercism/java/llms.txt Illustrates array manipulation, including accessing elements by index, modifying values, and iterating using both enhanced for-each and traditional for-loops. Includes methods for counting and summing array elements based on conditions. ```java class BirdWatcher { private final int[] birdsPerDay; public BirdWatcher(int[] birdsPerDay) { this.birdsPerDay = birdsPerDay.clone(); } // Access array element by index public int getToday() { return birdsPerDay[birdsPerDay.length - 1]; } // Modify array element public void incrementTodaysCount() { birdsPerDay[birdsPerDay.length - 1]++; } // For-each loop to search array public boolean hasDayWithoutBirds() { for (int day : birdsPerDay) { if (day == 0) { return true; } } return false; } // Traditional for-loop with index public int getCountForFirstDays(int numberOfDays) { int total = 0; if (numberOfDays > birdsPerDay.length) { numberOfDays = birdsPerDay.length; } for (int i = 0; i < numberOfDays; i++) { total = total + birdsPerDay[i]; } return total; } // Counting with condition public int getBusyDays() { int total = 0; for (int day : birdsPerDay) { if (day >= 5) { total++; } } return total; } } // Usage example int[] weekData = {2, 5, 0, 7, 4, 1, 3}; BirdWatcher watcher = new BirdWatcher(weekData); watcher.getToday(); // => 3 watcher.hasDayWithoutBirds(); // => true watcher.getCountForFirstDays(4); // => 14 watcher.getBusyDays(); // => 2 ``` -------------------------------- ### Declare and Initialize Array with Shortcut Notation in Java Source: https://github.com/exercism/java/blob/main/concepts/arrays/about.md These shortcut notations allow for concise declaration and initialization of arrays with predefined values. The compiler infers the size. ```java int[] threeIntsV1 = new int[] { 4, 9, 7 }; ``` ```java int[] threeIntsV2 = { 4, 9, 7 }; ``` -------------------------------- ### Standard Array Initialization Syntax in Java Source: https://github.com/exercism/java/blob/main/concepts/arrays/introduction.md Use this syntax to declare an array with a specified type and size. Elements are initialized to default values. ```java type[] variableName = new type[size]; ``` -------------------------------- ### Java Class with Constructor and Static Factory Source: https://context7.com/exercism/java/llms.txt Define classes to combine data and behavior. Constructors initialize objects, and static factory methods provide alternative ways to create instances. ```java class NeedForSpeed { private int speed; private int batteryDrain; private int distance = 0; private int battery = 100; // Constructor to initialize fields public NeedForSpeed(int speed, int batteryDrain) { this.speed = speed; this.batteryDrain = batteryDrain; } // Static factory method public static NeedForSpeed nitro() { return new NeedForSpeed(50, 4); } public boolean batteryDrained() { return battery < batteryDrain; } public int distanceDriven() { return distance; } // Method that modifies object state public void drive() { if (!batteryDrained()) { battery -= batteryDrain; distance += speed; } } } class RaceTrack { private int distance; RaceTrack(int distance) { this.distance = distance; } public boolean canFinishRace(NeedForSpeed car) { int maxDistance = (car.getCurrentBattery() / car.getBatteryDrain()) * car.getSpeed(); return maxDistance >= distance; } } // Usage example NeedForSpeed car = new NeedForSpeed(5, 2); car.batteryDrained(); // => false car.distanceDriven(); // => 0 car.drive(); car.distanceDriven(); // => 5 NeedForSpeed fastCar = NeedForSpeed.nitro(); // Factory method RaceTrack track = new RaceTrack(100); track.canFinishRace(fastCar); // => true ``` -------------------------------- ### Define a Java Constructor with Parameters Source: https://github.com/exercism/java/blob/main/concepts/constructors/about.md Define a Java class constructor that accepts parameters to initialize fields. Arguments are passed to the constructor during object instantiation. ```java class Building { private int numberOfStories; private int totalHeight; public Building(int numberOfStories, double storyHeight) { this.numberOfStories = numberOfStories; this.totalHeight = numberOfStories * storyHeight; } } // Call a constructor with two arguments var largeBuilding = new Building(55, 6.2) ``` -------------------------------- ### Java Collections Utilities Source: https://github.com/exercism/java/blob/main/concepts/lists/about.md Illustrates utility methods from the Collections class for sorting, reversing, filling, and creating lists with repeated elements. ```java List numbers = new ArrayList<>(List.of(1, 5, 3, 2, 4)); Collections.sort(numbers); // [1, 2, 3, 4, 5] Collections.reverse(numbers); // [5, 4, 3, 2, 1] Collections.fill(numbers, 42); // [42, 42, 42, 42, 42] List fiveNines = Collections.nCopies(5, 9); // [9, 9, 9, 9, 9] ``` -------------------------------- ### Update Gradle Wrapper Version Source: https://github.com/exercism/java/blob/main/reference/how-to-update-gradle.md Use this command to update the Gradle wrapper in the exercises directory to a specific version. Replace X.Y with the desired Gradle version. ```sh ./gradlew wrapper --gradle-version=X.Y ``` -------------------------------- ### Iterating Through an Array with a For Loop in Java Source: https://github.com/exercism/java/blob/main/concepts/for-loops/introduction.md Demonstrates how to use a standard for loop to access elements of an array by index. ```java for (int i = 0; i < array.length; i++) { System.out.print(array[i]); } ``` -------------------------------- ### Declare and Initialize a Variable in Java Source: https://github.com/exercism/java/blob/main/concepts/basics/about.md Use explicit typing to declare an integer variable and assign it an initial value. Variable types cannot be changed after declaration. ```java int explicitVar = 10; // Explicitly typed ``` ```java int count = 1; // Assign initial value count = 2; // Update to new value ``` -------------------------------- ### Basic Boolean Operations in Java Source: https://github.com/exercism/java/blob/main/concepts/booleans/about.md Demonstrates the results of OR (`||`), AND (`&&`), and NOT (`!`) operations on boolean values. ```java true || false // => true false || false // => false false || true // => true true && false // => false true && true // => true !true // => false !false // => true ``` -------------------------------- ### Basic For Loop Structure in Java Source: https://github.com/exercism/java/blob/main/concepts/for-loops/introduction.md The standard syntax for a for loop in Java, consisting of initialization, a test condition, and an update statement. ```java for (initialization; test; update) { body; } ``` -------------------------------- ### Create an Animal Class in Java Source: https://github.com/exercism/java/blob/main/concepts/inheritance/introduction.md Defines a base 'Animal' class with a 'bark()' method. This serves as a parent class for other animal types. ```java public class Animal { public void bark() { System.out.println("This is an animal"); } } ``` -------------------------------- ### Custom Object with hashCode and equals Source: https://github.com/exercism/java/blob/main/concepts/maps/about.md Implement `hashCode` and `equals` correctly for custom objects used as HashMap keys. Changes to fields affecting these methods can lead to unexpected behavior. ```java public class Stock { private String name; public void setName(String name) { this.name = name; } @Override public int hashCode() { return Objects.hash(name); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (Objects.equals(Stock.class, obj.getClass()) && obj instanceof Stock other) { return Objects.equals(name, other.name); } return false; } } ``` -------------------------------- ### Fix Gradle Permission Denied Error Source: https://github.com/exercism/java/blob/main/docs/TESTS.md If you encounter a 'Permission denied' error when running Gradle on Linux, use this command to grant execute permissions to the gradlew script. ```sh chmod +x ./gradlew ``` -------------------------------- ### For Loop Initialization in Java Source: https://github.com/exercism/java/blob/main/concepts/for-loops/introduction.md Sets the initial state for the loop, typically by declaring and assigning a variable. ```java int i = 1 ``` -------------------------------- ### Use an Enum Type in a Java Class Source: https://github.com/exercism/java/blob/main/concepts/enums/about.md Demonstrates how to use an enum type as a parameter in a method and how to use a switch statement to handle different enum values. Ensure all enum constants are handled. ```java public class Shop { public String getOpeningHours(DayOfWeek dayOfWeek) { switch (dayOfWeek) { case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: case FRIDAY: return "9am - 5pm"; case SATURDAY: return "10am - 4pm" case SUNDAY: return "Closed." } } } ``` -------------------------------- ### Java Switch Statement Scope Handling Source: https://github.com/exercism/java/blob/main/concepts/switch-statement/about.md Demonstrates how to correctly handle variable scope within traditional switch statements by using curly braces `{}` to delimit the scope of each case. ```java switch (expression) { case 1: { String message = "something"; break; } case 2: { String message = "anything"; break; } // (...) } ```