Posts in the “java” category

Design Patterns in Java

I've recently started writing a series of articles on Design Patterns in Java, i.e., Design Patterns explained using Java source code examples. Although it will take me a little while to create each design pattern example, this page will eventually contain links to all of those examples.

If you're not familiar with software design patterns, they're described on Wikipedia like this:

[toc hidden:1]

How to use ‘static import’ in Java

I was just reminding myself how to write a generics class in Java, and for some reason while I was doing that I wanted to use the Java 'import static' capability so instead of typing this:

System.out.println("foo");

I could just use this:

out.println("foo");

The only thing you have to do to make this happen is to use this import static statement at the top of your class:

How to compare String equality in Java

Java String comparison FAQ: Can you share some examples of how to compare strings in Java?

If you’re like me, when I first started using Java, I wanted to use the == operator to test whether two String instances were equal, but that’s not the correct way to do it in Java.

[toc hidden:1]

Java examples of the Law of Demeter

Summary: The Law of Demeter is discussed using Java source code examples.

Whenever you talk to a good, experienced programmer, they will tell you that "loosely coupled" classes are very important to good software design.

The Law of Demeter for functions (or methods, in Java) attempts to minimize coupling between classes in any program. In short, the intent of this "law" is to prevent you from reaching into an object to gain access to a third object's methods. The Law of Demeter is often described this way:

An Easy Rules example (a Java “rules engine”)

I’m considering using Easy Rules as a simple “rules engine” in my Android Football Game application, primarily because (a) there are a ton of “rules” involved in having the computer call offensive and defensive plays, and (b) I’m trying to find a way to simplify that code and make it more maintainable.

The Easy Rules website has a Hello, world demo you can look at to get started, but after that, here is my example.

[toc hidden:1]

How to use multiple regex patterns with replaceAll (Java String class)

Java FAQ: How can I use multiple regular expression patterns with the replaceAll method in the Java String class?

Here’s a little example that shows how to replace many regular expression (regex) patterns with one replacement string in Scala and Java. I’ll show all of this code in Scala’s interactive interpreter environment, but in this case Scala is very similar to Java, so the initial solution can easily be converted to Java.

Java int, double, float, and mixed-type arithmetic rules

Java FAQ: What are the rules about Java arithmetic (multiplication, division) involving mixed data types?

While working on a math problem in Java just a little while ago, I realized that I wasn’t comfortable with the Java mixed-type division rules. That is, I wondered if the result of this equation:

3 / 2

the same as the result of this equation:

3 / 2.0

or this equation:

3.0 / 2.0

A Java Factory Pattern (Factory method) example

Java Design Patterns FAQ: Can you provide an example of the Factory Pattern in Java?

Sure. In this article we'll look at a small-but-complete example of the Factory Pattern ("Factory Design Pattern") implemented in Java.

[toc hidden:1]

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).

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 5 for loop syntax example

Java 5 FAQ: Can you share some examples of the Java 5 for loop syntax?

Sure. As a bit of background, in the days before Java 5 you could create a for loop to iterate over a collection of strings like this:

// assumes there is a method named "getList()"
List list = getList();

for (Iterator it = list.iterator(); it.hasNext();) {
  String value=(String)it.next();
}

Java 5 for loop syntax

That’s not too bad, but with the release of Java 5 your for loops can now be a little tighter, like this: