JavaRush /Java Blog /Random EN /Coffee break #121. What is Classpath in Java and how to i...

Coffee break #121. What is Classpath in Java and how to install it? Immutability in Java

Published in the Random EN group

What is Classpath in Java and how to install it?

Source: Medium Knowing the basics of programming and the execution flow of program files helps us understand a language. Knowing the Classpath parameter is one of the basic concepts that every Java developer should know. Today we will discuss what a class path ( Classpath ) is, how to set it, and how it helps the JVM execute class files. Coffee break #121.  What is Classpath in Java and how to install it?  Immutability in Java - 1

What is Classpath?

Classpath is one of the basic parameters in Java, but it is often misunderstood by newcomers to programming. To simplify, a Classpath is simply a set of paths along which the Java compiler and JVM must find the necessary classes to compile or execute other classes.

How Classpath helps JVM in executing class files

Let's start with an example. Let's assume we have a Main.java file which is located in the /Users/vikram/Documents/test-java/src/com/programming/v1/Main.java folder .
package com.programming.v1;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello classpath");
    }
}
Let's say we are in /Users/vikram/Documents and want to compile this class:
javac test-java/src/com/programming/v1/Main.java
Now, to execute this class file, we need to tell the Java Virtual Machine where to look for the .class file using classpath or the cp flag in the java command .
vg@lp1 Documents % java -cp "test-java/src" com.programming.v1.Main
Hello classpath
vg@lp1 Documents % java -classpath "test-java/src" com.programming.v1.Main
Hello classpath
The first parameter is the root folder where the package is written. The second parameter is the package name with the class name. When a Java command is executed, the Java Virtual Machine looks in the test-java/src folder and then loads the main class to execute it.

How to set Classpath variable

The Classpath variable can be set as shown below on Linux machines:
export CLASSPATH="test-java/src"
Classpath on a Windows machine can be added/updated using environment variables. Once the environment variable is set, the java command can be executed as shown below:
vg@lp1 Documents % java com.programming.v1.Main
Hello classpath
That's all there is to know about Classpath . Thank you for reading!

Immutability in Java

Source: Medium Variables in Java are of two types: primitive and reference. Everything in Java is passed by value, but in the case of reference types, the source data can be updated using the passed memory address. The finalCoffee break #121.  What is Classpath in Java and how to install it?  Immutability in Java - 2 keyword is used to make the variable act as a constant, that is, avoid reassignment. This works well for primitives that have no heap memory, whereas for reference types only reassignment is limited and the internal state can be changed. This can lead to many concurrency issues and race conditions. Thus, including immutable characteristics in a regular type in Java provides many benefits.

Benefits of Immutability in Java

1. Thread safety

Immutable types are immune to race conditions in a multi-threaded environment because the object will remain consistent after it is created. Multiple threads cannot change their internal state, so synchronization is not required.

2. Fundamental type

String in the Java Standard Library is a good example of a base class. This is a very simple and immutable class that can be used to build business logic domains on top of it. Likewise, an immutable type can act as a great base type on which to build.

Characteristics

1. Private and Final fields

The fields that contain the state of an object are private and final . Private visibility prevents direct access to the field, while final visibility ensures that the field is assigned only once.

2. No modifier methods

The private field cannot be accessed outside the class. Typically, access methods (getters) and modifier methods (setters), respectively, are provided to read and write to fields. To ensure consistency, modifiers are not allowed.

3. Final class

Allowing class inheritance may break immutability. A subclass extending an immutable class can affect the state of an object. Therefore, the class is final .

4. Defensive Copies

During object creation, instead of assigning arguments from the constructor directly to private fields, creating a deep copy (or immutable copy) of the arguments will provide external modification. If one of the arguments is a reference type, it can be easily manipulated on the caller's end. Creating protective copies allows you to avoid this manipulation. Similarly, for accessors (getters), instead of directly referencing an internal field, a copy of it can be freely shared.

Implementation

Employee

import java.time.LocalDate;
import java.util.List;

import static java.util.List.copyOf;

public final class Employee {

    private final long id;
    private final String name;
    private final LocalDate joinDate;
    private final List<String> achievements;

    public Employee(long id,
                    String name,
                    LocalDate joinDate,
                    List<String> achievements) {
        this.id = id;
        this.name = name;
        this.joinDate = joinDate;
        this.achievements = copyOf(achievements);
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public LocalDate getJoinDate() {
        return joinDate;
    }

    public List<String> getAchievements() {
        return achievements;
    }
}
  • Not all fields have protective copies in the constructor. This is because id is primitive and the name and joinDate fields are immutable types. They cannot be changed by the caller and will remain unchanged, while the achievements field requires a copy of the argument made using the List.copyOf method . This is because copyOf returns an immutable List .

  • Likewise, accessor methods return fields directly rather than defensive copies because all field types are immutable (including achievements ) and therefore cannot be modified outside the class.

Improvements

Before Java 16

The Employee implementation can be improved with libraries such as Lombok . This reduces verbosity in the code and helps it look cleaner. The library comes with annotations to shorten the standard code. @Value (annotation) can be used to create getters and a constructor for all arguments. This also creates a final class and private and final fields . As a note, it also generates toString , equals and hashCode methods . The Employee implementation can be rewritten using @Value as shown below:
import lombok.Value;

import java.time.LocalDate;
import java.util.List;

import static java.util.List.copyOf;

@Value
public class Employee {

    long id;
    String name;
    LocalDate joinDate;
    List<String> achievements;

    public Employee(long id,
                    String name,
                    LocalDate joinDate,
                    List<String> achievements) {
        this.id = id;
        this.name = name;
        this.joinDate = joinDate;
        this.achievements = copyOf(achievements);
    }
}

Java 16 and later

The Java 16 release introduced a new Record feature . These (as stated by JEP) are classes that act as transparent carriers of immutable data and can be thought of as nominal tuples. The Employee class can be re-implemented as record Employee as shown below.
import java.time.LocalDate;
import java.util.List;

import static java.util.List.copyOf;

public record Employee(long id,
                       String name,
                       LocalDate joinDate,
                       List<String> achievements) {

    public Employee(long id,
                    String name,
                    LocalDate joinDate,
                    List<String> achievements) {
        this.id = id;
        this.name = name;
        this.joinDate = joinDate;
        this.achievements = copyOf(achievements);
    }
}

Flaws

The only problem with immutability is the additional memory and processing that even a small modification requires. Each time you need to create a new object, which can be very expensive. To get around this drawback, you can implement mechanisms such as caching and saving results.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION