repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P52_WorkingAroundNPE/src/main/java/modern/challenge/Main.java | Chapter02/P52_WorkingAroundNPE/src/main/java/modern/challenge/Main.java | package modern.challenge;
public class Main {
public static void main(String[] args) {
// 1 - Fix: NPE when calling an instance method via a null object
// ChainSaw cs = ChainSaw.initChainSaw("QW-T650"); // we get an UnsupportedOperationException
// cs.start(); // this code is not executed
// 2 - Fix: NPE when accessing (or, modifying) field of a null object
// ChainSaw cs = ChainSaw.initChainSaw("QW-T650"); // we get an UnsupportedOperationException
// boolean isStarted = cs.started; // this code is not executed
// System.out.println("Is started: " + isStarted);
// 3 - Fix: NPE when null is passed in method argument
// ChainSaw cs = ChainSaw.initChainSaw(null); // the passed null can be the result of calling an external service
// 4 - Fix: NPE when accessing index value of null array (or, collection)
/*
ChainSaw myChainSaw = ChainSaw.initChainSaw("QWE-T800");
ChainSaw[] friendsChainSaw = new ChainSaw[]{
ChainSaw.initChainSaw("Q22-T450"),
ChainSaw.initChainSaw("QRT-T300"),
ChainSaw.initChainSaw("Q-T900"),
null,
// ChainSaw.initChainSaw("QMM3-T850"), // this model is not supported
ChainSaw.initChainSaw("ASR-T900")
};
int score = myChainSaw.performance(friendsChainSaw);
System.out.println("Score: " + score);
*/
// 5 - Fix: NPE when accessing a field via a getter
// ChainSaw cs = ChainSaw.initChainSaw("T5A-T800");
// String power = cs.getPower();
// System.out.println(power.concat(" Watts"));
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P66_CompletenessInSwitchJDK21/src/main/java/modern/challenge/Main.java | Chapter02/P66_CompletenessInSwitchJDK21/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.util.Arrays;
public class Main {
final static class PlayerClub implements Sport {};
private enum PlayerTypes implements Sport { TENNIS, FOOTBALL, SNOOKER }
sealed interface Sport permits PlayerTypes, PlayerClub {};
// JDK 20
/*
private static String createPlayerOrClub(Sport s) {
return switch (s) {
case PlayerTypes p when p == PlayerTypes.TENNIS -> "Creating a tennis player ...";
case PlayerTypes p when p == PlayerTypes.FOOTBALL -> "Creating a football player ...";
case PlayerTypes p -> "Creating a snooker player ...";
case PlayerClub p -> "Creating a sport club ...";
};
}
*/
// JDK 21
private static String createPlayerOrClub(Sport s) {
return switch (s) {
case PlayerTypes.TENNIS -> "Creating a tennis player ...";
case PlayerTypes.FOOTBALL -> "Creating a football player ...";
case PlayerTypes.SNOOKER -> "Creating a snooker player ...";
case PlayerClub p -> "Creating a sport club ...";
};
}
public static void main(String[] args) {
Arrays.asList(PlayerTypes.FOOTBALL, PlayerTypes.SNOOKER, PlayerTypes.TENNIS, new PlayerClub()).stream()
.map(Main::createPlayerOrClub)
.forEach(System.out::println);
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P64_GuardedPatternsSwitch2JDK17/src/main/java/modern/challenge/Assess.java | Chapter02/P64_GuardedPatternsSwitch2JDK17/src/main/java/modern/challenge/Assess.java | package modern.challenge;
import static modern.challenge.FuelType.GASOLINE;
import static modern.challenge.FuelType.HYDROGEN;
import static modern.challenge.FuelType.KEROSENE;
enum FuelType { GASOLINE, HYDROGEN, KEROSENE }
class Vehicle {
private final int gallon;
private final FuelType fuel;
public Vehicle(int gallon, FuelType fuel) {
this.gallon = gallon;
this.fuel = fuel;
}
public int getGallon() {
return gallon;
}
public FuelType getFuel() {
return fuel;
}
}
public class Assess {
private static String theVehicle(Vehicle vehicle) {
return switch (vehicle) {
case Vehicle v && v.getFuel().equals(GASOLINE)
&& v.getGallon() < 120 -> "probably a car/van";
case Vehicle v && v.getFuel().equals(GASOLINE)
&& v.getGallon() > 120 -> "probably a big rig";
case Vehicle v && v.getFuel().equals(HYDROGEN)
&& v.getGallon() < 300_000 -> "probably an aircraft";
case Vehicle v && v.getFuel().equals(HYDROGEN)
&& v.getGallon() > 300_000 -> "probably a rocket";
case Vehicle v && v.getFuel().equals(KEROSENE)
&& v.getGallon() > 2_000 && v.getGallon() < 6_000
-> "probably a narrow-body aircraft";
case Vehicle v && v.getFuel().equals(KEROSENE)
&& v.getGallon() > 6_000 && v.getGallon() < 55_000
-> "probably a large (B747-400) aircraft";
default -> "no clue";
};
}
public static void main(String[] args) {
System.out.println(theVehicle(new Vehicle(500, GASOLINE)));
System.out.println(theVehicle(new Vehicle(2000, HYDROGEN)));
System.out.println(theVehicle(new Vehicle(20000, KEROSENE)));
System.out.println(theVehicle(new Vehicle(20, KEROSENE)));
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P38_StringToBinaryEncodings/src/main/java/modern/challenge/Charsets.java | Chapter02/P38_StringToBinaryEncodings/src/main/java/modern/challenge/Charsets.java | package modern.challenge;
import java.nio.charset.Charset;
public class Charsets {
private Charsets() {
throw new AssertionError("Cannot be instantiated");
}
public static String stringToBinaryEncoding(String str, String encoding) {
if (str == null) {
throw new IllegalArgumentException("The given string cannot be null");
}
final Charset charset = Charset.forName(encoding);
final byte[] strBytes = str.getBytes(charset);
final StringBuilder strBinary = new StringBuilder();
for (byte strByte : strBytes) {
for (int i = 0; i < 8; i++) {
strBinary.append((strByte & 128) == 0 ? 0 : 1);
strByte <<= 1;
}
strBinary.append(" ");
}
return strBinary.toString().trim();
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P38_StringToBinaryEncodings/src/main/java/modern/challenge/Main.java | Chapter02/P38_StringToBinaryEncodings/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class Main {
public static final String LETTER = "A";
public static final String CHINESE = "暗";
public static final String EMOJI = "😍";
public static final String STR = "😍 I love 💕 you Ӝ so much 💕 😍 🎼🎼🎼!";
public static void main(String[] args) throws IOException {
System.out.println("""
////////////////////////////////////////////////////////////////////////
// For Unicode characters having code point less than 65,535 (0xFFFF) //
////////////////////////////////////////////////////////////////////////
""");
String l1 = Charsets.stringToBinaryEncoding(LETTER, "UTF-32");
String l2 = Charsets.stringToBinaryEncoding(LETTER, StandardCharsets.UTF_16BE.name());
String l3 = Charsets.stringToBinaryEncoding(LETTER, StandardCharsets.UTF_16LE.name());
String l4 = Charsets.stringToBinaryEncoding(LETTER, StandardCharsets.UTF_8.name());
System.out.println("LETTER (UTF-32): " + l1);
System.out.println("LETTER (UTF_16BE): " + l2);
System.out.println("LETTER (UTF_16LE): " + l3);
System.out.println("LETTER (UTF_8): " + l4);
System.out.println();
String c1 = Charsets.stringToBinaryEncoding(CHINESE, "UTF-32");
String c2 = Charsets.stringToBinaryEncoding(CHINESE, StandardCharsets.UTF_16BE.name());
String c3 = Charsets.stringToBinaryEncoding(CHINESE, StandardCharsets.UTF_16LE.name());
String c4 = Charsets.stringToBinaryEncoding(CHINESE, StandardCharsets.UTF_8.name());
System.out.println("CHINESE (UTF-32): " + c1);
System.out.println("CHINESE (UTF_16BE): " + c2);
System.out.println("CHINESE (UTF_16LE): " + c3);
System.out.println("CHINESE (UTF_8): " + c4);
System.out.println();
String e1 = Charsets.stringToBinaryEncoding(EMOJI, "UTF-32");
String e2 = Charsets.stringToBinaryEncoding(EMOJI, StandardCharsets.UTF_16BE.name());
String e3 = Charsets.stringToBinaryEncoding(EMOJI, StandardCharsets.UTF_16LE.name());
String e4 = Charsets.stringToBinaryEncoding(EMOJI, StandardCharsets.UTF_8.name());
System.out.println("EMOJI (UTF-32): " + e1);
System.out.println("EMOJI (UTF_16BE): " + e2);
System.out.println("EMOJI (UTF_16LE): " + e3);
System.out.println("EMOJI (UTF_8): " + e4);
System.out.println();
String s1 = Charsets.stringToBinaryEncoding(STR, "UTF-32");
String s2 = Charsets.stringToBinaryEncoding(STR, StandardCharsets.UTF_16BE.name());
String s3 = Charsets.stringToBinaryEncoding(STR, StandardCharsets.UTF_16LE.name());
String s4 = Charsets.stringToBinaryEncoding(STR, StandardCharsets.UTF_8.name());
System.out.println("STR (UTF-32): " + s1);
System.out.println("STR (UTF_16BE): " + s2);
System.out.println("STR (UTF_16LE): " + s3);
System.out.println("STR (UTF_8): " + s4);
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P38_ReadingWritingFileUTF8/src/main/java/modern/challenge/Main.java | Chapter02/P38_ReadingWritingFileUTF8/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Main {
public static void main(String[] args) throws IOException {
Path chineseUtf16File = Paths.get("chineseUTF16.txt");
Path chineseUtf8File = Paths.get("chineseUTF8.txt");
System.out.println("\n\nRead a text file using UTF-8 (before JDK 18):");
System.out.println("-------------------------------------------------");
try ( BufferedReader br = new BufferedReader(
new FileReader(chineseUtf8File.toFile(), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
System.out.println("\n\nRead a text file using UTF-8 (JDK 18+):");
System.out.println("-------------------------------------------");
try ( BufferedReader br = new BufferedReader(
new FileReader(chineseUtf8File.toFile()))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
System.out.println("\n\nRead a text file using UTF-16 (all JDKs):");
System.out.println("---------------------------------------------");
try ( BufferedReader br = new BufferedReader(
new FileReader(chineseUtf16File.toFile(), StandardCharsets.UTF_16))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
System.out.println("\n\nWrite text file using UTF-8 (before JDK 18)");
System.out.println("-----------------------------------------------");
Path textFile1 = Paths.get("sampleUtf8BeforeJDK18.txt");
try ( BufferedWriter bw = Files.newBufferedWriter(
textFile1, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
bw.write("Lorem ipsum dolor sit amet, consectetur adipiscing elit, ");
bw.newLine();
bw.write("sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
}
System.out.println("\n\nWrite text file using UTF-8 (JDK 18+)");
System.out.println("-----------------------------------------");
Path textFile2 = Paths.get("sampleUtf8AfterJDK18.txt");
try ( BufferedWriter bw = Files.newBufferedWriter(textFile2,
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
bw.write("Lorem ipsum dolor sit amet, consectetur adipiscing elit, ");
bw.newLine();
bw.write("sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
}
System.out.println("\n\nWrite text file using UTF-16 (all JDKs)");
System.out.println("-------------------------------------------");
Path textFile3 = Paths.get("sampleUtf16.txt");
try ( BufferedWriter bw = Files.newBufferedWriter(
textFile3, StandardCharsets.UTF_16,
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
bw.write("Lorem ipsum dolor sit amet, consectetur adipiscing elit, ");
bw.newLine();
bw.write("sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
}
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P48_XlintDefaultConstructor/src/main/java/module-info.java | Chapter02/P48_XlintDefaultConstructor/src/main/java/module-info.java | module P48_XlintDefaultConstructor {
exports modern.challenge;
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P48_XlintDefaultConstructor/src/main/java/modern/challenge/House.java | Chapter02/P48_XlintDefaultConstructor/src/main/java/modern/challenge/House.java | package modern.challenge;
public class House {
private String location;
private float price;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P48_XlintDefaultConstructor/src/main/java/modern/challenge/Main.java | Chapter02/P48_XlintDefaultConstructor/src/main/java/modern/challenge/Main.java | package modern.challenge;
public class Main {
public static void main(String[] args) {
House house = new House();
house.setLocation("NY, 23");
house.setPrice(100_000);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P47_ErasureBridge/src/main/java/modern/challenge/Puzzle.java | Chapter02/P47_ErasureBridge/src/main/java/modern/challenge/Puzzle.java | package modern.challenge;
public class Puzzle<E> {
public E piece;
public Puzzle(E piece) {
this.piece = piece;
}
public void setPiece(E piece) {
this.piece = piece;
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P47_ErasureBridge/src/main/java/modern/challenge/FunPuzzle.java | Chapter02/P47_ErasureBridge/src/main/java/modern/challenge/FunPuzzle.java | package modern.challenge;
public class FunPuzzle extends Puzzle<String> {
public FunPuzzle(String piece) {
super(piece);
}
@Override
public void setPiece(String piece) {
super.setPiece(piece);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P47_ErasureBridge/src/main/java/modern/challenge/Main.java | Chapter02/P47_ErasureBridge/src/main/java/modern/challenge/Main.java | package modern.challenge;
public class Main {
public static void main(String[] args) {
FunPuzzle fp = new FunPuzzle("head");
Puzzle p = fp; // Compiler throws an unchecked warning (raw type)
p.setPiece(5); // ClassCastException
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P55_EqualOperatorVsEquals/src/main/java/modern/challenge/Main.java | Chapter02/P55_EqualOperatorVsEquals/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
Integer x1 = 14;
Integer y1 = 14;
System.out.println(x1 == y1); // true
System.out.println(x1.equals(y1)); // true
Integer x2 = 129;
Integer y2 = 129;
System.out.println(x2 == y2); // false
System.out.println(x2.equals(y2)); // true
System.out.println();
// don't do this
List<Integer> listOfInt1 = new ArrayList<>(Arrays.asList(x1, y1, x2, y2));
System.out.println(listOfInt1);
listOfInt1.removeIf(t -> t == x1 || t == x2);
System.out.println(listOfInt1);
System.out.println();
// do this
List<Integer> listOfInt2 = new ArrayList<>(Arrays.asList(x1, y1, x2, y2));
System.out.println(listOfInt2);
listOfInt2.removeIf(t -> t.equals(x1) || t.equals(x2));
System.out.println(listOfInt2);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P40_StringIndentity/src/main/java/modern/challenge/MyPoint.java | Chapter02/P40_StringIndentity/src/main/java/modern/challenge/MyPoint.java | package modern.challenge;
public class MyPoint {
private final int x;
private final int y;
private final int z;
public MyPoint(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
@Override
public int hashCode() {
int hash = 7;
hash = 23 * hash + this.x;
hash = 23 * hash + this.y;
hash = 23 * hash + this.z;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MyPoint other = (MyPoint) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return this.z == other.z;
}
@Override
public String toString() {
return "MyPoint{" + "x=" + x + ", y=" + y + ", z=" + z + '}';
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P40_StringIndentity/src/main/java/modern/challenge/Main.java | Chapter02/P40_StringIndentity/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.util.Objects;
public class Main {
public static void main(String[] args) throws IOException {
MyPoint p = new MyPoint(1, 2, 3);
System.out.println("Objects.toIdentityString(): "
+ Objects.toIdentityString(p));
System.out.println("p.toString(): "
+ p.toString());
System.out.println("Integer.toHexString(p.hashCode()): "
+ Integer.toHexString(p.hashCode()));
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P44_ByteToHexString/src/main/java/modern/challenge/Main.java | Chapter02/P44_ByteToHexString/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
byte v = -125;
byte[] varr = new byte[]{-3, 0, 12, 11, -5, 123};
String s = "fd000c0bfb7b";
System.out.println("Convert byte value to hexadecimal string:");
System.out.println("byteToHexStringV1:" + Converters.byteToHexStringV1(v));
System.out.println("byteToHexStringV2:" + Converters.byteToHexStringV2(v));
System.out.println("byteToHexStringV3:" + Converters.byteToHexStringV3(v));
System.out.println("byteToHexStringV4:" + Converters.byteToHexStringV4(v));
System.out.println("byteToHexStringV5:" + Converters.byteToHexStringV5(v));
System.out.println();
System.out.println("Convert byte array to hexadecimal string:");
System.out.println("byteArrToHexStringV1:" + Converters.byteArrToHexStringV1(varr));
System.out.println("byteArrToHexStringV2:" + Converters.byteArrToHexStringV2(varr));
System.out.println("byteArrToHexStringV3:" + Converters.byteArrToHexStringV3(varr));
System.out.println("byteArrToHexStringV4:" + Converters.byteArrToHexStringV4(varr));
System.out.println();
System.out.println("Convert hexadecimal string to byte value:");
System.out.println("hexToByteV1:" + Converters.hexToByteV1("09"));
System.out.println("hexToByteV2:" + Converters.hexToByteV2("09"));
System.out.println();
System.out.println("Convert hexadecimal string to byte array:");
System.out.println("hexStringToByteArrV1: "
+ Arrays.toString(Converters.hexStringToByteArrV1(s)));
System.out.println("hexStringToByteArrV1: "
+ Arrays.toString(Converters.hexStringToByteArrV2(s)));
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P44_ByteToHexString/src/main/java/modern/challenge/Converters.java | Chapter02/P44_ByteToHexString/src/main/java/modern/challenge/Converters.java | package modern.challenge;
import java.math.BigInteger;
import java.util.HexFormat;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public final class Converters {
private Converters() {
throw new AssertionError("Cannot be instantiated");
}
public static String byteToHexStringV1(byte v) {
int higher = (v >> 4) & 0xF;
int lower = v & 0xF;
String result = String.valueOf(
new char[]{
Character.forDigit(higher, 16),
Character.forDigit(lower, 16)}
);
return result;
}
public static String byteToHexStringV2(byte v) {
char[] hexArray = "0123456789abcdef".toCharArray();
int hex = v & 0xFF;
String result = String.valueOf(
new char[]{
hexArray[hex >>> 4],
hexArray[hex & 0x0F]}
);
return result;
}
public static String byteToHexStringV3(byte v) {
return Integer.toHexString(v & 0xFF);
}
// this is slow, better avoid
public static String byteToHexStringV4(byte v) {
return String.format("%02x ", v);
}
public static String byteToHexStringV5(byte v) {
HexFormat hex = HexFormat.of();
return hex.toHexDigits(v);
}
public static String byteArrToHexStringV1(byte[] varr) {
if (varr == null || varr.length == 0) {
throw new IllegalArgumentException("The given array cannot be null or empty");
}
char[] hexArray = "0123456789abcdef".toCharArray();
int l = varr.length;
char[] cs = new char[l * 2];
for (int i = 0; i < l; i++) {
int hex = varr[i] & 0xFF;;
int higher = hex >>> 4;
int lower = hex & 0x0F;
cs[i * 2 + 0] = hexArray[higher];
cs[i * 2 + 1] = hexArray[lower];
}
return String.valueOf(cs);
}
public static String byteArrToHexStringV2(byte[] varr) {
if (varr == null || varr.length == 0) {
throw new IllegalArgumentException("The given array cannot be null or empty");
}
return new BigInteger(1, varr).toString(16);
}
// this is slow, better avoid
public static String byteArrToHexStringV3(byte[] varr) {
if (varr == null || varr.length == 0) {
throw new IllegalArgumentException("The given array cannot be null or empty");
}
return IntStream.range(0, varr.length)
.mapToObj(i -> String.format("%02x", varr[i]))
.collect(Collectors.joining());
}
public static String byteArrToHexStringV4(byte[] varr) {
if (varr == null || varr.length == 0) {
throw new IllegalArgumentException("The given array cannot be null or empty");
}
HexFormat hex = HexFormat.of();
return hex.formatHex(varr);
}
public static byte hexToByteV1(String s) {
if (s == null || s.length() != 2) {
throw new IllegalArgumentException("The given string is not a valid hexadecimal number");
}
int d1 = Character.digit(s.charAt(0), 16);
int d2 = Character.digit(s.charAt(1), 16);
if (d1 == -1 || d2 == -1) {
throw new IllegalArgumentException("The given string is not a valid hexadecimal number");
}
return (byte) ((d1 << 4) + d2);
}
public static byte hexToByteV2(String s) {
if (s == null || s.length() != 2) {
throw new IllegalArgumentException("The given string is not a valid hexadecimal number");
}
HexFormat hex = HexFormat.of();
return hex.parseHex(s)[0];
}
public static byte[] hexStringToByteArrV1(String s) {
if (s == null || s.length() == 0) {
throw new IllegalArgumentException("The given string cannot be null or empty");
}
char[] sc = s.toCharArray();
int l = sc.length / 2;
byte[] b = new byte[l];
for (int i = 0; i < l; i++) {
int higher = Character.digit(sc[i * 2], 16);
int lower = Character.digit(sc[i * 2 + 1], 16);
int r = (higher << 4) | lower;
if (r > 127) {
r -= 256;
}
b[i] = (byte) r;
}
return b;
}
public static byte[] hexStringToByteArrV2(String s) {
if (s == null || s.length() == 0) {
throw new IllegalArgumentException("The given string cannot be null or empty");
}
HexFormat hex = HexFormat.of();
return hex.parseHex(s);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P46_AnonymousClassesAndStatics/src/main/java/modern/challenge/Printer.java | Chapter02/P46_AnonymousClassesAndStatics/src/main/java/modern/challenge/Printer.java | package modern.challenge;
public interface Printer {
public void print(String quality);
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P46_AnonymousClassesAndStatics/src/main/java/modern/challenge/Main.java | Chapter02/P46_AnonymousClassesAndStatics/src/main/java/modern/challenge/Main.java | package modern.challenge;
public class Main {
public static void main(String[] args) {
printerTest();
}
public static void printerTest() {
// before JDK 16
/*
Printer printer = new Printer() {
@Override
public void print(String quality) {
if ("best".equals(quality)) {
Tools tools = new Tools();
tools.enableLaserGuidance();
tools.setHighResolution();
}
System.out.println("Printing photo-test ...");
}
class Tools {
private void enableLaserGuidance() {
System.out.println("Adding laser guidance ...");
}
private void setHighResolution() {
System.out.println("Set high resolution ...");
}
}
};
*/
// before JDK 16
/*
Printer printer = new Printer() {
@Override
public void print(String quality) {
class Tools {
private void enableLaserGuidance() {
System.out.println("Adding laser guidance ...");
}
private void setHighResolution() {
System.out.println("Set high resolution ...");
}
}
if ("best".equals(quality)) {
Tools tools = new Tools();
tools.enableLaserGuidance();
tools.setHighResolution();
}
System.out.println("Printing photo-test ...");
}
};
*/
// JDK 16+
/*
Printer printer = new Printer() {
@Override
public void print(String quality) {
if ("best".equals(quality)) {
enableLaserGuidance();
setHighResolution();
}
System.out.println("Printing photo-test ...");
}
private static void enableLaserGuidance() {
System.out.println("Adding laser guidance ...");
}
private static void setHighResolution() {
System.out.println("Set high resolution ...");
}
};
*/
Printer printer = new Printer() {
@Override
public void print(String quality) {
if ("best".equals(quality)) {
Tools.enableLaserGuidance();
Tools.setHighResolution();
}
System.out.println("Printing photo-test ...");
}
private final static class Tools {
private static void enableLaserGuidance() {
System.out.println("Adding laser guidance ...");
}
private static void setHighResolution() {
System.out.println("Set high resolution ...");
}
}
};
printer.print("ok");
System.out.println();
printer.print("best");
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P47_ErasureGeneric/src/main/java/modern/challenge/Main.java | Chapter02/P47_ErasureGeneric/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Object> list = listOf(1, "one");
System.out.println(list);
}
public static <T, R extends T> List<T> listOf(T t, R r) {
List<T> list = new ArrayList<>();
list.add(t);
list.add(r);
return list;
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P50_ImmutableStack/src/main/java/modern/challenge/ImmutableStack.java | Chapter02/P50_ImmutableStack/src/main/java/modern/challenge/ImmutableStack.java | package modern.challenge;
import java.util.Iterator;
public class ImmutableStack<E> implements Stack<E> {
private final E head;
private final Stack<E> tail;
private ImmutableStack(final E head, final Stack<E> tail) {
this.head = head;
this.tail = tail;
}
public static <U> Stack<U> empty(final Class<U> type) {
return new EmptyStack<>();
}
@Override
public Stack<E> push(E e) {
return new ImmutableStack<>(e, this);
}
@Override
public Stack<E> pop() {
return this.tail;
}
@Override
public E peek() {
return this.head;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Iterator<E> iterator() {
return new StackIterator<>(this);
}
private static class StackIterator<U> implements Iterator<U> {
private Stack<U> stack;
public StackIterator(final Stack<U> stack) {
this.stack = stack;
}
@Override
public boolean hasNext() {
return !this.stack.isEmpty();
}
@Override
public U next() {
U e = this.stack.peek();
this.stack = this.stack.pop();
return e;
}
@Override
public void remove() {
}
}
private static class EmptyStack<U> implements Stack<U> {
@Override
public Stack<U> push(U u) {
return new ImmutableStack<>(u, this);
}
@Override
public Stack<U> pop() {
throw new UnsupportedOperationException("Unsupported operation on an empty stack");
}
@Override
public U peek() {
throw new UnsupportedOperationException ("Unsupported operation on an empty stack");
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public Iterator<U> iterator() {
return new StackIterator<>(this);
}
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P50_ImmutableStack/src/main/java/modern/challenge/Stack.java | Chapter02/P50_ImmutableStack/src/main/java/modern/challenge/Stack.java | package modern.challenge;
public interface Stack<T> extends Iterable<T> {
boolean isEmpty();
Stack<T> push(T value);
Stack<T> pop();
T peek();
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P50_ImmutableStack/src/main/java/modern/challenge/Main.java | Chapter02/P50_ImmutableStack/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
Stack<String> s1 = ImmutableStack.empty(String.class);
Stack<String> s2 = s1.push("Hello");
Stack<String> s3 = s2.push("Immutable");
Stack<String> s4 = s2.push("Stack"); // shares its tail with s3
System.out.println("S1: " + s1.isEmpty());
System.out.println("\nS2:");
Iterator<String> it2 = s2.iterator();
while (it2.hasNext()) {
System.out.println(it2.next());
}
System.out.println("\nS3:");
Iterator<String> it3 = s3.iterator();
while (it3.hasNext()) {
System.out.println(it3.next());
}
System.out.println("\nS4:");
Iterator<String> it4 = s4.iterator();
while (it4.hasNext()) {
System.out.println(it4.next());
}
// s4.pop().pop().pop(); // UnsupportedOperationException: Unsupported operation on an empty stack
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P66_CompletenessInSwitchJDK20/src/main/java/modern/challenge/Main.java | Chapter02/P66_CompletenessInSwitchJDK20/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.lang.constant.ClassDesc;
import java.lang.constant.ConstantDesc;
import java.lang.constant.DynamicConstantDesc;
import java.lang.constant.MethodHandleDesc;
import java.lang.constant.MethodTypeDesc;
import java.nio.CharBuffer;
import java.util.Arrays;
import javax.swing.text.Segment;
public class Main {
static class Vehicle {}
static class Car extends Vehicle {}
static class Van extends Vehicle {}
static class Truck extends Vehicle {} // since there is no case Truck this
// will be handle by default label or case Vehicle
private static String whatAmI(Vehicle vehicle) {
return switch(vehicle) {
case Car car -> "You're a car";
case Van van -> "You're a van";
case Vehicle v -> "You're a vehicle"; // this is a total pattern
// default -> "I have no idea ... what are you?"; // can be used instead of the total pattern
};
}
private static String whatAmI(Object o) {
return switch(o) {
case Car car -> "You're a car";
case Van van -> "You're a van";
case Vehicle v -> "You're a vehicle";
case Object obj -> "You're an object";
// default -> "I have no idea ... what are you?"; // can be used instead of the total pattern
};
}
private static String whatAmI(CharSequence cs) {
return switch(cs) {
case String str -> "You're a string";
case Segment segment -> "You're a Segment";
case CharBuffer charbuffer -> "You're a CharBuffer";
case StringBuffer strbuffer -> "You're a StringBuffer";
case StringBuilder strbuilder -> "You're a StringBuilder";
case CoolChar cool -> "Welcome ... you're a CoolChar"; // we have created this
case CharSequence charseq -> "You're a CharSequence"; // this is a total pattern
// default -> "I have no idea ... what are you?"; // can be used instead of the total pattern
};
}
private static class CoolChar implements CharSequence {
@Override public int length() { return 0; }
@Override public char charAt(int index) { return '0'; };
@Override public CharSequence subSequence(int start, int end) { return null; }
}
// ConstantDesc is sealed
private static String whatAmI(ConstantDesc constantDesc) {
return switch(constantDesc) {
case Integer i -> "You're an Integer";
case Long l -> "You're a Long";
case Float f -> " You're a Float";
case Double d -> "You're a Double";
case String s -> "You're a String";
case ClassDesc cd -> "You're a ClassDesc";
case DynamicConstantDesc dcd -> "You're a DCD";
case MethodHandleDesc mhd -> "You're a MethodHandleDesc";
case MethodTypeDesc mtd -> "You're a MethodTypeDesc";
};
}
sealed interface Player {}
final static class Tennis implements Player {}
final static class Football implements Player {}
final static class Snooker implements Player {}
// final static class Golf implements Player {} // enable this to see how the compiler warns you
// about not covering all possible cases in switch
private static String trainPlayer(Player p) {
return switch (p) {
case Tennis t -> "Training the tennis player ..." + t;
case Football f -> "Training the football player ..." + f;
case Snooker s -> "Training the snooker player ..." + s;
// case Golf g -> "Training the snooker player ..." + g;
// case Player player -> "Training some player"; // most probably you don't want to do this
// default -> "No player"; // most probably you don't want to do this
};
}
private enum PlayerTypes {
TENNIS,
FOOTBALL,
SNOOKER,
// GOLF // enable this to see how the compiler warns you
// about not covering all possible cases in switch
}
private static String createPlayer(PlayerTypes p) {
return switch (p) {
case TENNIS -> "Creating a tennis player ...";
case FOOTBALL -> "Creating a football player ...";
case SNOOKER -> "Creating a snooker player ...";
// case GOLF -> "Creating a golf player ...";
// case PlayerTypes pt -> "Creating some player"; // most probably you don't want to do this
// default -> "No player was created"; // most probably you don't want to do this
};
}
public static void main(String[] args) {
Arrays.asList(new Car(), new Van(), new Truck()).stream()
.map(Main::whatAmI)
.forEach(System.out::println);
System.out.println();
Arrays.asList(new Car(), new Van(), new Truck(), new String()).stream()
.map(Main::whatAmI)
.forEach(System.out::println);
System.out.println();
Arrays.asList(new String(), new StringBuilder(), new CoolChar()).stream()
.map(Main::whatAmI)
.forEach(System.out::println);
System.out.println();
Arrays.asList(new Football(), new Tennis(), new Snooker()).stream()
.map(Main::trainPlayer)
.forEach(System.out::println);
System.out.println();
Arrays.asList(PlayerTypes.FOOTBALL, PlayerTypes.SNOOKER, PlayerTypes.TENNIS).stream()
.map(Main::createPlayer)
.forEach(System.out::println);
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P60_RewritingEqualsTypePatternInstanceof/src/main/java/modern/challenge/MyPointGenericOld.java | Chapter02/P60_RewritingEqualsTypePatternInstanceof/src/main/java/modern/challenge/MyPointGenericOld.java | package modern.challenge;
import java.util.Objects;
public final class MyPointGenericOld<E> {
private final E x;
private final E y;
private final E z;
public MyPointGenericOld(E x, E y, E z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int hashCode() {
int hash = 5;
hash = 83 * hash + Objects.hashCode(this.x);
hash = 83 * hash + Objects.hashCode(this.y);
hash = 83 * hash + Objects.hashCode(this.z);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof MyPointGenericOld<?>)) {
return false;
}
final MyPointGenericOld<?> other = (MyPointGenericOld<?>) obj;
return (this.x == other.x && this.y == other.y && this.z == other.z);
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P60_RewritingEqualsTypePatternInstanceof/src/main/java/modern/challenge/MyPointGenericNew.java | Chapter02/P60_RewritingEqualsTypePatternInstanceof/src/main/java/modern/challenge/MyPointGenericNew.java | package modern.challenge;
import java.util.Objects;
public final class MyPointGenericNew<E> {
private final E x;
private final E y;
private final E z;
public MyPointGenericNew(E x, E y, E z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int hashCode() {
int hash = 5;
hash = 83 * hash + Objects.hashCode(this.x);
hash = 83 * hash + Objects.hashCode(this.y);
hash = 83 * hash + Objects.hashCode(this.z);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
return obj instanceof MyPointGenericNew<?> other
&& this.x == other.x && this.y == other.y && this.z == other.z;
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P60_RewritingEqualsTypePatternInstanceof/src/main/java/modern/challenge/MyPointOld.java | Chapter02/P60_RewritingEqualsTypePatternInstanceof/src/main/java/modern/challenge/MyPointOld.java | package modern.challenge;
public final class MyPointOld {
private final int x;
private final int y;
private final int z;
public MyPointOld(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int hashCode() {
int hash = 3;
hash = 73 * hash + this.x;
hash = 73 * hash + this.y;
hash = 73 * hash + this.z;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof MyPointOld)) {
return false;
}
final MyPointOld other = (MyPointOld) obj;
return (this.x == other.x && this.y == other.y && this.z == other.z);
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P60_RewritingEqualsTypePatternInstanceof/src/main/java/modern/challenge/MyPointNew.java | Chapter02/P60_RewritingEqualsTypePatternInstanceof/src/main/java/modern/challenge/MyPointNew.java | package modern.challenge;
public final class MyPointNew {
private final int x;
private final int y;
private final int z;
public MyPointNew(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int hashCode() {
int hash = 3;
hash = 73 * hash + this.x;
hash = 73 * hash + this.y;
hash = 73 * hash + this.z;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
return obj instanceof MyPointNew other
&& this.x == other.x && this.y == other.y && this.z == other.z;
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P60_RewritingEqualsTypePatternInstanceof/src/main/java/modern/challenge/Main.java | Chapter02/P60_RewritingEqualsTypePatternInstanceof/src/main/java/modern/challenge/Main.java | package modern.challenge;
public class Main {
public static void main(String[] args) {
int x1 = 2, y1 = 3, z1 = 1;
int x2 = 5, y2 = 0, z2 = 1;
Integer xg1 = Integer.valueOf(2), yg1 = Integer.valueOf(3), zg1 = Integer.valueOf(1);
Integer xg2 = Integer.valueOf(5), yg2 = Integer.valueOf(0), zg2 = Integer.valueOf(1);
MyPointOld old1 = new MyPointOld(x1, y1, z1);
MyPointOld old2 = new MyPointOld(x2, y2, z2);
MyPointOld old3 = new MyPointOld(x1, y1, z1);
MyPointNew new1 = new MyPointNew(x1, y1, z1);
MyPointNew new2 = new MyPointNew(x2, y2, z2);
MyPointNew new3 = new MyPointNew(x1, y1, z1);
MyPointGenericOld oldg1 = new MyPointGenericOld<>(xg1, yg1, zg1);
MyPointGenericOld oldg2 = new MyPointGenericOld<>(xg2, yg2, zg2);
MyPointGenericOld oldg3 = new MyPointGenericOld<>(xg1, yg1, zg1);
MyPointGenericNew newg1 = new MyPointGenericNew<>(xg1, yg1, zg1);
MyPointGenericNew newg2 = new MyPointGenericNew<>(xg2, yg2, zg2);
MyPointGenericNew newg3 = new MyPointGenericNew<>(xg1, yg1, zg1);
System.out.println("old1 equals old2: " + old1.equals(old2));
System.out.println("old1 equals old3: " + old1.equals(old3));
System.out.println("old2 equals old3: " + old2.equals(old3));
System.out.println();
System.out.println("new1 equals new2: " + new1.equals(new2));
System.out.println("new1 equals new3: " + new1.equals(new3));
System.out.println("new2 equals new3: " + new2.equals(new3));
System.out.println();
System.out.println("oldg1 equals oldg2: " + oldg1.equals(oldg2));
System.out.println("oldg1 equals oldg3: " + oldg1.equals(oldg3));
System.out.println("oldg2 equals oldg3: " + oldg2.equals(oldg3));
System.out.println();
System.out.println("newg1 equals newg2: " + newg1.equals(newg2));
System.out.println("newg1 equals newg3: " + newg1.equals(newg3));
System.out.println("newg2 equals newg3: " + newg2.equals(newg3));
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P64_GuardedPatternsSwitch1/src/main/java/modern/challenge/House.java | Chapter02/P64_GuardedPatternsSwitch1/src/main/java/modern/challenge/House.java | package modern.challenge;
class Heater {}
class Stove extends Heater {}
class Chimney extends Heater {
private final boolean electric;
public Chimney(boolean electric) {
this.electric = electric;
}
public boolean isElectric() {
return electric;
}
}
public class House {
private static String turnOnTheHeat(Heater heater) {
return switch (heater) {
case Stove stove -> "Make a fire in the stove";
case Chimney chimney when chimney.isElectric() -> "Plug in the chimney";
case Chimney chimney -> "Make a fire in the chimney";
default -> "No heater available!";
};
}
public static void main(String[] args) {
System.out.println(turnOnTheHeat(new Stove()));
System.out.println(turnOnTheHeat(new Chimney(true)));
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P67_UnconditionalPatterns/src/main/java/modern/challenge/Main.java | Chapter02/P67_UnconditionalPatterns/src/main/java/modern/challenge/Main.java | package modern.challenge;
class Vehicle {
public String start() { return "started"; }
public String stop() { return "stopped"; }
}
class Truck extends Vehicle {}
class Van extends Vehicle {}
public class Main {
private static String drive(Vehicle v) {
return switch (v) {
case Truck truck -> "truck: " + truck;
case Van van -> "van: " + van;
// case null -> "so, you don't have a vehicle?"; // we can still use a null check
case Vehicle vehicle -> "vehicle: " + vehicle.start(); // total/unconditional pattern throw NPE immediately
};
}
public static void main(String[] args) {
System.out.println(Main.drive(new Truck()));
System.out.println(Main.drive(new Van()));
System.out.println(Main.drive(null));
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/SnookerPlayer.java | Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/SnookerPlayer.java | package modern.challenge;
public class SnookerPlayer extends Player {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/FootballPlayer.java | Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/FootballPlayer.java | package modern.challenge;
public class FootballPlayer extends Player {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/Player.java | Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/Player.java | package modern.challenge;
public class Player {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/Main.java | Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/Main.java | package modern.challenge;
public class Main {
public enum PlayerTypes {
TENNIS,
FOOTBALL,
SNOOKER
}
public static void main(String[] args) {
Player player = createPlayer(PlayerTypes.SNOOKER);
}
private static Player createPlayer(PlayerTypes playerType) {
return switch (playerType) {
case TENNIS-> {
System.out.println("Creating a TennisPlayer ...");
yield new TennisPlayer();
}
case FOOTBALL-> {
System.out.println("Creating a FootballPlayer ...");
yield new FootballPlayer();
}
case SNOOKER-> {
System.out.println("Creating a SnookerPlayer ...");
yield new SnookerPlayer();
}
default->
throw new IllegalArgumentException("Invalid player type: " + playerType);
};
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/TennisPlayer.java | Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/TennisPlayer.java | package modern.challenge;
public class TennisPlayer extends Player{
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/UnknownPlayerException.java | Chapter02/P53_YieldStatementBlocks/src/main/java/modern/challenge/UnknownPlayerException.java | package modern.challenge;
public class UnknownPlayerException extends RuntimeException {
private static final long serialVersionUID = 1L;
public UnknownPlayerException() {
super();
}
public UnknownPlayerException(String message) {
super(message);
}
public UnknownPlayerException(Throwable cause) {
super(cause);
}
public UnknownPlayerException(String message, Throwable cause) {
super(message, cause);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P47_ErasureVsOverloading/src/main/java/modern/challenge/Main.java | Chapter02/P47_ErasureVsOverloading/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.util.List;
public class Main {
public static void main(String[] args) {
new Main().print(List.of(new A(), new A()));
new Main().print(List.of(new B(), new B()));
}
void print(List<A> listOfA, Void... v) {
System.out.println("Printing A: " + listOfA);
}
void print(List<B> listofB) {
System.out.println("Printing B: " + listofB);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P47_ErasureVsOverloading/src/main/java/modern/challenge/A.java | Chapter02/P47_ErasureVsOverloading/src/main/java/modern/challenge/A.java | package modern.challenge;
public class A {}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P47_ErasureVsOverloading/src/main/java/modern/challenge/B.java | Chapter02/P47_ErasureVsOverloading/src/main/java/modern/challenge/B.java | package modern.challenge;
public class B {}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P47_PolymorphicOverloading/src/main/java/modern/challenge/Main.java | Chapter02/P47_PolymorphicOverloading/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.File;
public class Main {
static String wordie = "";
public static void main(String[] args) {
kaboom(1); // c
kaboom(1, 2, 3); // q
kaboom(1d); // f
kaboom((short) 1); // b
kaboom(1L); // d
kaboom(Double.valueOf("1")); // l
kaboom(true); // m
// kaboom() // reference to kaboom is ambiguous
kaboom(1L, true); // o
kaboom(new int[]{1,2,3}, 1); // o
System.out.println("Wordie:"+wordie); // cqfbdlmoo
}
static void kaboom(byte b) { wordie += "a";}
static void kaboom(short s) { wordie += "b";}
static void kaboom(int i) { wordie += "c";}
static void kaboom(long l) { wordie += "d";}
static void kaboom(float f) { wordie += "e";}
static void kaboom(double d) { wordie += "f";}
static void kaboom(Byte b) { wordie += "g";}
static void kaboom(Short s) { wordie += "h";}
static void kaboom(Integer i) { wordie += "i";}
static void kaboom(Long l) { wordie += "j";}
static void kaboom(Float f) { wordie += "k";}
static void kaboom(Double d) { wordie += "l";}
static void kaboom(boolean o) { wordie += "m";}
static void kaboom(Object o) { wordie += "n";}
static void kaboom(Object... ov) { wordie += "o";}
static void kaboom(Number n) { wordie += "p";}
static void kaboom(Number... nv) { wordie += "q";}
static void kaboom(File f) { wordie += "r";}
static void kaboom(File... fv) { wordie += "s";}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P42_SnippetsInJavadocPreJDK18/src/main/java/modern/challenge/Telemeter.java | Chapter02/P42_SnippetsInJavadocPreJDK18/src/main/java/modern/challenge/Telemeter.java | package modern.challenge;
import java.awt.Point;
/**
* A telemeter with laser ranging from 0 to 60 ft including calculation of
* surfaces and volumes with high-precision
*
* <pre>{@code
* Telemeter.Calibrate.at(0.00001);
* Telemeter telemeter = new Telemeter(0.15, 2, "IP54");
* }</pre>
*/
public class Telemeter {
private final double precision;
private final int clazz;
private final String protection;
/**
* Telemeter constructor
*
* @param precision telemeter precision (for instance, 0.15 millimeters)
* @param clazz telemeter class (for instance, 1 or 2)
* @param protection telemeter protection (for instance, IP54)
*/
public Telemeter(double precision, int clazz, String protection) {
this.precision = precision;
this.clazz = clazz;
this.protection = protection;
}
/**
* Method for calculating the distance between two points
*
* @param sc from this point
* @param ec to this point
* @param interpolation use interpolation or not
* @return the computed distance as integer
*
* <p><b>Example:</b></p>
* <pre>{@code
* Point sp = new Point(12, 56);
* Point ep = new Point(43, 45);
*
* int d = telementer.distance(sp, ep, true);
* }</pre>
*/
public int distance(Point sc, Point ec, boolean interpolation) {
return 0;
}
/**
* Class used to calibrate the telemeter
*/
public static final class Calibrate {
/**
* Cannot be instantiated
*/
private Calibrate() {
throw new AssertionError("Cannot be instantiated");
}
/**
* Method used for calibrating the telemeter to the given epsilon
* (for instance, eps = 0.00001)
*
* @param eps the telemeter is calibrated to this precision
* @param type the type of calibration
* @return true, if calibration was done with success
*
* <p>
* {@code Telemeter.Calibrate.at(0.00001);}
* </p>
*
* PERFORM THE CALIBRATION BEFORE CREATING AN INSTANCE OF THIS CLASS
*/
public static boolean at(double eps, String type) {
return true;
}
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P42_SnippetsInJavadocPreJDK18/src/main/java/modern/challenge/Main.java | Chapter02/P42_SnippetsInJavadocPreJDK18/src/main/java/modern/challenge/Main.java | package modern.challenge;
/**
*
* Main class
*
* <pre>{@code
* Telemeter.Calibrate.at(0.00001, "HIGH");
*
* Point sp = new Point(12, 56);
* Point ep = new Point(43, 45);
*
* Telemeter telemeter = new Telemeter(0.15, 2, "IP54");
*
* int d = telemeter.distance(sp, ep, true);
* }</pre>
*/
public class Main {
/**
* Default constructor
*/
public Main() {}
/**
* The main() method
*
* @param args command line arguments
*/
public static void main(String[] args) {
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P41_UnamedClassesMain/src/main/java/HelloWorld.java | Chapter02/P41_UnamedClassesMain/src/main/java/HelloWorld.java | void main() {
System.out.println("Hello World!");
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P58_TypePatternMatchingInstanceof/src/main/java/modern/challenge/Usb.java | Chapter02/P58_TypePatternMatchingInstanceof/src/main/java/modern/challenge/Usb.java | package modern.challenge;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Usb {
public static String saveOld(Object o) throws IOException {
if (o instanceof File) {
File file = (File) o;
return "Saving a file of size: " + String.format("%,d bytes", file.length());
}
if (o instanceof Path) {
Path path = (Path) o;
return "Saving a file of size: " + String.format("%,d bytes", Files.size(path));
}
if (o instanceof String) {
String str = (String) o;
return "Saving a string of size: " + String.format("%,d bytes", str.length());
}
return "I cannot save the given object";
}
public static String save(Object o) throws IOException {
if (o instanceof File file) {
return "Saving a file of size: " + String.format("%,d bytes", file.length());
}
if (o instanceof String str) {
return "Saving a string of size: " + String.format("%,d bytes", str.length());
}
if (o instanceof Path path) {
return "Saving a file of size: " + String.format("%,d bytes", Files.size(path));
}
return "I cannot save the given object";
}
public static void main(String[] args) throws IOException {
System.out.println(saveOld(Paths.get("pom.xml")));
System.out.println(saveOld(new File("pom.xml")));
System.out.println(saveOld("This is a plain string"));
System.out.println();
System.out.println(save(Paths.get("pom.xml")));
System.out.println(save(new File("pom.xml")));
System.out.println(save("This is a plain string"));
System.out.println();
// JDK 20 -> expression type cannot be a subtype of pattern type (upcasting is allowed)
// JDK 21 -> this works
if ("foo" instanceof String str) {System.out.println(str);}
if ("foo" instanceof CharSequence sequence) {System.out.println(sequence);}
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/SnookerPlayer.java | Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/SnookerPlayer.java | package modern.challenge;
public class SnookerPlayer extends Player {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/FootballPlayer.java | Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/FootballPlayer.java | package modern.challenge;
public class FootballPlayer extends Player {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/Player.java | Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/Player.java | package modern.challenge;
public class Player {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/Main.java | Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/Main.java | package modern.challenge;
public class Main {
public enum PlayerTypes {
TENNIS,
FOOTBALL,
SNOOKER,
UNKNOWN
}
public static void main(String[] args) {
createPlayerNoNullCheck(PlayerTypes.TENNIS);
createPlayerNoNullCheck(null);
createPlayerNullCheck(PlayerTypes.TENNIS);
createPlayerNullCheck(null);
createPlayerNullCase(PlayerTypes.TENNIS);
createPlayerNullCase(null);
createPlayerNullAndDefaultCase(PlayerTypes.TENNIS);
createPlayerNullAndDefaultCase(null);
}
private static Player createPlayerNoNullCheck(PlayerTypes playerType) {
return switch (playerType) {
case TENNIS ->
new TennisPlayer();
case FOOTBALL ->
new FootballPlayer();
case SNOOKER ->
new SnookerPlayer();
case UNKNOWN ->
throw new UnknownPlayerException("Player type is unknown");
// default is not mandatory
default ->
throw new IllegalArgumentException("Invalid player type: " + playerType);
};
}
private static Player createPlayerNoNullCheckYield(PlayerTypes playerType) {
return switch (playerType) {
case TENNIS:
yield new TennisPlayer();
case FOOTBALL:
yield new FootballPlayer();
case SNOOKER:
yield new SnookerPlayer();
case UNKNOWN:
throw new UnknownPlayerException("Player type is unknown");
// default is not mandatory
default:
throw new IllegalArgumentException("Invalid player type: " + playerType);
};
}
private static Player createPlayerNullCheck(PlayerTypes playerType) {
// handling null values in a condition outside switch
if (playerType == null) {
throw new IllegalArgumentException("Player type cannot be null");
}
return switch (playerType) {
case TENNIS ->
new TennisPlayer();
case FOOTBALL ->
new FootballPlayer();
case SNOOKER ->
new SnookerPlayer();
case UNKNOWN ->
throw new UnknownPlayerException("Player type is unknown");
// default is not mandatory
default ->
throw new IllegalArgumentException("Invalid player type: " + playerType);
};
}
private static Player createPlayerNullCheckYield(PlayerTypes playerType) {
// handling null values in a condition outside switch
if (playerType == null) {
throw new IllegalArgumentException("Player type cannot be null");
}
return switch (playerType) {
case TENNIS:
yield new TennisPlayer();
case FOOTBALL:
yield new FootballPlayer();
case SNOOKER:
yield new SnookerPlayer();
case UNKNOWN:
throw new UnknownPlayerException("Player type is unknown");
// default is not mandatory
default:
throw new IllegalArgumentException("Invalid player type: " + playerType);
};
}
private static Player createPlayerNullCase(PlayerTypes playerType) {
return switch (playerType) {
case TENNIS ->
new TennisPlayer();
case FOOTBALL ->
new FootballPlayer();
case SNOOKER ->
new SnookerPlayer();
case null ->
throw new NullPointerException("Player type cannot be null");
case UNKNOWN ->
throw new UnknownPlayerException("Player type is unknown");
// default is not mandatory
default ->
throw new IllegalArgumentException("Invalid player type: " + playerType);
};
}
private static Player createPlayerNullCaseYield(PlayerTypes playerType) {
return switch (playerType) {
case TENNIS:
yield new TennisPlayer();
case FOOTBALL:
yield new FootballPlayer();
case SNOOKER:
yield new SnookerPlayer();
case null:
throw new NullPointerException("Player type cannot be null");
case UNKNOWN:
throw new UnknownPlayerException("Player type is unknown");
// default is not mandatory
default:
throw new IllegalArgumentException("Invalid player type: " + playerType);
};
}
private static Player createPlayerNullAndDefaultCase(PlayerTypes playerType) {
return switch (playerType) {
case TENNIS ->
new TennisPlayer();
case FOOTBALL ->
new FootballPlayer();
case SNOOKER ->
new SnookerPlayer();
// default is not mandatory
case null, default ->
throw new IllegalArgumentException("Invalid player type: " + playerType);
};
}
private static Player createPlayerNullAndDefaultCaseYield(PlayerTypes playerType) {
return switch (playerType) {
case TENNIS:
yield new TennisPlayer();
case FOOTBALL:
yield new FootballPlayer();
case SNOOKER:
yield new SnookerPlayer();
// default is not mandatory
case null, default:
throw new IllegalArgumentException("Invalid player type: " + playerType);
};
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/TennisPlayer.java | Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/TennisPlayer.java | package modern.challenge;
public class TennisPlayer extends Player{
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/UnknownPlayerException.java | Chapter02/P54_CaseNullClauseInSwitch/src/main/java/modern/challenge/UnknownPlayerException.java | package modern.challenge;
public class UnknownPlayerException extends RuntimeException {
private static final long serialVersionUID = 1L;
public UnknownPlayerException() {
super();
}
public UnknownPlayerException(String message) {
super(message);
}
public UnknownPlayerException(Throwable cause) {
super(cause);
}
public UnknownPlayerException(String message, Throwable cause) {
super(message, cause);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P61_TypePatternInstanceofGenerics/src/main/java/modern/challenge/Main.java | Chapter02/P61_TypePatternInstanceofGenerics/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.util.EnumMap;
import java.util.Map;
public class Main {
enum Status {
DRAFT, READY
}
static class Book {
public void review() { System.out.println("reviewing ..."); };
public void print() { System.out.println("printing ..."); };
}
public static <K, V> void processOld(Map<K, ? extends V> map) {
if (map instanceof EnumMap<?, ? extends V>) {
EnumMap<?, ? extends V> books = (EnumMap<?, ? extends V>) map;
if (books.get(Status.DRAFT) instanceof Book) {
Book book = (Book) books.get(Status.DRAFT);
book.review();
}
}
}
public static <K, V> void processNew(Map<K, ? extends V> map) {
if (map instanceof EnumMap<?, ? extends V> books
&& books.get(Status.DRAFT) instanceof Book book) {
book.review();
}
}
public static void main(String[] args) {
EnumMap<Status, Book> books = new EnumMap<>(Status.class);
books.put(Status.DRAFT, new Book());
books.put(Status.READY, new Book());
processOld(books);
processNew(books);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK8/src/main/java/modern/challenge/Book.java | Chapter02/P43_InvokeDefaultMethodsJDK8/src/main/java/modern/challenge/Book.java | package modern.challenge;
public interface Book extends Printable {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK8/src/main/java/modern/challenge/Draft.java | Chapter02/P43_InvokeDefaultMethodsJDK8/src/main/java/modern/challenge/Draft.java | package modern.challenge;
public interface Draft extends Writable {
@Override
default void write(String draft) {
System.out.println("Draft: Writing in draft: " + draft);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK8/src/main/java/modern/challenge/Main.java | Chapter02/P43_InvokeDefaultMethodsJDK8/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
// invoke Printable.print(String doc)
System.out.println("Invoke Printable.print(String doc):");
Printable pproxy = (Printable) Proxy.newProxyInstance(
Printable.class.getClassLoader(),
new Class<?>[]{Printable.class}, (o, m, p) -> {
if (m.isDefault()) {
Constructor<Lookup> cntr = Lookup.class
.getDeclaredConstructor(Class.class);
cntr.setAccessible(true);
return cntr.newInstance(Printable.class)
.in(Printable.class)
.unreflectSpecial(m, Printable.class)
.bindTo(o)
.invokeWithArguments(p);
}
return null;
});
pproxy.print("Chapter 2");
// invoke Writable.write(String doc)
System.out.println("\nInvoke Writable.write(String doc):");
Writable wproxy = (Writable) Proxy.newProxyInstance(
Writable.class.getClassLoader(),
new Class<?>[]{Writable.class}, (o, m, p) -> {
if (m.isDefault()) {
Constructor<Lookup> cntr = Lookup.class
.getDeclaredConstructor(Class.class);
cntr.setAccessible(true);
return cntr.newInstance(Writable.class)
.in(Writable.class)
.unreflectSpecial(m, Writable.class)
.bindTo(o)
.invokeWithArguments(p);
}
return null;
});
wproxy.write("Chapter 5");
// invoke Draft.write(String doc)
System.out.println("\nInvoke Draft.write(String doc):");
Draft wdproxy = (Draft) Proxy.newProxyInstance(
Draft.class.getClassLoader(),
new Class<?>[]{Draft.class}, (o, m, p) -> {
if (m.isDefault()) {
Constructor<Lookup> cntr = Lookup.class
.getDeclaredConstructor(Class.class);
cntr.setAccessible(true);
return cntr.newInstance(Draft.class)
.in(Draft.class)
.unreflectSpecial(m, Draft.class)
.bindTo(o)
.invokeWithArguments(p);
}
return null;
});
wdproxy.write("Chapter 13");
// invoke Draft.write(String doc) and Writable.write(String doc)
System.out.println("\nInvoke Draft.write(String doc) and Writable.write(String doc):");
Writable dpproxy = (Writable) Proxy.newProxyInstance(
Writable.class.getClassLoader(),
new Class<?>[]{Writable.class, Draft.class}, (o, m, p) -> {
if (m.isDefault() && m.getName().equals("write")) {
Constructor<Lookup> cntr = Lookup.class
.getDeclaredConstructor(Class.class);
cntr.setAccessible(true);
cntr.newInstance(Draft.class)
.in(Draft.class)
.findSpecial(Draft.class, "write",
MethodType.methodType(void.class, String.class), Draft.class)
.bindTo(o)
.invokeWithArguments(p);
return cntr.newInstance(Writable.class)
.in(Writable.class)
.findSpecial(Writable.class, "write",
MethodType.methodType(void.class, String.class), Writable.class)
.bindTo(o)
.invokeWithArguments(p);
}
return null;
});
dpproxy.write("Chapter 1");
// invoke Book.print(String doc)
System.out.println("\nInvoke Book.print(String doc):");
Book bpproxy = (Book) Proxy.newProxyInstance(
Book.class.getClassLoader(),
new Class<?>[]{Book.class}, (o, m, p) -> {
if (m.isDefault()) {
Constructor<Lookup> cntr = Lookup.class
.getDeclaredConstructor(Class.class);
cntr.setAccessible(true);
return cntr.newInstance(Book.class)
.in(Book.class)
.unreflectSpecial(m, Book.class)
.bindTo(o)
.invokeWithArguments(p);
}
return null;
});
bpproxy.print("Chapter 7");
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK8/src/main/java/modern/challenge/Printable.java | Chapter02/P43_InvokeDefaultMethodsJDK8/src/main/java/modern/challenge/Printable.java | package modern.challenge;
public interface Printable {
default void setup() {
System.out.println("Printable: Setup the printer");
}
default void print(String doc) {
System.out.println("Printable: Printing the document: " + doc);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK8/src/main/java/modern/challenge/Writable.java | Chapter02/P43_InvokeDefaultMethodsJDK8/src/main/java/modern/challenge/Writable.java | package modern.challenge;
public interface Writable {
default void setup() {
System.out.println("Writable: Setup the editor");
}
default void write(String doc) {
System.out.println("Writable: Writing in document: " + doc);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P62_TypePatternInstanceofStream/src/main/java/modern/challenge/Main.java | Chapter02/P62_TypePatternInstanceofStream/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
interface Engine {}
class HypersonicEngine implements Engine {} // not implemented
class HighSpeedEngine implements Engine {} // not implemented
class RegularEngine implements Engine {
private final int maxSpeed;
private final boolean electric;
public RegularEngine(int maxSpeed, boolean electric) {
this.maxSpeed = maxSpeed;
this.electric = electric;
}
public int getMaxSpeed() {
return maxSpeed;
}
public boolean isElectric() {
return electric;
}
@Override
public String toString() {
return "RegularEngine{" + "maxSpeed=" + maxSpeed + ", electric=" + electric + '}';
}
}
public class Main {
private static List<Engine> filterRegularEngines(List<Engine> engines, int testSpeed) {
for (Iterator<Engine> i = engines.iterator(); i.hasNext();) {
final Engine e = i.next();
if (e instanceof RegularEngine) {
final RegularEngine popularEngine = (RegularEngine) e;
if (popularEngine.isElectric()) {
if (!hasEnoughAutonomy(popularEngine, testSpeed)) {
i.remove();
}
}
}
}
return engines;
}
private static List<Engine> filterRegularEnginesStream(List<Engine> engines, int testSpeed) {
engines.removeIf(e -> e instanceof RegularEngine engine
&& engine.isElectric()
&& !hasEnoughAutonomy(engine, testSpeed));
return engines;
}
private static boolean hasEnoughAutonomy(Engine engine, int testSpeed) {
return Math.random() > 0.5;
}
public static void main(String[] args) {
List<Engine> engines = new ArrayList<>();
engines.add(new RegularEngine(210, true));
engines.add(new RegularEngine(190, true));
engines.add(new RegularEngine(200, false));
engines.add(new RegularEngine(150, false));
engines.add(new RegularEngine(150, true));
engines.add(new RegularEngine(210, false));
System.out.println("Inital list: " + engines);
System.out.println();
// System.out.println("After filter: " + filterRegularEngines(engines, 180));
System.out.println("After filter (stream): " + filterRegularEnginesStream(engines, 180));
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK9/src/main/java/modern/challenge/Book.java | Chapter02/P43_InvokeDefaultMethodsJDK9/src/main/java/modern/challenge/Book.java | package modern.challenge;
public interface Book extends Printable {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK9/src/main/java/modern/challenge/Draft.java | Chapter02/P43_InvokeDefaultMethodsJDK9/src/main/java/modern/challenge/Draft.java | package modern.challenge;
public interface Draft extends Writable {
@Override
default void write(String draft) {
System.out.println("Draft: Writing in draft: " + draft);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK9/src/main/java/modern/challenge/Main.java | Chapter02/P43_InvokeDefaultMethodsJDK9/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
// invoke Printable.print(String doc)
System.out.println("Invoke Printable.print(String doc):");
Printable pproxy = (Printable) Proxy.newProxyInstance(
Printable.class.getClassLoader(),
new Class<?>[]{Printable.class}, (o, m, p) -> {
if (m.isDefault()) {
return MethodHandles.lookup().findSpecial(Printable.class, "print",
MethodType.methodType(void.class, String.class), Printable.class)
.bindTo(o)
.invokeWithArguments(p);
}
return null;
});
pproxy.print("Chapter 2");
// invoke Writable.write(String doc)
System.out.println("\nInvoke Writable.write(String doc):");
Writable wproxy = (Writable) Proxy.newProxyInstance(
Writable.class.getClassLoader(),
new Class<?>[]{Writable.class}, (o, m, p) -> {
if (m.isDefault()) {
return MethodHandles.lookup().findSpecial(Writable.class, "write",
MethodType.methodType(void.class, String.class), Writable.class)
.bindTo(o)
.invokeWithArguments(p);
}
return null;
});
wproxy.write("Chapter 5");
// invoke Draft.write(String doc)
System.out.println("\nInvoke Draft.write(String doc):");
Draft wdproxy = (Draft) Proxy.newProxyInstance(
Draft.class.getClassLoader(),
new Class<?>[]{Draft.class}, (o, m, p) -> {
if (m.isDefault()) {
return MethodHandles.lookup().findSpecial(Draft.class, "write",
MethodType.methodType(void.class, String.class), Draft.class)
.bindTo(o)
.invokeWithArguments(p);
}
return null;
});
wdproxy.write("Chapter 13");
// invoke Draft.write(String doc) and Writable.write(String doc)
System.out.println("\nInvoke Draft.write(String doc) and Writable.write(String doc):");
Writable dpproxy = (Writable) Proxy.newProxyInstance(
Writable.class.getClassLoader(),
new Class<?>[]{Writable.class, Draft.class}, (o, m, p) -> {
if (m.isDefault() && m.getName().equals("write")) {
MethodHandles.lookup().findSpecial(Draft.class, m.getName(),
MethodType.methodType(void.class, m.getParameterTypes()), Draft.class)
.bindTo(o)
.invokeWithArguments(p);
return MethodHandles.lookup().findSpecial(Writable.class, m.getName(),
MethodType.methodType(void.class, m.getParameterTypes()), Writable.class)
.bindTo(o)
.invokeWithArguments(p);
}
return null;
});
dpproxy.write("Chapter 1");
// invoke Book.print(String doc)
System.out.println("\nInvoke Book.print(String doc):");
Book bpproxy = (Book) Proxy.newProxyInstance(
Book.class.getClassLoader(),
new Class<?>[]{Book.class}, (o, m, p) -> {
if (m.isDefault()) {
return MethodHandles.lookup().findSpecial(Book.class, "print",
MethodType.methodType(void.class, String.class), Book.class)
.bindTo(o)
.invokeWithArguments(p);
}
return null;
});
bpproxy.print("Chapter 7");
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK9/src/main/java/modern/challenge/Printable.java | Chapter02/P43_InvokeDefaultMethodsJDK9/src/main/java/modern/challenge/Printable.java | package modern.challenge;
public interface Printable {
default void setup() {
System.out.println("Printable: Setup the printer");
}
default void print(String doc) {
System.out.println("Printable: Printing the document: " + doc);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK9/src/main/java/modern/challenge/Writable.java | Chapter02/P43_InvokeDefaultMethodsJDK9/src/main/java/modern/challenge/Writable.java | package modern.challenge;
public interface Writable {
default void setup() {
System.out.println("Writable: Setup the editor");
}
default void write(String doc) {
System.out.println("Writable: Writing in document: " + doc);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P42_SnippetsInJavadoc/src/main/java/modern/challenge/Telemeter.java | Chapter02/P42_SnippetsInJavadoc/src/main/java/modern/challenge/Telemeter.java | package modern.challenge;
import java.awt.Point;
/**
* A telemeter with laser ranging from 0 to 60 ft including calculation of
* surfaces and volumes with high-precision
*
* {@snippet lang="java" :
* Telemeter.Calibrate.at(0.00001); // @link substring="Calibrate" target="Calibrate#at(double, String)"
* Telemeter telemeter = new Telemeter(
* #{telemeter.precision},
* #{telemeter.clazz},
* "IP54" // @highlight regex='".*"'
* );
* }
*
* {@snippet lang="properties" :
* telemeter.precision.default=42
* telemeter.clazz.default=2
* }
*/
public class Telemeter {
private final double precision;
private final int clazz;
private final String protection;
/**
* Telemeter constructor
*
* @param precision telemeter precision (for instance, 0.15 millimeters)
* @param clazz telemeter class (for instance, 1 or 2)
* @param protection telemeter protection (for instance, IP54)
*/
public Telemeter(double precision, int clazz, String protection) {
this.precision = precision;
this.clazz = clazz;
this.protection = protection;
}
/**
* Method for calculating the distance between two points
*
* @param sc from this point
* @param ec to this point
* @param interpolation use interpolation or not
* @return the computed distance as integer
*
* <p><b>Example:</b></p>
* {@snippet class = "DistanceSnippet"}
*
* <p><b>Defaults:</b></p>
* {@snippet file = ParamDefaultSnippet.properties region=dist}
*/
public int distance(Point sc, Point ec, boolean interpolation) {
return 0;
}
/**
* Class used to calibrate the telemeter
*/
public static final class Calibrate {
/**
* Cannot be instantiated
*/
private Calibrate() {
throw new AssertionError("Cannot be instantiated");
}
/**
* Method used for calibrating the telemeter to the given epsilon
* (for instance, eps = 0.00001)
*
* @param eps the telemeter is calibrated to this precision
* @param type the type of calibration
* @return true, if calibration was done with success
*
* <p><b>Example:</b></p>
* {@snippet file = AtSnippet.txt region=only-code}
*
* <p><b>Defaults:</b></p>
* {@snippet file = ParamDefaultSnippet.properties region=at}
*
* PERFORM THE CALIBRATION BEFORE CREATING AN INSTANCE OF THIS CLASS
*/
public static boolean at(double eps, String type) {
return true;
}
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P42_SnippetsInJavadoc/src/main/java/modern/challenge/Main.java | Chapter02/P42_SnippetsInJavadoc/src/main/java/modern/challenge/Main.java | package modern.challenge;
/**
*
* Main class
*
* {@snippet file = MainSnippet.txt region=sample}
*/
public class Main {
/**
* Default constructor
*/
public Main() {}
/**
* The main() method
*
* @param args command line arguments
*/
public static void main(String[] args) {
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P42_SnippetsInJavadoc/src/snippet-src/DistanceSnippet.java | Chapter02/P42_SnippetsInJavadoc/src/snippet-src/DistanceSnippet.java | Point sp = new Point(12, 56);
Point ep = new Point(43, 45);
int d = telementer.distance(sp, ep, true); | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK16/src/main/java/modern/challenge/Book.java | Chapter02/P43_InvokeDefaultMethodsJDK16/src/main/java/modern/challenge/Book.java | package modern.challenge;
public interface Book extends Printable {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK16/src/main/java/modern/challenge/Draft.java | Chapter02/P43_InvokeDefaultMethodsJDK16/src/main/java/modern/challenge/Draft.java | package modern.challenge;
public interface Draft extends Writable {
@Override
default void write(String draft) {
System.out.println("Draft: Writing in draft: " + draft);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK16/src/main/java/modern/challenge/Main.java | Chapter02/P43_InvokeDefaultMethodsJDK16/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
// invoke Printable.print(String doc)
System.out.println("Invoke Printable.print(String doc):");
Printable pproxy = (Printable) Proxy.newProxyInstance(
Printable.class.getClassLoader(),
new Class<?>[]{Printable.class}, (o, m, p) -> {
if (m.isDefault()) {
return InvocationHandler.invokeDefault(o, m, p);
}
return null;
});
pproxy.print("Chapter 2");
// invoke Writable.write(String doc)
System.out.println("\nInvoke Writable.write(String doc):");
Writable wproxy = (Writable) Proxy.newProxyInstance(
Writable.class.getClassLoader(),
new Class<?>[]{Writable.class}, (o, m, p) -> {
if (m.isDefault()) {
return InvocationHandler.invokeDefault(o, m, p);
}
return null;
});
wproxy.write("Chapter 5");
// invoke Draft.write(String doc)
System.out.println("\nInvoke Draft.write(String doc):");
Draft wdproxy = (Draft) Proxy.newProxyInstance(
Draft.class.getClassLoader(),
new Class<?>[]{Draft.class}, (o, m, p) -> {
if (m.isDefault()) {
return InvocationHandler.invokeDefault(o, m, p);
}
return null;
});
wdproxy.write("Chapter 13");
// invoke Draft.write(String doc) and Writable.write(String doc)
System.out.println("\nInvoke Draft.write(String doc) and Writable.write(String doc):");
Writable dpproxy = (Writable) Proxy.newProxyInstance(
Writable.class.getClassLoader(),
new Class<?>[]{Writable.class, Draft.class}, (o, m, p) -> {
if (m.isDefault() && m.getName().equals("write")) {
Method writeInDraft = Draft.class.getMethod(m.getName(), m.getParameterTypes());
InvocationHandler.invokeDefault(o, writeInDraft, p);
return InvocationHandler.invokeDefault(o, m, p);
}
return null;
});
dpproxy.write("Chapter 1");
// invoke Book.print(String doc)
System.out.println("\nInvoke Book.print(String doc):");
Book bpproxy = (Book) Proxy.newProxyInstance(
Book.class.getClassLoader(),
new Class<?>[]{Book.class}, (o, m, p) -> {
if (m.isDefault()) {
return InvocationHandler.invokeDefault(o, m, p);
}
return null;
});
bpproxy.print("Chapter 7");
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK16/src/main/java/modern/challenge/Printable.java | Chapter02/P43_InvokeDefaultMethodsJDK16/src/main/java/modern/challenge/Printable.java | package modern.challenge;
public interface Printable {
default void setup() {
System.out.println("Printable: Setup the printer");
}
default void print(String doc) {
System.out.println("Printable: Printing the document: " + doc);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P43_InvokeDefaultMethodsJDK16/src/main/java/modern/challenge/Writable.java | Chapter02/P43_InvokeDefaultMethodsJDK16/src/main/java/modern/challenge/Writable.java | package modern.challenge;
public interface Writable {
default void setup() {
System.out.println("Writable: Setup the editor");
}
default void write(String doc) {
System.out.println("Writable: Writing in document: " + doc);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P38_AsciiVsUnicode/src/main/java/modern/challenge/Charsets.java | Chapter02/P38_AsciiVsUnicode/src/main/java/modern/challenge/Charsets.java | package modern.challenge;
import java.util.stream.Collectors;
public class Charsets {
private Charsets() {
throw new AssertionError("Cannot be instantiated");
}
public static String strToBinary(String str) {
if (str == null) {
throw new IllegalArgumentException("The given string cannot be null");
}
String binary = str.chars()
.mapToObj(Integer::toBinaryString)
.map(t -> "0" + t)
.collect(Collectors.joining(" "));
return binary;
}
public static String codePointToBinary(String str) {
if (str == null) {
throw new IllegalArgumentException("The given string cannot be null");
}
String binary = str.codePoints()
.mapToObj(Integer::toBinaryString)
.collect(Collectors.joining(" "));
return binary;
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P38_AsciiVsUnicode/src/main/java/modern/challenge/Main.java | Chapter02/P38_AsciiVsUnicode/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
public class Main {
public static final String LETTER = "A";
public static final String CHINESE = "暗";
public static final String EMOJI = "😍";
public static final String STR = "😍 I love 💕 you Ӝ so much 💕 😍 🎼🎼🎼!";
public static void main(String[] args) throws IOException {
System.out.println("""
////////////////////////////////////////////////////////////////////////
// For Unicode characters having code point less than 65,535 (0xFFFF) //
////////////////////////////////////////////////////////////////////////
""");
int cp1 = LETTER.charAt(0);
String hcp1 = Integer.toHexString(cp1);
String bcp1 = Integer.toBinaryString(cp1);
System.out.println("LETTER, Decimal code point: " + cp1);
System.out.println("LETTER, Hexadecimal code point: " + hcp1);
System.out.println("LETTER, Binary encoding: " + bcp1);
System.out.println();
int cp2 = CHINESE.charAt(0);
String hcp2 = Integer.toHexString(cp2);
String bcp2 = Integer.toBinaryString(cp2);
System.out.println("CHINESE, Decimal code point: " + cp2);
System.out.println("CHINESE, Hexadecimal code point: " + hcp2);
System.out.println("CHINESE, Binary encoding: " + bcp2);
System.out.println();
// this return a wrong result because the code point of 😍 is 128525 > 65535
int cp3 = EMOJI.charAt(0);
String hcp3 = Integer.toHexString(cp3);
String bcp3 = Integer.toBinaryString(cp3);
System.out.println("EMOJI, Wrong decimal code point: " + cp3);
System.out.println("EMOJI, Wrong hexadecimal code point: " + hcp3);
System.out.println("EMOJI, Wrong binary encoding: " + bcp3);
System.out.println();
String result1 = Charsets.strToBinary("Hello World");
System.out.println("Binary 'Hello World':" + result1);
String result2 = Charsets.strToBinary(LETTER);
System.out.println("LETTER, Binary:" + result2);
String result3 = Charsets.strToBinary(CHINESE);
System.out.println("CHINESE, Binary:" + result3);
// this return a wrong result because the code point of 😍 is 128525 > 65535
String result4 = Charsets.strToBinary(EMOJI);
System.out.println("EMOJI, Binary:" + result4);
System.out.println();
System.out.println("""
/////////////////////////////////
// For all Unicode characters //
/////////////////////////////////
""");
int ucp1 = LETTER.codePointAt(0);
String uhcp1 = Integer.toHexString(ucp1);
String ubcp1 = Integer.toBinaryString(ucp1);
System.out.println("LETTER, Decimal code point: " + ucp1);
System.out.println("LETTER, Hexadecimal code point: " + uhcp1);
System.out.println("LETTER, Binary encoding: " + ubcp1);
System.out.println();
int ucp2 = CHINESE.codePointAt(0);
String uhcp2 = Integer.toHexString(ucp2);
String ubcp2 = Integer.toBinaryString(ucp2);
System.out.println("CHINESE, Decimal code point: " + ucp2);
System.out.println("CHINESE, Hexadecimal code point: " + uhcp2);
System.out.println("CHINESE, Binary encoding: " + ubcp2);
System.out.println();
int a1 = LETTER.charAt(0);
int a2 = LETTER.codePointAt(0);
System.out.println("'a1', code point via charAt():" + a1);
System.out.println("'a2', code point codePointAt():" + a2);
int b1 = CHINESE.charAt(0);
int b2 = CHINESE.codePointAt(0);
System.out.println("'b1', code point via charAt():" + b1);
System.out.println("'b2', code point codePointAt():" + b2);
int c1 = EMOJI.charAt(0);
int c2 = EMOJI.codePointAt(0);
System.out.println("'c1', code point via charAt():" + c1);
System.out.println("'c2', code point codePointAt():" + c2);
System.out.println();
int ucp3 = EMOJI.codePointAt(0);
String uhcp3 = Integer.toHexString(ucp3);
String ubcp3 = Integer.toBinaryString(ucp3);
System.out.println("Is EMOJI ?: " + Character.isEmoji(ucp3)); // JDK 21
System.out.println("EMOJI, Decimal code point: " + ucp3);
System.out.println("EMOJI, Hexadecimal code point: " + uhcp3);
System.out.println("EMOJI, Binary encoding: " + ubcp3);
System.out.println();
String result5 = Charsets.codePointToBinary("Hello World");
System.out.println("Binary 'Hello World':" + result5);
String result6 = Charsets.codePointToBinary(LETTER);
System.out.println("LETTER, Binary:" + result6);
String result7 = Charsets.codePointToBinary(CHINESE);
System.out.println("CHINESE, Binary:" + result7);
String result8 = Charsets.codePointToBinary(EMOJI);
System.out.println("EMOJI, Binary:" + result8);
String result9 = Charsets.codePointToBinary(STR);
System.out.println("Binary of a combined string:" + result9);
System.out.println();
String str1 = String.valueOf(Character.toChars(65));
System.out.println("Get the string from code point 65: " + str1 + " Length:" + str1.length());
String str2 = String.valueOf(Character.toChars(128525));
System.out.println("Get the string from code point 128525: " + str2 + " Length:" + str2.length());
int cp = Character.codePointOf("Smiling Face with Heart-Shaped Eyes");
System.out.println("Code point of 'Smiling Face with Heart-Shaped Eyes': " + cp);
int cpc = Character.codePointCount(EMOJI, 0, EMOJI.length());
System.out.println("Code point count of 'Smiling Face with Heart-Shaped Eyes': " + cpc);
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P67_UnconditionalPatternsJDK17/src/main/java/modern/challenge/Main.java | Chapter02/P67_UnconditionalPatternsJDK17/src/main/java/modern/challenge/Main.java | package modern.challenge;
class Vehicle {
public String start() { return "started"; }
public String stop() { return "stopped"; }
}
class Truck extends Vehicle {}
class Van extends Vehicle {}
public class Main {
private static String drive(Vehicle v) {
return switch (v) {
case Truck truck -> "truck: " + truck;
case Van van -> "van: " + van;
case null -> "so, you don't have a vehicle?"; // save the situation before JDK 19
case Vehicle vehicle -> "vehicle: " + vehicle.start(); // total/unconditional pattern
};
}
public static void main(String[] args) {
System.out.println(Main.drive(new Truck()));
System.out.println(Main.drive(new Van()));
System.out.println(Main.drive(null));
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P47_ErasureHeapPollution/src/main/java/modern/challenge/Main.java | Chapter02/P47_ErasureHeapPollution/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
Main.listOf(ints, 1, 2, 3);
Main.listsOfYeak(ints);
}
// @SuppressWarnings({"unchecked", "varargs"})
@SafeVarargs
public static <T> void listOf(List<T> list, T... ts) {
list.addAll(Arrays.asList(ts));
}
// don't use @SafeVarargs in such cases
public static void listsOfYeak(List<Integer>... lists) {
Object[] listsAsArray = lists;
listsAsArray[0] = Arrays.asList(4, 5, 6);
Integer someInt = lists[0].get(0);
listsAsArray[0] = Arrays.asList("a", "b", "c");
Integer someIntYeak = lists[0].get(0); // ClassCastException
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/SnookerPlayer.java | Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/SnookerPlayer.java | package modern.challenge;
public class SnookerPlayer extends Player {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/FootballPlayer.java | Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/FootballPlayer.java | package modern.challenge;
public class FootballPlayer extends Player {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/Player.java | Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/Player.java | package modern.challenge;
public class Player {
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/Main.java | Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/Main.java | package modern.challenge;
public class Main {
public enum PlayerTypes {
TENNIS,
FOOTBALL,
SNOOKER,
UNKNOWN
}
public static void main(String[] args) {
// switch statement
Player playerSwitchStatementUgly = createPlayerSwitchStatementUgly(PlayerTypes.TENNIS);
Player playerSwitchStatementNice = createPlayerSwitchStatementNice(PlayerTypes.TENNIS);
// switch expression
Player playerSwitchExpression = createPlayerSwitchExpression(PlayerTypes.TENNIS);
Player playerSwitchExpressionYield = createPlayerSwitchExpressionBreak(PlayerTypes.TENNIS);
}
private static Player createPlayerSwitchStatementUgly(PlayerTypes playerType) {
Player player = null;
switch (playerType) {
case TENNIS:
player = new TennisPlayer();
break;
case FOOTBALL:
player = new FootballPlayer();
break;
case SNOOKER:
player = new SnookerPlayer();
break;
case UNKNOWN:
throw new UnknownPlayerException("Player type is unknown");
default:
throw new IllegalArgumentException("Invalid player type: " + playerType);
}
return player;
}
private static Player createPlayerSwitchStatementNice(PlayerTypes playerType) {
switch (playerType) {
case TENNIS:
return new TennisPlayer();
case FOOTBALL:
return new FootballPlayer();
case SNOOKER:
return new SnookerPlayer();
case UNKNOWN:
throw new UnknownPlayerException("Player type is unknown");
default:
throw new IllegalArgumentException("Invalid player type: " + playerType);
}
}
private static Player createPlayerSwitchExpression(PlayerTypes playerType) {
return switch (playerType) {
case TENNIS->
new TennisPlayer();
case FOOTBALL->
new FootballPlayer();
case SNOOKER->
new SnookerPlayer();
case UNKNOWN->
throw new UnknownPlayerException("Player type is unknown");
// default is not mandatory
default->
throw new IllegalArgumentException("Invalid player type: " + playerType);
};
}
private static Player createPlayerSwitchExpressionBreak(PlayerTypes playerType) {
return switch (playerType) {
case TENNIS:
yield new TennisPlayer();
case FOOTBALL:
yield new FootballPlayer();
case SNOOKER:
yield new SnookerPlayer();
case UNKNOWN:
throw new UnknownPlayerException("Player type is unknown");
// default is not mandatory
default:
throw new IllegalArgumentException("Invalid player type: " + playerType);
};
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/TennisPlayer.java | Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/TennisPlayer.java | package modern.challenge;
public class TennisPlayer extends Player{
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/UnknownPlayerException.java | Chapter02/P53_YieldSwitchExpression/src/main/java/modern/challenge/UnknownPlayerException.java | package modern.challenge;
public class UnknownPlayerException extends RuntimeException {
private static final long serialVersionUID = 1L;
public UnknownPlayerException() {
super();
}
public UnknownPlayerException(String message) {
super(message);
}
public UnknownPlayerException(Throwable cause) {
super(cause);
}
public UnknownPlayerException(String message, Throwable cause) {
super(message, cause);
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter02/P63_TypePatternMatchingSwitch/src/main/java/modern/challenge/Usb.java | Chapter02/P63_TypePatternMatchingSwitch/src/main/java/modern/challenge/Usb.java |
package modern.challenge;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Usb {
public static String save(Object o) throws IOException {
return switch(o) {
case File file -> "Saving a file of size: " + String.format("%,d bytes", file.length());
case Path path -> "Saving a file of size: " + String.format("%,d bytes", Files.size(path));
case String str -> "Saving a string of size: " + String.format("%,d bytes", str.length());
case null -> "Why are you doing this?";
default -> "I cannot save the given object";
};
}
public static void main(String[] args) throws IOException {
System.out.println(save(Paths.get("pom.xml")));
System.out.println(save(new File("pom.xml")));
System.out.println(save("This is a plain string"));
System.out.println(save(null));
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P272_ProgrammaticSWSAdaptRequest/src/main/java/modern/challenge/Main.java | Chapter13/P272_ProgrammaticSWSAdaptRequest/src/main/java/modern/challenge/Main.java | package modern.challenge;
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import java.io.IOException;
import static java.lang.System.out;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
HttpHandler fileHandler = SimpleFileServer.createFileHandler(
Path.of("./docs").toAbsolutePath());
Filter preFilter = Filter.adaptRequest(
"Add 'Author' header", r -> r.with("Author", List.of("Anghel Leonard")));
Filter postFilter = SimpleFileServer.createOutputFilter(out, SimpleFileServer.OutputLevel.VERBOSE);
HttpServer sws = HttpServer.create(
new InetSocketAddress(9009), 10, "/mybooks", fileHandler, preFilter, postFilter);
sws.start();
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P274_SWSInMemoryFileSystem/src/main/java/modern/challenge/Main.java | Chapter13/P274_SWSInMemoryFileSystem/src/main/java/modern/challenge/Main.java | package modern.challenge;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import com.sun.net.httpserver.SimpleFileServer.OutputLevel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws IOException {
HttpServer sws = SimpleFileServer.createFileServer(
new InetSocketAddress(9009),
inMemoryDirectory(),
OutputLevel.VERBOSE);
sws.start();
}
private static Path inMemoryDirectory() throws IOException {
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.forCurrentPlatform());
Path docs = fileSystem.getPath("docs");
Files.createDirectory(docs);
Path books = docs.resolve("books.txt"); // /docs/books.txt
Files.write(books, ImmutableList.of(
"Java Coding Problems 1st Edition",
"Java Coding Problems 2st Edition",
"jOOQ Masterclass",
"The Complete Coding Interview Guide in Java"),
StandardCharsets.UTF_8);
return docs.toAbsolutePath();
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P271_ProgrammaticSWSFileHandler/src/main/java/modern/challenge/Main.java | Chapter13/P271_ProgrammaticSWSFileHandler/src/main/java/modern/challenge/Main.java | package modern.challenge;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws IOException {
HttpHandler fileHandler = SimpleFileServer.createFileHandler(
Path.of("./docs").toAbsolutePath());
HttpServer sws = HttpServer.create(
new InetSocketAddress(9009), 10, "/mybooks", fileHandler);
sws.start();
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P262_NonBlockingEchoServer/src/main/java/modern/challenge/Main.java | Chapter13/P262_NonBlockingEchoServer/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Main {
private static final int SERVER_PORT = 4444;
private final Map<SocketChannel, List<byte[]>> registerTrack = new HashMap<>();
private final ByteBuffer tBuffer = ByteBuffer.allocate(2 * 1024);
private void startEchoServer() {
// call the open() method for Selector/ServerSocketChannel
try (Selector selector = Selector.open();
ServerSocketChannel serverSC = ServerSocketChannel.open()) {
// ServerSocketChannel and Selector successfully opened
if ((serverSC.isOpen()) && (selector.isOpen())) {
// configure non-blocking mode
serverSC.configureBlocking(false);
// optionally, configure the client side options
serverSC.setOption(StandardSocketOptions.SO_RCVBUF, 256 * 1024);
serverSC.setOption(StandardSocketOptions.SO_REUSEADDR, true);
// bind the server socket channel to the port
serverSC.bind(new InetSocketAddress(SERVER_PORT));
// register this channel with the selector
serverSC.register(selector, SelectionKey.OP_ACCEPT);
// waiting for clients
System.out.println("Waiting for clients ...");
while (true) {
// waiting for events
selector.select();
// the selected keys have something to be processed
Iterator itkeys = selector.selectedKeys().iterator();
while (itkeys.hasNext()) {
SelectionKey selkey = (SelectionKey) itkeys.next();
// avoid processing the same key twice
itkeys.remove();
if (!selkey.isValid()) {
continue;
}
if (selkey.isAcceptable()) {
acceptOperation(selkey, selector);
} else if (selkey.isReadable()) {
this.readOperation(selkey);
} else if (selkey.isWritable()) {
this.writeOperation(selkey);
}
}
}
} else {
System.out.println("Cannot open the selector/channel");
}
} catch (IOException ex) {
System.err.println(ex);
// handle exception
}
}
// isAcceptable = true
private void acceptOperation(SelectionKey selkey, Selector selector) throws IOException {
ServerSocketChannel serverSC = (ServerSocketChannel) selkey.channel();
SocketChannel acceptSC = serverSC.accept();
acceptSC.configureBlocking(false);
System.out.println("New connection: " + acceptSC.getRemoteAddress());
// send an welcome message
acceptSC.write(ByteBuffer.wrap("Hey !\n".getBytes("UTF-8")));
// register the channel with this selector to support more I/O
registerTrack.put(acceptSC, new ArrayList<>());
acceptSC.register(selector, SelectionKey.OP_READ);
}
// isReadable = true
private void readOperation(SelectionKey selkey) {
try {
SocketChannel socketC = (SocketChannel) selkey.channel();
tBuffer.clear();
int byteRead = -1;
try {
byteRead = socketC.read(tBuffer);
} catch (IOException e) {
System.err.println("Read error!");
// handle exception
}
if (byteRead == -1) {
this.registerTrack.remove(socketC);
System.out.println("Connection was closed by: " + socketC.getRemoteAddress());
socketC.close();
selkey.cancel();
return;
}
byte[] byteData = new byte[byteRead];
System.arraycopy(tBuffer.array(), 0, byteData, 0, byteRead);
System.out.println(new String(byteData, "UTF-8") + " from " + socketC.getRemoteAddress());
// send the bytes back to client
doEchoTask(selkey, byteData);
} catch (IOException ex) {
System.err.println(ex);
// handle exception
}
}
// isWritable = true
private void writeOperation(SelectionKey selkey) throws IOException {
SocketChannel socketC = (SocketChannel) selkey.channel();
List<byte[]> channelByteData = registerTrack.get(socketC);
Iterator<byte[]> iter = channelByteData.iterator();
while (iter.hasNext()) {
byte[] itb = iter.next();
iter.remove();
socketC.write(ByteBuffer.wrap(itb));
}
selkey.interestOps(SelectionKey.OP_READ);
}
private void doEchoTask(SelectionKey selkey, byte[] dataByte) {
SocketChannel socketC = (SocketChannel) selkey.channel();
List<byte[]> channelByteData = registerTrack.get(socketC);
channelByteData.add(dataByte);
selkey.interestOps(SelectionKey.OP_WRITE);
}
public static void main(String[] args) {
Main main = new Main();
main.startEchoServer();
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P271_ProgrammaticSWSExecutor/src/main/java/modern/challenge/Main.java | Chapter13/P271_ProgrammaticSWSExecutor/src/main/java/modern/challenge/Main.java | package modern.challenge;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import com.sun.net.httpserver.SimpleFileServer.OutputLevel;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
HttpServer sws = SimpleFileServer.createFileServer(
new InetSocketAddress(9009),
Path.of("./docs").toAbsolutePath(),
OutputLevel.VERBOSE);
sws.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
sws.start();
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P267_BlockingEchoServerKEM/src/main/java/modern/challenge/Main.java | Chapter13/P267_BlockingEchoServerKEM/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KEM;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class Main {
private static final int PORT = 5555;
private static final String IP = "127.0.0.1";
private static final Map<SocketAddress, SecretKey> receiver = new HashMap<>(1);
private static SecretKey secretKeySender;
public static void main(String[] args)
throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
ByteBuffer buffer = ByteBuffer.allocate(44);
try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
if (serverSocketChannel.isOpen()) {
serverSocketChannel.configureBlocking(true);
serverSocketChannel.bind(new InetSocketAddress(IP, PORT));
System.out.println("Waiting for connections ...");
while (true) {
try (SocketChannel socketChannel = serverSocketChannel.accept()) {
System.out.println("Incoming connection from: " + socketChannel.getRemoteAddress());
receiver.put(socketChannel.getRemoteAddress(), null);
while (socketChannel.read(buffer) != -1) {
if (receiver.get(socketChannel.getRemoteAddress()) == null) {
KeyFactory kf = KeyFactory.getInstance("X25519");
PublicKey publicKeyReceiver = kf.generatePublic(
new X509EncodedKeySpec(buffer.array()));
KEM kemSender = KEM.getInstance("DHKEM");
KEM.Encapsulator encorSender = kemSender.newEncapsulator(publicKeyReceiver);
KEM.Encapsulated encedSender = encorSender.encapsulate(
0, encorSender.secretSize(), "AES");
secretKeySender = encedSender.key();
receiver.put(socketChannel.getRemoteAddress(), secretKeySender);
socketChannel.write(ByteBuffer.wrap(encedSender.encapsulation()));
System.out.println("Secret Key Sender: " + secretKeySender);
buffer.clear();
} else {
int position = buffer.position();
byte[] message = new byte[position];
buffer.flip();
buffer.get(message, 0, position);
buffer.clear();
System.out.println("\nEncrypted message:");
System.out.println(new String(message, Charset.defaultCharset()));
System.out.println("\nDecrypted message:");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySender);
String decMessage = new String(cipher.doFinal(message), Charset.defaultCharset());
System.out.println(decMessage);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySender);
socketChannel.write(ByteBuffer.wrap(
cipher.doFinal("The generated password is: O98S!".getBytes())));
}
}
} catch (IOException ex) {
// handle exception
}
}
} else {
System.out.println("The server socket channel cannot be opened!");
}
} catch (IOException ex) {
System.err.println(ex);
// handle exception
}
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P275_SWSZipFileSystem/src/main/java/modern/challenge/Main.java | Chapter13/P275_SWSZipFileSystem/src/main/java/modern/challenge/Main.java | package modern.challenge;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import com.sun.net.httpserver.SimpleFileServer.OutputLevel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
HttpServer sws = SimpleFileServer.createFileServer(
new InetSocketAddress(9009), zipFileSystem(),
OutputLevel.VERBOSE);
sws.start();
}
private static Path zipFileSystem() throws IOException {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
Path root = Path.of("./zips").toAbsolutePath();
Path zipPath = root.resolve("docs.zip").toAbsolutePath().normalize();
FileSystem zipfs = FileSystems.newFileSystem(zipPath, env);
Path externalTxtFile = Paths.get("./docs/books.txt");
Path pathInZipfile = zipfs.getPath("/bookszipped.txt");
// copy a file into the zip file
Files.copy(externalTxtFile, pathInZipfile,
StandardCopyOption.REPLACE_EXISTING);
return zipfs.getPath("/");
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P263_ConnectedClient/src/main/java/modern/challenge/Main.java | Chapter13/P263_ConnectedClient/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardProtocolFamily;
import java.nio.channels.DatagramChannel;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
public class Main {
private static final int SERVER_PORT = 4444;
private static final String SERVER_IP = "127.0.0.1"; // modify this accordingly if you want to test remote
private static final int MAX_SIZE_OF_PACKET = 65507;
public static void main(String[] args) {
CharBuffer cBuffer;
Charset charset = Charset.defaultCharset();
CharsetDecoder chdecoder = charset.newDecoder();
ByteBuffer bufferToEcho = ByteBuffer.wrap("Echo: I'm a great server!".getBytes());
ByteBuffer echoedBuffer = ByteBuffer.allocateDirect(MAX_SIZE_OF_PACKET);
// create a datagram channel
try (DatagramChannel dchannel
= DatagramChannel.open(StandardProtocolFamily.INET)) {
// optionally, configure the client side options
dchannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);
dchannel.setOption(StandardSocketOptions.SO_SNDBUF, 4 * 1024);
// if the channel was successfully opened
if (dchannel.isOpen()) {
// connect to server (remote address)
dchannel.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT));
// if the channel was successfully connected
if (dchannel.isConnected()) {
// sending data packets
int sentBytes = dchannel.write(bufferToEcho);
System.out.println("Sent " + sentBytes + " bytes to the server");
dchannel.read(echoedBuffer);
echoedBuffer.flip();
cBuffer = chdecoder.decode(echoedBuffer);
System.out.println(cBuffer.toString());
echoedBuffer.clear();
} else {
System.out.println("Cannot connect the channel");
}
} else {
System.out.println("Cannot open the channel");
}
} catch (SecurityException | IOException ex) {
System.err.println(ex);
// handle exception
}
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P261_BlockingEchoServer/src/main/java/modern/challenge/Main.java | Chapter13/P261_BlockingEchoServer/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
public class Main {
private static final int SERVER_PORT = 4444;
private static final String SERVER_IP = "127.0.0.1";
public static void main(String[] args) {
ByteBuffer tBuffer = ByteBuffer.allocateDirect(1024);
// open a brand new server socket channel
try (ServerSocketChannel serverSC = ServerSocketChannel.open()) {
// server socket channel was created
if (serverSC.isOpen()) {
// configure the blocking mode
serverSC.configureBlocking(true);
// optionally, configure the server side options
serverSC.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);
serverSC.setOption(StandardSocketOptions.SO_REUSEADDR, true);
// bind the server socket channel to local address
serverSC.bind(new InetSocketAddress(SERVER_IP, SERVER_PORT));
// waiting for clients
System.out.println("Waiting for clients ...");
// ready to accept incoming connections
while (true) {
try (SocketChannel acceptSC = serverSC.accept()) {
System.out.println("New connection: " + acceptSC.getRemoteAddress());
// sending data
while (acceptSC.read(tBuffer) != -1) {
tBuffer.flip();
acceptSC.write(tBuffer);
if (tBuffer.hasRemaining()) {
tBuffer.compact();
} else {
tBuffer.clear();
}
}
} catch (IOException ex) {
// handle exception
}
}
} else {
System.out.println("Server socket channel unavailable!");
}
} catch (IOException ex) {
System.err.println(ex);
// handle exception
}
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P263_ConnectionlessClient/src/main/java/modern/challenge/Main.java | Chapter13/P263_ConnectionlessClient/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardProtocolFamily;
import java.nio.channels.DatagramChannel;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
public class Main {
private static final int SERVER_PORT = 4444;
private static final String SERVER_IP = "127.0.0.1"; // modify this accordingly if you want to test remote
private static final int MAX_SIZE_OF_PACKET = 65507;
public static void main(String[] args) throws InterruptedException {
CharBuffer cBuffer;
Charset charset = Charset.defaultCharset();
CharsetDecoder chdecoder = charset.newDecoder();
ByteBuffer bufferToEcho = ByteBuffer.wrap(
"Echo: I'm a great server!".getBytes());
ByteBuffer echoedBuffer = ByteBuffer.allocateDirect(MAX_SIZE_OF_PACKET);
// create a datagram channel
try (DatagramChannel dchannel
= DatagramChannel.open(StandardProtocolFamily.INET)) {
// if the channel was successfully opened
if (dchannel.isOpen()) {
// optionally, configure the client side options
dchannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);
dchannel.setOption(StandardSocketOptions.SO_SNDBUF, 4 * 1024);
// sending data packets
int sentBytes = dchannel.send(bufferToEcho, new InetSocketAddress(SERVER_IP, SERVER_PORT));
System.out.println("Sent " + sentBytes + " bytes to the server");
dchannel.receive(echoedBuffer);
// hack to wait for the server to echo
Thread.sleep(5000);
echoedBuffer.flip();
cBuffer = chdecoder.decode(echoedBuffer);
System.out.println(cBuffer.toString());
echoedBuffer.clear();
} else {
System.out.println("Cannot open the channel");
}
} catch (SecurityException | IOException ex) {
System.err.println(ex);
// handle exception
}
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P265_NetworkInterface/src/main/java/modern/challenge/Main.java | Chapter13/P265_NetworkInterface/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class Main {
public static void main(String[] args) throws SocketException {
Enumeration allNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetworkInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) allNetworkInterfaces.nextElement();
System.out.println("\nDisplay Name: " + ni.getDisplayName());
System.out.println(ni.getDisplayName() + " is up and running ? " + ni.isUp());
System.out.println(ni.getDisplayName() + " is multicast capable ? " + ni.supportsMulticast());
System.out.println(ni.getDisplayName() + " name: " + ni.getName());
System.out.println(ni.getDisplayName() + " is virtual ? " + ni.isVirtual());
Enumeration ips = ni.getInetAddresses();
if (!ips.hasMoreElements()) {
System.out.println("IP addresses: none");
} else {
System.out.println("IP addresses:");
while (ips.hasMoreElements()) {
InetAddress ip = (InetAddress) ips.nextElement();
System.out.println("IP: " + ip);
}
}
}
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P271_ProgrammaticSWSFilters/src/main/java/modern/challenge/Main.java | Chapter13/P271_ProgrammaticSWSFilters/src/main/java/modern/challenge/Main.java | package modern.challenge;
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Main {
public static void main(String[] args) throws IOException {
HttpHandler fileHandler = SimpleFileServer.createFileHandler(
Path.of("./docs").toAbsolutePath());
Path swslog = Paths.get("swslog.txt");
BufferedOutputStream output = new BufferedOutputStream(Files.newOutputStream(
swslog, StandardOpenOption.CREATE, StandardOpenOption.WRITE));
Filter filter = SimpleFileServer.createOutputFilter(output, SimpleFileServer.OutputLevel.VERBOSE);
HttpServer sws = HttpServer.create(
new InetSocketAddress(9009), 10, "/mybooks", fileHandler, filter);
sws.start();
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P266_MulticastServer/src/main/java/modern/challenge/Main.java | Chapter13/P266_MulticastServer/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.StandardProtocolFamily;
import java.nio.channels.DatagramChannel;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.util.Date;
public class Main {
private static final int SERVER_PORT = 4444;
private static final String MULTICAST_GROUP = "225.4.5.6";
private static final String MULTICAST_NI_NAME = "ethernet_32775";
public static void main(String[] args) {
ByteBuffer dtBuffer;
// create a channel
try (DatagramChannel dchannel = DatagramChannel.open(StandardProtocolFamily.INET)) {
// if the channel was successfully opened
if (dchannel.isOpen()) {
// get the multicast network interface
NetworkInterface mni = NetworkInterface.getByName(MULTICAST_NI_NAME);
// optionally, configure the server side options
dchannel.setOption(StandardSocketOptions.IP_MULTICAST_IF, mni);
dchannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
// bind the channel to local address
dchannel.bind(new InetSocketAddress(SERVER_PORT));
System.out.println("Server is ready ... sending date-time info soon ...");
// sending datagrams
while (true) {
// sleep for 10000 ms (10 seconds)
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {}
System.out.println("Sending date-time ...");
dtBuffer = ByteBuffer.wrap(new Date().toString().getBytes());
dchannel.send(dtBuffer, new InetSocketAddress(
InetAddress.getByName(MULTICAST_GROUP), SERVER_PORT));
dtBuffer.flip();
}
} else {
System.out.println("The channel is unavailable!");
}
} catch (IOException ex) {
System.err.println(ex);
}
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P273_ProgrammaticSWSComplementHandler/src/main/java/modern/challenge/Main.java | Chapter13/P273_ProgrammaticSWSComplementHandler/src/main/java/modern/challenge/Main.java | package modern.challenge;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpHandlers;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.Request;
import com.sun.net.httpserver.SimpleFileServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) throws IOException {
HttpHandler complementHandler = HttpHandlers.of(200, Headers.of(
"Content-Type", "text/plain"), "No data available");
HttpHandler fileHandler = SimpleFileServer.createFileHandler(
Path.of("./docs").toAbsolutePath());
Predicate<Request> predicate = request -> request.getRequestMethod().equalsIgnoreCase("GET");
HttpHandler handler = HttpHandlers.handleOrElse(predicate, fileHandler, complementHandler);
HttpServer sws = HttpServer.create(
new InetSocketAddress(9009), 10, "/mybooks", handler);
sws.start();
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P276_SWSJavaRuntimeDirectory/src/main/java/modern/challenge/Main.java | Chapter13/P276_SWSJavaRuntimeDirectory/src/main/java/modern/challenge/Main.java | package modern.challenge;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import com.sun.net.httpserver.SimpleFileServer.OutputLevel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws IOException {
HttpServer sws = SimpleFileServer.createFileServer(
new InetSocketAddress(9009), jrtFileSystem(),
OutputLevel.VERBOSE);
sws.start();
}
private static Path jrtFileSystem() {
URI uri = URI.create("jrt:/");
FileSystem jrtfs = FileSystems.getFileSystem(uri);
Path jrtRoot = jrtfs.getPath("modules").toAbsolutePath();
return jrtRoot;
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P262_NonBlockingEchoClient/src/main/java/modern/challenge/Main.java | Chapter13/P262_NonBlockingEchoClient/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
public class Main {
private static final int SERVER_PORT = 4444;
private static final String SERVER_IP = "127.0.0.1";
private static final int TIMEOUT_SELECTOR = 1_000;
public static void main(String[] args) throws InterruptedException {
ByteBuffer tBuffer = ByteBuffer.allocateDirect(2 * 1024);
ByteBuffer rBuffer;
CharBuffer cBuffer;
Charset charset = Charset.defaultCharset();
CharsetDecoder chdecoder = charset.newDecoder();
// call the open() for ServerSocketChannel and Selector
try (Selector selector = Selector.open();
SocketChannel clientSC = SocketChannel.open()) {
// ServerSocketChannel and Selector successfully opened
if ((clientSC.isOpen()) && (selector.isOpen())) {
// configure non-blocking mode
clientSC.configureBlocking(false);
// optionally, configure the client side options
clientSC.setOption(StandardSocketOptions.SO_RCVBUF, 128 * 1024);
clientSC.setOption(StandardSocketOptions.SO_SNDBUF, 128 * 1024);
clientSC.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
// register this channel with the selector
clientSC.register(selector, SelectionKey.OP_CONNECT);
// connecting to the remote host
clientSC.connect(new java.net.InetSocketAddress(SERVER_IP, SERVER_PORT));
System.out.println("Local host: " + clientSC.getLocalAddress());
// waiting for the connection
while (selector.select(TIMEOUT_SELECTOR) > 0) {
// get the keys
Set selkeys = selector.selectedKeys();
Iterator iter = selkeys.iterator();
// traverse and process the keys
while (iter.hasNext()) {
SelectionKey selkey = (SelectionKey) iter.next();
// remove the current key
iter.remove();
// get the key's socket channel
try (SocketChannel keySC = (SocketChannel) selkey.channel()) {
// attempt a connection
if (selkey.isConnectable()) {
// connection successfully achieved
System.out.println("Connection successfully achieved!");
// pending connections will be closed
if (keySC.isConnectionPending()) {
keySC.finishConnect();
}
// this delay is not necessary - it was added just for easy following the output
Thread.sleep(new Random().nextInt(5000));
// read/write from/to server
while (keySC.read(tBuffer) != -1) {
tBuffer.flip();
cBuffer = chdecoder.decode(tBuffer);
System.out.println(cBuffer.toString());
if (tBuffer.hasRemaining()) {
tBuffer.compact();
} else {
tBuffer.clear();
}
int r = new Random().nextInt(100);
if (r == 50) {
System.out.println("Number 50 is here so the channel will be closed");
break;
} else {
// this delay is not necessary - it was added just for easy following the output
Thread.sleep(new Random().nextInt(3000));
rBuffer = ByteBuffer.wrap(
"Random number:".concat(String.valueOf(r).concat(" ")).getBytes("UTF-8"));
keySC.write(rBuffer);
}
}
}
} catch (IOException ex) {
System.err.println(ex);
// handle exception
}
}
}
} else {
System.out.println("Cannot open the selector/channel");
}
} catch (IOException ex) {
System.err.println(ex);
// handle exception
}
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P261_BlockingEchoClient/src/main/java/modern/challenge/Main.java | Chapter13/P261_BlockingEchoClient/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Random;
public class Main {
private static final int SERVER_PORT = 4444;
private static final String SERVER_IP = "127.0.0.1";
public static void main(String[] args) {
ByteBuffer tBuffer = ByteBuffer.allocateDirect(1024);
ByteBuffer hBuffer = ByteBuffer.wrap("Hey !".getBytes());
ByteBuffer rBuffer;
CharBuffer cBuffer;
Charset charset = Charset.defaultCharset();
CharsetDecoder chdecoder = charset.newDecoder();
// create a brand new client socket channel
try (SocketChannel clientSC = SocketChannel.open()) {
// client socket channel was created
if (clientSC.isOpen()) {
// configure the blocking mode
clientSC.configureBlocking(true);
// optionally, configure the client side options
clientSC.setOption(StandardSocketOptions.SO_RCVBUF, 128 * 1024);
clientSC.setOption(StandardSocketOptions.SO_SNDBUF, 128 * 1024);
clientSC.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
clientSC.setOption(StandardSocketOptions.SO_LINGER, 5);
// connect this channel's socket to the proper address
clientSC.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT));
// check the connection availability
if (clientSC.isConnected()) {
// sending data
clientSC.write(hBuffer);
while (clientSC.read(tBuffer) != -1) {
tBuffer.flip();
cBuffer = chdecoder.decode(tBuffer);
System.out.println(cBuffer.toString());
if (tBuffer.hasRemaining()) {
tBuffer.compact();
} else {
tBuffer.clear();
}
int r = new Random().nextInt(100);
if (r == 50) {
System.out.println("Number 50 is here so the channel will be closed");
break;
} else {
rBuffer = ByteBuffer.wrap(
"Random number:".concat(String.valueOf(r)).getBytes());
clientSC.write(rBuffer);
}
}
} else {
System.out.println("Connection unavailable!");
}
} else {
System.out.println("Client socket channel unavailable!");
}
} catch (IOException ex) {
System.err.println(ex);
// handle exception
}
}
} | java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
PacktPublishing/Java-Coding-Problems-Second-Edition | https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P267_BlockingEchoClientKEM/src/main/java/modern/challenge/Main.java | Chapter13/P267_BlockingEchoClientKEM/src/main/java/modern/challenge/Main.java | package modern.challenge;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.DecapsulateException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KEM;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class Main {
private static final int PORT = 5555;
private static final String IP = "127.0.0.1";
private static PublicKey publicKey;
private static PrivateKey privateKey;
private static SecretKey secretKeyReceiver;
static {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("X25519");
KeyPair kp = kpg.generateKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException, DecapsulateException {
ByteBuffer buffer = ByteBuffer.allocate(32);
try (SocketChannel socketChannel = SocketChannel.open()) {
if (socketChannel.isOpen()) {
socketChannel.configureBlocking(true);
socketChannel.connect(new InetSocketAddress(IP, PORT));
if (socketChannel.isConnected()) {
// transmitting the public key to the sender
socketChannel.write(ByteBuffer.wrap(publicKey.getEncoded()));
while (socketChannel.read(buffer) != -1) {
if (secretKeyReceiver == null) {
KEM kemReceiver = KEM.getInstance("DHKEM");
KEM.Decapsulator decReceiver = kemReceiver.newDecapsulator(privateKey);
secretKeyReceiver = decReceiver.decapsulate(
buffer.array(), 0, decReceiver.secretSize(), "AES");
System.out.println("Secret Key Receiver: " + secretKeyReceiver);
buffer.clear();
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeyReceiver);
socketChannel.write(ByteBuffer.wrap(
cipher.doFinal("My token is: 763".getBytes())));
} else {
int position = buffer.position();
byte[] message = new byte[position];
buffer.flip();
buffer.get(message, 0, position);
buffer.clear();
System.out.println("\nEncrypted message:");
System.out.println(new String(message, Charset.defaultCharset()));
System.out.println("\nDecrypted message:");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, secretKeyReceiver);
String decMessage = new String(cipher.doFinal(message), Charset.defaultCharset());
System.out.println(decMessage);
}
}
} else {
System.out.println("The connection cannot be established!");
}
} else {
System.out.println("The socket channel cannot be opened!");
}
} catch (IOException ex) {
System.err.println(ex);
// handle exception
}
}
}
| java | MIT | 47b7c834407a607580baf8e3a23c1c24c24b8bc0 | 2026-01-05T02:37:06.170961Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.