Java Misc

class ClassA implements Cloneable { private int someNum; private ClassC nestedObjectReference; @Override public Object clone() throws CloneNotSupportedException { ClassA classA = (ClassA) super.clone(); // with this, we are ensuring that deep copy will be performed classA.setNestedObjectReference((ClassC) this.nestedObjectReference.clone()); return classA; } // constructor, getters and setters } class ClassC implements Cloneable { private String classData; public…

Read More What is a Deep Copy in Java?

protected Object clone() throws CloneNotSupportedException class ClassA implements Cloneable { private int someNum; private ClassC nestedObjectReference; @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } // getter and setter methods } class ClassC { private String classData; public ClassC(String classData) { this.classData = classData; } // getter and setter methods } public class Test…

Read More Object Cloning in Java

public sealed class Vehicle permits Car, Truck, Bus {} final class Bus extends Vehicle { } non-sealed class Truck extends Account { } sealed class Car permits BlueCar, RedCar{ } public abstract sealed class User permits PremiumUser, AdvancedUser { public abstract String getUserData(); } non-sealed class PremiumUser extends User { @Override public String getUserData() {…

Read More Sealed Classes and Interfaces in Java

class Test { public static void main(String[] args) { String name = null; System.out.println(name.toUpperCase()); } } Output: Exception in thread “main” java.lang.NullPointerException at com.example.Test.main (Test.java:9)   Here, we got an error message that the NPE has occurred on line 9. Unfortunately, we can’t conclude which value exactly was null from the message. class Test { public static…

Read More Helpful NullPointerExceptions (NPE) in Java

class User { private String name; private String username; private String membershipType; private String address; public User(String name, String username, String membershipType, String address) { this.name = name; this.username = username; this.membershipType = membershipType; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public…

Read More Java Records

String multilineText= “”” Hi, this is one simple example of a multiline text”””; class Test { public static void main(String[] args) { String example = “{\”key1\”:\”value1\”,\”key2\”:” + “\”value2\”,\”key3\”:\”value3\”}”; System.out.println(example); } } Output: {“key1″:”value1″,”key2″:”value2″,”key3″:”value3”}   Now, let’s use a Text Block: class Test { public static void main(String[] args) { String example = “”” { “key1”:…

Read More Java Text Blocks