Exercism Java Track
repository·main·Indexed 21 days ago
https://github.com/exercism/javaSource 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.
What's inside exercism-java
- 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.
What is a class in Java
mainA class is the primary object-oriented construct in Java. It acts as a template for creating instances (also known as objects). A class combines:
- Fields (also known as instance variables): Data stored by the class.
- 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();What is a Set in Java
mainA
Setis an unordered collection that guarantees no duplicate values are present. Unlike aList, which allows duplicates, aSetensures 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");What is an interface in Java
mainAn 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; } }What is method overloading in Java
mainMethod 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.
What is a Map and how to use it in Java
mainA
Mapis a data structure used for storing key-value pairs, similar to dictionaries in other languages. In Java,Mapis an interface, andHashMapis a common implementation. Each key in a map can be associated with exactly one value; if you useputwith 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 }Define classes and methods in Java
mainJava is an object-oriented language where all functions (called methods) must be defined within a
class.- Defining a class: Use the
classkeyword. - 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
returnkeyword to send a value back from a method. - Access Control: Use the
publicaccess 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; } }- Defining a class: Use the
Work with the `char` primitive type
mainIn Java, the
charprimitive type is a 16-bit representation of a single character. Character literals are defined using single quotes (e.g.,'A').char lowerA = 'a'; char upperB = 'B';Override methods in a subclass using @Override
mainWhen 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
@Overrideannotation. 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!!"); }Java Class and Method Fundamentals
mainIn 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
returnstatement 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, orprivateto change this visibility.
Use Boolean Expressions and Operators for Logic
mainBoolean logic is used to evaluate conditions that result in a
booleanvalue (trueorfalse).Common operators include:
- Equality
==: Returnstrueif two values are equal. - Inequality
!=: Returnstrueif two values are not equal. - Logical-Or
||: Returnstrueif either (or both) expressions are true. - Modulo operator
%: Returns the remainder of a division. For example,number % 2 == 0is a common way to check if a number is even.
- Equality
Generate random integers with java.util.Random
mainUse the
java.util.Randomclass to generate random integers.- To get any integer within the full range of
Integer.MIN_VALUEtoInteger.MAX_VALUE, usenextInt(). - To get a non-negative integer within a specific range from
0(inclusive) to an upper bound (exclusive), usenextInt(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);- To get any integer within the full range of