Exercism Java Track

repository·main·Indexed 21 days ago

https://github.com/exercism/java

Source code and educational logic for Java exercises on the Exercism platform. Includes conceptual guides on Java basics (static typing, methods, classes), arrays, bit manipulation, boolean operators, and character processing, as well as information on tooling components like java-test-runner, java-representer, and java-analyzer.

Tokens
30.9K
Snippets
121
Records
159
Agent score
72%

What's inside exercism-java

  1. Overview of the Exercism Java Track

    main
    This repository serves as the central source for all Java exercises within the Exercism platform. It contains the exercise logic and code required for learners to complete the Java track.
  2. What is a class in Java

    main

    A class is the primary object-oriented construct in Java. It acts as a template for creating instances (also known as objects). A class combines:

    1. Fields (also known as instance variables): Data stored by the class.
    2. Methods: Behavior or actions the class can perform.

    The combination of grouping related data and behavior while restricting access to members is known as encapsulation.

    class Car {
    }
    
    // Create two car instances
    Car myCar = new Car();
    Car yourCar = new Car();
  3. What is a Set in Java

    main

    A Set is an unordered collection that guarantees no duplicate values are present. Unlike a List, which allows duplicates, a Set ensures each element is unique. The generic type parameter (e.g., Set<Integer>) defines the type of elements the set can hold.

    Set<Integer> ints = Set.of(1, 2, 3);
    Set<String> strings = Set.of("alpha", "beta", "gamma");
    Set<Object> mixed = Set.of(1, false, "foo");
  4. What is an interface in Java

    main

    An interface is a type that defines a group of related functionality through method signatures without providing implementation bodies. It serves to decouple the usage of a class from its specific implementation, enabling polymorphism. This allows a single type to support multiple different implementations or provide generic behaviors like formatting, comparison, or conversion.

    Key characteristics:

    • Methods appear as signatures only (no bodies).
    • Implementing classes must provide implementations for all operations defined by the interface.
    • Interfaces typically contain instance methods.
    • A class can implement multiple interfaces (e.g., implements InterfaceA, InterfaceB).
    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;
        }
    }
  5. What is method overloading in Java

    main

    Method overloading allows a class to define multiple methods with the same name, provided they have different parameter lists. This is a fundamental object-oriented feature used to perform similar operations with different types or numbers of inputs, improving code readability and organization.

    Key Rules

    • Signature is the Deciding Factor: Overloading is determined by the method's signature, which consists of the method name and the parameter list.
    • Return Types are Insufficient: You cannot overload a method by only changing its return type; the parameter list must be different.
    • Parameter Requirements: To successfully overload, methods must differ in either the number of parameters or the type of parameters.
  6. What is a Map and how to use it in Java

    main

    A Map is a data structure used for storing key-value pairs, similar to dictionaries in other languages. In Java, Map is an interface, and HashMap is a common implementation. Each key in a map can be associated with exactly one value; if you use put with an existing key, the old value will be updated with the new one.

    // Make an instance
    Map<String, Integer> fruitPrices = new HashMap<>();
    
    // Add entries
    fruitPrices.put("apple", 100);
    fruitPrices.put("pear", 80);
    
    // Update an existing key
    fruitPrices.put("pear", 40);
    // Result: { "apple" => 100, "pear" => 40 }
  7. Define classes and methods in Java

    main

    Java is an object-oriented language where all functions (called methods) must be defined within a class.

    • Defining a class: Use the class keyword.
    • Defining a method: Methods must explicitly declare the types for all parameters and the return type. There is no type inference for parameters.
    • Returning values: Use the return keyword to send a value back from a method.
    • Access Control: Use the public access modifier to allow a method to be called by other classes.
    • Scope: The scope of variables and methods is defined by curly braces { and }.
    class Calculator {
        public int add(int x, int y) {
            return x + y;
        }
    }
  8. Override methods in a subclass using @Override

    main

    When a subclass provides a specific implementation for a method already defined in its parent class, it is called overriding.

    While not strictly required by the compiler, it is a best practice to use the @Override annotation. This annotation explicitly indicates that the method is intended to override a method from the superclass, helping to prevent errors (such as typos in the method signature) that would otherwise result in the creation of a new method instead of an override.

    @Override
    public void bark() {
        System.out.println("Lion here!!");
    }
  9. Java Class and Method Fundamentals

    main

    In Java, logic is organized into classes. To use a method, you must typically create an instance of its class and call the method on that instance using the class.method() syntax.

    Key components include:

    • Method: A series of statements executed when called.
    • Parameter: Information passed into a method during invocation.
    • Return values: Specified in the method signature; the return statement exits the method and passes control (and a value) back to the caller.
    • Visibility: Controls access to classes and methods. If no modifier is provided, the class/method is package-private (accessible only within the same package). Use public, protected, or private to change this visibility.
  10. Use Boolean Expressions and Operators for Logic

    main

    Boolean logic is used to evaluate conditions that result in a boolean value (true or false).

    Common operators include:

    • Equality ==: Returns true if two values are equal.
    • Inequality !=: Returns true if two values are not equal.
    • Logical-Or ||: Returns true if either (or both) expressions are true.
    • Modulo operator %: Returns the remainder of a division. For example, number % 2 == 0 is a common way to check if a number is even.
  11. Generate random integers with java.util.Random

    main

    Use the java.util.Random class to generate random integers.

    • To get any integer within the full range of Integer.MIN_VALUE to Integer.MAX_VALUE, use nextInt().
    • To get a non-negative integer within a specific range from 0 (inclusive) to an upper bound (exclusive), use nextInt(int bound).
    • To generate a random integer within a custom range [min, max), use the formula: min + random.nextInt(max - min).
    Random random = new Random();
    
    // Full range
    random.nextInt();
    
    // Range 0 to 9
    random.nextInt(10);
    
    // Range 10 to 19
    10 + random.nextInt(10);