lars
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 5/11/2025 in #❓︱qotw-answers
Week 125 — How can one set the heap size of a Java application?
Why the need?
We get
OutOfMemoryError
when the heap memory runs out. When this happens the JVM throws the OutOfMemoryError and if it is uncaught the program crashes.
Check JVM heap settings
To see how your JVM chooses defaults:
You’ll see values like:
These are set ergonomically based on your machine’s specs.
Example
In this Example we keep allocating 10MB chunks of memory until we get the OutOfMemoryError
.
Solution
We can set the initial as well as the max heap size by passing some VM options when we run the program.
- -Xms
: initial heap size
- -Xmx
: max heap size
We can pass these options like this:
Or for more verbose GC info we can add this options as well
3 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 5/11/2025 in #❓︱qotw-answers
Week 125 — How can one set the heap size of a Java application?
By default, the JVM detects a suitable heap size given system and environment constraints but sometimes, developers may want to set it to a different value.
For configuring the heap site, the most important option is the maximum heap size which can be set with the
-Xmx
argument. This argument must come before the main class or the -jar
argument when calling the java
command:
Similar to the maximum heap size, it is also possible to set an initial heap size. When the application starts, it will start with that heap size and allocate more memory if necessary until it reaches the maximum heap size.
3 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 5/4/2025 in #❓︱qotw-answers
Week 124 — How can one read and write CSV files in Java?
It could be done using BufferedReader, FileReader for reading CSV
And
BufferedWriter, FileWriter for writing CSV
4 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 5/4/2025 in #❓︱qotw-answers
Week 124 — How can one read and write CSV files in Java?
To write such a CSV file with Apache Commons CSV, one can call the
printRecord
on the CSVFormat
class for every entry:
It can then be read using the CSVFormat.parse
method:
4 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 5/4/2025 in #❓︱qotw-answers
Week 124 — How can one read and write CSV files in Java?
Reading and writing CSV files is possible both using the standard libraries (e.g.
java.io
) and using external libraries.
For example, we might want to save the following record in a CSV file and read it again:
This can be done using the JDK standard libraries by creating a Writer
and saving it line by line:
To read a CSV file corresponding to the code before, the file can be read line by line and split by commas:
However, this code does not address the possibility of commas, quoting, line breaks or backslashes in the input. While it is possible to add validation for that, it is also possible to use external libraries for this task.4 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/27/2025 in #❓︱qotw-answers
Week 123 — What is the difference between List.of() and Arrays.asList()?
Similar to
List.of
, List.copyOf
creates an immutable List
that is a copy of another List
Since this is a copy, changing the original List
doesn't modify the copy.
On the other hand, Collections.unmodifiableList
creates an unmodifiable view on a List
. While that view cannot be modified, changes to the backing List
are propagated to the view:
3 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/27/2025 in #❓︱qotw-answers
Week 123 — What is the difference between List.of() and Arrays.asList()?
Java provides various factory methods for creating lists and other collections including
List.of
, Arrays.asList
as well as List.copyOf
and Collections.unmodifiableList
.
The List.of
method creates a new list from the elements passed as arguments. The created list is immutable.
On the other hand, Arrays.asList
creates a List
view from an array. Changes to the List
are reflected in the array and vice-versa. Since arrays are not resizable, it is not possible to add or remove elements.
3 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/20/2025 in #❓︱qotw-answers
Week 122 — How can one specify a charset when reading from/writing to a text file?
To write data to a text file encoded with a given charset, the JDK provides overloads for many methods that behave differently for charsets:
This file can then be read using the same charset:
If the console is able to display emojis and configured correctly using UTF-8, executing the two code snippets after each other should display
Hello World
and the 💻 emoji.
However, if the file is attempted to be read using a charset that doesn't match, the output can get messed up:
As UTF-8 and UTF-16 don't use the same representations of characters, the output consists of characters that have little in common with the original text. When attemping to read the text file using ASCII instead, an exception is thrown because the emoji contains characters that are not valid ASCII:
3 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/20/2025 in #❓︱qotw-answers
Week 122 — How can one specify a charset when reading from/writing to a text file?
When writing a file, it is stored as binary data on the file system.
To store text files, the textual content has to converted to a binary format before writing to the file and converted back after reading. The used character encoding/charset decides how that process is performed. When converting between strings and binary data, the same charset should be used both converting the text to binary and for converting it back.
One such charset is ASCII which represents each character using only 7 bits at the cost of only being able to represent a few characters (typically aligned so that each character actually needs one byte). In contrast to that, unicode allows storing more characters where different characters may require a different amount of space depending on the character used. It comes in different flavors like UTF-8 (which requires at least 8 bits = 1 byte to store each character) or UTF-16 (requires at least 16 bits = 2 bytes to store each character). Letters that can be represented using ASCII are represented the exact same way in UTF-8 with the first bit being set to
0
. To indicate multiple bytes needed for a "code point" the first bits are set to 1
. Unicode also supports many other things like combining (joining) multiple code points to a single displayable character.
Java provides the java.nio.charset.Charset
class to represent charsets and includes the java.nio.charset.StandardCharsets
class with some commonly used charsets like US_ASCII
and UTF_8
.3 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
The Java standard libraries provide several mechanisms for sorting:
1. Arrays.sort()
Used for sorting arrays.
Works for primitive types (e.g., int[]) and objects (e.g., String[], Integer[]).
Overloads allow custom sorting via Comparator.
ex;
Arrays.sort(array);
Arrays.sort(array, Comparator.reverseOrder());
2. Collections.sort()
Used for sorting List collections (e.g., ArrayList).
Can sort using natural order or with a custom Comparator.
ex;
Collections.sort(list);
Collections.sort(list, comparator);
3. List.sort() (Java 8+)
Direct method on List interface using a lambda or Comparator.
ex;
list.sort(Comparator.comparing(Person::getName));
4. Streams API (Java 8+)
Used for sorting streams, especially in functional-style processing.
ex;
list.stream().sorted().collect(Collectors.toList());
list.stream().sorted(Comparator.comparing(...));
These mechanisms use efficient sorting algorithms internally, like TimSort for object sorting.
10 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
Once the comparison logic is defined, it can be used in a number of ways....
COLLECTIONS
Many classes in the Java Collections framework understand classes that implement
Comparable
, and will use the "natural ordering" exposed by that interface. Those same collection classes will often allow a separate Comparator
implementation to be supplied in the constructor to use for ordering. For instance,TreeSet
expects objects added to it to implement Comparable
, unless a separate Comparator
has been supplied to the constructor.
The List
interface defines a sort(Comparator)
method, which also allows for a null
parameter, in which case the "natural ordering" is used.
ARRAYS
The Collections framework also provides the Arrays
class, which contains a number of static methods for working with arrays, including comparison, sorting, and searching operations. Some of the methods accept a Comparator
, which can be null
to trigger the use of "natural ordering" (similar to the List::sort(Comparator)
method). Some require that the objects implement the Comparable
interface.
Note that Arrays
also provides methods for comparing, sorting, and searching arrays of numeric primitives, which are inherently comparable.10 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
The foundation of sorting comes down to two interfaces:
java.lang.Comparable<T>
and java.util.Comparator<T>
Comparable
is implemented by classes that want to have an intrinsic comparison order between objects of that class. For instance, a Person
class might implement Comparable<Person>
that sorts Person
objects by last name, then first name:
Comparator
provides a mechanism for creating external comparison ordering operations. These are often implemented as lambdas, but do not have to be. To continue the Person
example, another class can be created to order those objects by years of service:
10 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
There are a number of different mechanisms for sorting objects and values in a Java program. Which one to use depends on the data structure being used.
10 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
Similarly,
TreeSet
can be used to create a Set
which does not allow duplicates and is always sorted.
10 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
When elements are produced in some way and need to be consumed in their natural order (according to
Comparable
) or according to a custom Comparable
), PriorityQueue
is based on a heap and can be used which ensures that the "smallest" element is consumed first.
10 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
In addition to arrays,
List
s can be sorted using the Collections.sort
method.
10 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
Objects that have a natural order can choose to implement
Comparable
which allows them to define a compareTo
method specifying how these objects should be ordered by default (unless a custom Comparator
is specified). For example, String
s are naturally ordered lexicographically so it is not necessary to provide a custom Comparator
when that order is wanted.
10 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/13/2025 in #❓︱qotw-answers
Week 121 — What mechanisms do the Java standard libraries provide for sorting?
Arrays can be sorted using the
Arrays.sort
methods:
Sorting primitive types typically happens in ascending order of their values but when sorting arbitrary objects, one needs to decide how these should be sorted which can be done using a Comparator
that compares two objects and returns
- a positive value if the first object is considered greater than the second object
- a negative value if the first object is considered smaller than the second object
- zero if both objects are equal10 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/6/2025 in #❓︱qotw-answers
Week 120 — What are the differences between `HashSet` and `TreeSet`?
In addition to
Set
, the TreeSet
implements both SortedSet
and NavigableSet
. SortedSet
guarantees the sort and iteration order of its elements. The order is determined by the elements' natural order, or by a Comparator
provided at construction time. NavigableSet
defines additional methods to navigate through the elements in the Set
. Because the elements are in a predictable order, the navigation methods also behave predictably.6 replies
JCHJava Community | Help. Code. Learn.
•Created by JavaBot on 4/6/2025 in #❓︱qotw-answers
Week 120 — What are the differences between `HashSet` and `TreeSet`?
HashSet
& TreeSet
are both implementations of the java.util.Set
interface. Like all implementations of Set
, only unique elements are allowed. However, a TreeSet
also provides predictable iteration order and other navigation primitives.6 replies