Posts in the “java” category

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.

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 printf cheat sheet for my own programming purposes, and then thought it might be helpful to share it here.

Many languages, same syntax

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, Python, Perl, PHP, Ruby, Scala, and others. This means that your printf knowledge is reusable, which is a good thing.

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.

A Java HTTPS client example

Java HTTPS client FAQ: Can you share some source code for a Java HTTPS client application?

Sure, here's the source code for an example Java HTTPS client program I just used to download the contents of an HTTPS (SSL) URL. I actually found some of this in a newsgroup a while ago, but I can't find the source today to give them credit, so my apologies for that.

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 create and throw a custom exception

Java exceptions FAQ: How do I create a custom exception in Java?

Solution

The solution is to:

  • Create a custom exception class in Java
  • Throw the custom Java exception
  • In other code, catch the custom exception, and
  • Look at the output from our custom exception when we print a stack trace

Java stack and heap definitions

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: 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:

Java ‘array of objects’ syntax examples

Java array FAQ: Can you share some examples of how to create arrays in Java (Java object arrays)?

While I generally work with lists and maps in Java, I occasionally need to create object arrays in Java. Since I don't use arrays that often, I thought I'd share some examples here so I can have a handy Java array syntax reference.

A simple Java String array

I work with the String class a lot, and here's how to create a String array in Java: