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

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

Published in the Random EN group

What is Classpath in Java and how to set it?

Source: Medium Knowing the basics of programming and the flow of program files helps us understand the language. Knowing the Classpath parameter is one of the basic concepts that every Java developer should own. Today we'll discuss what a 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 set it?  Immutability in Java - 1

What is Classpath?

Classpath is one of the main parameters in Java, however it is often misunderstood by programming newbies. To simplify, the Classpath is simply a set of paths that the Java compiler and JVM must use to find the necessary classes to compile or execute other classes.

How does Classpath help the JVM in executing class files

Let's start with an example. Let's say we have a Main.java file 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 we want to compile this class:
javac test-java/src/com/programming/v1/Main.java
Now, in order to execute this class file, we need to tell the Java Virtual Machine where to look for the .class file using the 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 to. 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 computers:
export CLASSPATH="test-java/src"
The 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 There are two types of variables in Java: primitive and reference. Everything in Java is passed by value, but in the case of reference types, the original data can be updated using the passed memory address. The finalCoffee break #121.  What is Classpath in Java and how to set it?  Immutability in Java - 2 keyword is used to make a variable act like a constant, i.e. avoid reassignment. This works well for primitives that don't have heap memory, while for reference types, only reassignment is limited and internal state can be changed. This can lead to a lot of concurrency issues and race conditions. Thus, including immutable characteristics in a regular type in Java has many advantages.

Advantages of Immutability in Java

1. Thread safety

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

2. Basic 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 create business logic domains on top of it. Similarly, an immutable type can act as a great base type that you can build on.

Characteristics

1. Private and Final fields

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

2. No modifier methods

A private field cannot be accessed outside of the class. Usually, access methods (getters) and modifier methods (setters) are provided for reading and writing to fields, respectively. Modifiers are not allowed to ensure immutability.

3. Final class

Allowing class inheritance can break immutability. A subclass that extends an immutable class can affect the state of an object. Therefore, the class is final ( final ).

4. Defensive Copies

During object creation, instead of assigning arguments from the constructor directly to private fields, making a deep copy (or immutable copy) of the arguments will ensure the external modification. If one of the arguments is a reference type, it can be easily manipulated on the caller. Creating defensive copies avoids this manipulation. Similarly, for accessors (getters), instead of directly referencing an internal field, you can freely share a copy of it.

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 defensive copies in the constructor. This is because id is primitive and the name and joinDate fields are immutable types. They cannot be modified by the caller and will remain unchanged, while the achievements field requires a copy of the argument made with the List.copyOf method . This is because copyOf returns an immutable List .

  • Similarly, accessors return fields directly rather than defensive copies, because all field types are immutable (including achievements ) and thus cannot be modified outside the class.

Improvements

Before Java 16

The implementation of Employee can be improved with libraries like Lombok . This reduces verbosity in the code and helps it look cleaner. The library comes with annotations to reduce standard code. @Value (annotation) can be used to create getters and constructor of all arguments. This also creates a final class and private and final fields . As a side note, it also generates the toString , equals and hashCode methods . The Employee implementation can be rewritten with @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 release of Java 16 introduced a new Record function . It is (according to the JEP) 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 extra memory and processing required for even a small modification. Each time you need to create a new object, which can be very expensive. To get around this shortcoming, you can implement mechanisms such as caching and saving results.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION