java

recent posts related to java, jdbc, spring, etc.

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 method to replace all instances of a pattern in a String with a replacement pattern

Note: The code shown below is a bit old. If you want to perform a “search and replace” operation on all instances of a given pattern, all you have to do these days is use the replaceAll method on a Java String, like this:

String s = "123 Main Street";
String result = s.replaceAll("[0-9]", "-");

That second line of code returns the string “--- Main Street”. I kept the information below here for background information.

How to determine the current monitor size with multiple displays - Java Swing, JavaFX

Note: This code is currently a work in progress. I know of possible approaches, but I don’t know of a perfect working solution yet.

I’m currently trying to find the right way to find the current monitor size, when you’re writing a Java Swing application to work in a multiple-monitor configuration. I always use three monitors, so I can test this pretty easily.

A Java TimerTask, Timer, and scheduleAtFixedRate example

As a quick note, if you ever need to use a Java TimerTask, you can define one like this:

class BrightnessTimerTask extends TimerTask {
    @Override
    public void run() {
        // your custom code here ...
    }        
}

and you can then instantiate it, create a Timer, and schedule the task like this:

How to cast a null value in Java

Until a little while ago I don’t think I had ever thought about intentionally casting a null value in Java, but then I ran into a problem and realized that the solution was to cast a null value, like this:

FileDialog d = new FileDialog((java.awt.Frame) null);

You have to do that in this case because FileDialog has several one-argument constructors, including one that takes a JFrame and another that takes a JDialog. If you just put null in the constructor the Java compiler or your favorite IDE will complain, so you have to cast the null value to one of those specific types, and this syntax shows how to do this. (My app uses multiple frames, and at the moment I’d rather put null in the FileDialog constructor than try to determine which frame is currently in the foreground.)