Posts in the “java” category

What is a Java NumberFormatException?

Java exception FAQ: What is a Java NumberFormatException?

Answer: A Java NumberFormatException usually occurs when you try to do something like convert a String to a numeric value, like an int, float, double, long, etc.

The best way to show a NumberFormatException is by example, so here’s an example where I intentionally write bad Java code to throw a NumberFormatException:

A Java Month class (that can be used in a calendar application)

Summary: This blog post shares some source code for a Java Month class that you can use in your applications, such as a Java calendar applications.

I was just cleaning up some old bits, and ran across a Java Month class that I've used on several calendar-related projects. If you happen to be working on a Java calendar application, and need a class to represent the months in a year, this source code may be helpful, so I thought I'd share it here.

Converting a Scala class file to decompiled Java source code

As a Scala newbie, I'm curious about how the process of converting a Scala class back to Java source code works. What I really want to see is how my Scala source code is converted to Java source code. Besides plain old curiosity, I think that understanding more about how Scala works can also be very important to my understanding of Scala (such as the apply() method, and so on).

Java/OOP: The Strategy Design Pattern in Java

Summary: A discussion of the Strategy Design Pattern using Java source code examples.

The Strategy Design Pattern consists of a number of related algorithms encapsulated in a driver class often named Context. A user or a client program typically selects the algorithm they want to use, although the Context class may also select the algorithm automatically.

The intent of the Strategy Pattern is to make the algorithms easily interchangeable, and provide a means to choose the appropriate algorithm at a particular time.

Java: How to square a number

[toc]

Java math FAQ: How do I square a number in Java?

You can square a number in Java in at least two different ways:

  1. Multiply the number by itself
  2. Call the Math.pow function

A Java "extract method" refactoring example

Summary: A Java "extract method" refactoring example is demonstrated.

If you don't own a copy of Martin Fowler's Refactoring book, I highly recommend it. The basic idea of refactoring source code is that the code "smells" in one way or another, and there are a variety of ways to improve smelly code. More specifically, Mr. Fowler describes refactoring as this:

A simple RxJava 2 “Hello, world” example

As a brief note, and assuming that you already know a little bit about RxJava, here’s the simplest possible RxJava 2 “Hello, world” example I think you can create:

package hello;

import io.reactivex.Observable;

public class HelloWorld {

    public static void main(String[] args) {
        Observable<String> observable = Observable.just("Hello, world");
        observable.subscribe(System.out::println);
    }

}

A Java method that returns a random boolean value based on a probability

If you ever need a Java method that returns a boolean value based on a given probability, I can confirm that this method works:

/**
 * `probability` should be given as a percentage, such as
 * 10.0 (10.0%) or 25.5 (25.5%). As an example, if `probability` 
 * is 60% (60.0), 100 calls to this function should return ~60 
 * `true` values.
 * (Note that Math.random returns a value >= 0.0 and < 1.0.)
 */
static boolean getRandomBoolean(float probability) {
    double randomValue = Math.random()*100;  //0.0 to 99.9
    return randomValue <= probability;
}

Creating and populating a Java ArrayList (Java 9 and newer)

If you want to create and populate a Java ArrayList with Java 9, 11, and newer, you can use this syntax:

List<> ints = ArrayList<Integer>(List.of(1,2,3));

As shown, this uses the usual ArrayList constructor and the Java List.of method. Once you have an ArrayList like this you can continue to add new elements to it as usual:

ints.add(4);

Java: How to print elements in a List (without using a 'for' loop)

I was just reminded that if you need to print every element in a Java List, you can use the forEach method on the List:

// [1] create a List of strings.
java.util.List<String> listOfStrings = CollectionConverters.asJava(xs);

// [2] print the List of strings using forEach and System.out.println.
// note that there is no need for a 'for' loop.
listOfStrings.forEach(System.out::println);

I can confirm that as of August, 2021, this solution works just fine. So if you ever need to print every element in a Java List — without using a for loop — I hope this example is helpful.

A `printf` format reference page (cheat sheet) (C, Java, Scala, etc.)

Summary: This page is a printf formatting cheat sheet or reference page. I originally created this cheat sheet for my own programming purposes, and then thought I would share it here.

A great thing about the printf formatting syntax is that the format specifiers you can use are very similar — if not identical — between different languages, including C, C++, Java, Perl, PHP, Ruby, Scala, and others. This means that your printf knowledge is reusable, which is a good thing.

How to control Java heap size (memory) allocation (xmx, xms)

[toc]

Java/Scala memory FAQ: How do I control the amount of memory my Java program uses (i.e., Java RAM usage)?

Java RAM: Short answer

The short answer is that you use these java command-line parameters to help control the RAM use of application:

Java Timestamp example: How to create a “current timestamp” (i.e., now)

Java date/time FAQ: When working with the Timestamp class, how do I create a “Java current timestamp”? For instance, how do I create a JDBC Timestamp object to represent the “current time” (“now”)?

Solution

You can create a “current time” JDBC Timestamp in just a few lines of code, using the Java Calendar class and a java.util.Date instance, as shown in this example code:

[toc hidden:1]

A Java deep clone (deep copy) example

[toc]

Back when I was interviewing for computer programming positions in Boulder and Louisville, Colorado, I found that many interviewers ask questions about Java serialization. After being asked about serialization for the third time, I remembered an old Java deep clone hack that takes advantage of serialization.