Posts in the “java” category

Java stack, heap, and frames definitions (Java memory information)

Summary: This article provides definitions and descriptions of the Java stack and heap.

I just read a couple of emails about the concepts of a Java stack and heap, and thinking that their descriptions weren’t exactly right, I decided to do a little research. There’s no better source than the source, so directly from Oracle’s Java website, here are definitions for the Java stack and Java heap.

Java switch statement example (switch structure and syntax)

Java switch case statement FAQ: Can you provide an example of a Java switch/case statement syntax?

Here's a sample Java method that takes an int argument and attempts to turn that int into a month string, using a Java switch case statement to make that decision:

A complete Java Ant MacOS Jarbundler build script

Java Mac application FAQ: Can you share a Java/Mac Ant build script that uses the Jarbundler task to make my Java application look like a native Mac OS X application?

NOTE: This solution is for Mac OS X systems running versions of Java prior to Java 7. If I remember right, it only works on those systems, and therefore only on Mac OS X systems 10.6 and earlier. I'm working on new tutorials for Java 7 and Mac OS X 10.7, 10.8, 10.9, and newer.

A Mac/Java javapackager example (getting the application bundle root directory)

UPDATE: The approach below worked with Java 8, and here is a link to the new solution for macOS and Java 14 and newer.

I wrote earlier about how to use the javapackager command to create a macOS application bundle from a Java application, so I won’t repeat all of that information here. Instead, in this article I just want to show how to display an image that’s stored in the Contents/Resources/Java directory of a Mac/Java application bundle.

An example of JSoup’s OutputSettings class

I ended up not using this code, but if you wanted to see one way to use JSoup’s OutputSettings (Document.OutputSettings) class to set some parameters before calling JSoup.clean, I hope this is helpful:

// tried some things to improve the html output
val settings: OutputSettings = new OutputSettings
settings.prettyPrint(true)  //`true` is default
settings.charset("UTF-8")
settings.outline(true)  //this is close to what i want, but too extreme
settings.indentAmount(4)
val cleanHtml: String = Jsoup.clean(html, "", wl, settings)

I can attest that this code works, it’s just not what I need at the moment.

Also, the code shown is written in Scala, but as you can see, it converts easily to Java.

Java Jar file: How to read a file from a Jar file

Java jar file reading FAQ: Can you show me how a Java application can read a file from own of its own Jar files?

Here's an example of some Java code I'm using to read a file (a text file) from a Java Jar file. This is useful any time you pack files and other resources into Jar files to distribute your Java application.

Java - read Jar file example #1

The source code to read a file from a Java Jar file uses the getClass and getResourceAsStream methods:

Java socket timeout: How to set the timeout on a Java socket

Java socket FAQ: How do I set the timeout on a Java socket? That is, when I'm trying to read data from a Java socket, and I'm not getting any response from the server, how do I make sure my code doesn't hang up? (It needs to time out after several seconds.)

Java socket timeout

Answer: Just set the SO_TIMEOUT on your Java Socket, as shown in the following sample code:

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

As a quick Java tip related to lists, 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.

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:

Java ‘int’ array examples (declaring, initializing, populating)

Java array FAQ: How do you create an array of Java int values (i.e., a Java “int array”)?

Answer: There are several ways to define an int array in Java; let’s take a look at a few examples.

1) Declare a Java int array with initial size; populate it later

If you know the desired size of your array, an you'll be adding elements to your array some time later in your code, you can define a Java int array using this syntax:

Java: JOptionPane showMessageDialog examples (part 1)

[toc]

I’ve been working with the Java JOptionPane showMessageDialog a lot lately, so I thought I’d create a page here with a number of showMessageDialog examples, sort of a JOptionPane reference page.

I’ll walk you through some Java JOptionPane examples here, starting with a simple example and then increasing the level of difficulty as I go on.

Java JFrame example: How to display a JFrame

This morning when I saw some Java JFrame code on a mailing list, it made me think that I needed to put a simple JFrame example out here, something that would show how to properly construct and display a JFrame without getting into a discussion of anything else. Here are two examples that show the correct technique.

1) A simple Java JFrame example

To that end, here is the source code for a simple "JFrame example" demo class. This example shows how to construct a JFrame, and make sure it's properly displayed using the SwingUtilities invokeLater method:

The Java 8 lambda Thread and Runnable syntax and examples

As a quick note, here are some examples of the Java 8 lambda Thread and Runnable syntax. As a little bonus I also show the Java lambda syntax in other situations, such as with an ActionListener, and several “handler” examples, including when a lambda has multiple parameters.

The Java Thread/Runnable lambda syntax

First, here’s the lambda syntax for a Runnable that was introduced with Java 8, and now works with Java 11, Java 14, Java 17, etc., where I create a Runnable and pass it to a Thread:

Runnable runnable = () -> { 
    // your code here ...
};
Thread t = new Thread(runnable);
t.start();

And here’s the Java Thread lambda syntax (without a Runnable):

Thread t = new Thread(() -> {
    // your code here ...
});

You can also use this lambda approach to create a Java Thread, without creating a reference (variable) to the thread:

new Thread(() -> // your code here).start();

Note: There’s an interesting approach documented here:

def run2() = {println("hi2")}
new Thread(() => run2).start

The older Thread and Runnable syntax

If you can’t use Java 8+ lambdas — or don’t want to — here’s the pre-lambda thread syntax using a Runnable:

// pre java 8 lambdas
Thread t = new Thread(new Runnable() {
    public void run() {
        // your code here ...
    }
});

t.start();

Here’s the old Thread syntax, using the anonymous class approach:

Thread thread = new Thread() {
    public void run() {
        // your code here
    }
}

thread.start();

You can also create a class to extend a Thread and then run it, like this:

public class MyThread extends Thread {
    public void run() {
        // your code here
    }
}

MyThread myThread = new MyThread();
myTread.start();

Java 8 ActionListener examples

With Java 8 lambdas this ActionListener/ActionEvent code:

ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        handleMakeTheImageLargerAction();
}};

can be rewritten as this:

ActionListener actionListener = actionEvent -> handleMakeTheImageLargerAction();

More Java lambda syntax examples

While I’m in the Java lambda neighborhood, here are some more examples of the Java lambda syntax, in this case showing how I use the lambda syntax for some java.awt.Desktop event handlers:

desktop.setAboutHandler(e ->
    JOptionPane.showMessageDialog(null, "About dialog")
);
desktop.setPreferencesHandler(e ->
    JOptionPane.showMessageDialog(null, "Preferences dialog")
);
desktop.setQuitHandler((e,r) -> {
        JOptionPane.showMessageDialog(null, "Quit dialog");
        System.exit(0);
    }
);

That code comes from my Java 10 on MacOS About, Preferences, and Quit handlers example.

How to set a Java JFrame title

JFrame title FAQ: How do I set the title of a Java JFrame?

Solution

There are two ways to set the JFrame title. First, you can set the JFrame title when you construct your JFrame, like this:

Java: How to find the longest String in an array of Strings

Java String array FAQ: Can you share an example of how to determine the largest String in a Java String array?

Sure, in this tutorial I'll share the source code for a complete Java class with a method that demonstrates how to find the longest String in a Java string array.

Finding the longest string in a Java string array

Here's the source code that shows how to find the longest string in a Java String array: