Posts in the “java” category

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

Java String array examples (with Java 5 for loop syntax)

Java String array FAQ: Can you share some Java array examples, specifically some String array examples, as well as the new for loop syntax that was introduced back in Java 5?

Solution

Sure. In this tutorial, I’ll show how to declare, populate, and iterate through Java string arrays, including the for loop syntax that was introduced with Java 5. Because creating a String array is just like creating and using any other Java object array, these examples also work as more generic object array examples.

A Java Robot class mouse and keyboard/keystroke example

Java Robot class FAQ: Can you show me an example of how to use the Java Robot class?

Answer: Um, yeah, sure ... I say that a little jokingly. Okay, what really happened is that while developing this Java Robot example code on my Mac, I had to reboot it about 10 times. When you use the Java Robot class, you're poking your head out into the native operating system, and if you mess up with your GUI events -- at least on a Mac OS X system -- a lot of bad things can happen.

Java two dimensional (2d) array examples

It's been so long since I create a two-dimensional Java array in I almost couldn't remember how to do it. Fortunately I did, and I thought I'd include my sample code here in case it will help anyone else.

So, in this quick tutorial, I'll show you how to create a two-dimensional array (2D array) of Java String objects, and then I'll show you how to access each element in the array.

How to create a two-dimensional Java array

First, here's how I create the two-dimensional arrays of strings with this code:

A Java instanceof array example

While working with various "Java instanceof" tests recently, my curiosity was piqued, and I thought I'd take a look at how the instanceof operator works when testing against a Java array.

Scala varargs syntax (and examples)

Scala FAQ: How do I use the Scala varargs syntax (or, What is the Scala varargs syntax)?

You can define a Scala function that accepts a varargs parameter like this:

def printAll(strings: String*) {
    strings.map(println)
}

The only magic in using the varargs syntax is adding the * symbol after the String declaration, as highlighted in this line of code in the function declaration:

Java: How to append text to a file with the FileWriter class

Java file writing FAQ: How do I append text to the end of a text file in Java?

The short answer is that you should create a FileWriter instance with the append flag set to true, like this:

BufferedWriter bw = new BufferedWriter(new FileWriter("checkbook.dat", true));

The rest of this article explains this.

A Java MySQL SELECT example

Summary: This is a Java/MySQL SQL SELECT example, demonstrating how to issue a SQL SELECT command from your Java source code, using a MySQL database.

A Java deep clone (deep copy) example

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.

Java enum examples/tutorial (an enum reference page)

Java enumerations FAQ: Can you share some Java enum examples, such as how to declare a Java enum, and how to use a Java enum in a for loop, if/then statement, and Java switch statement?

Sure. As described in the Sun/Oracle Java documentation, “you should use enum types any time you need to represent a fixed set of constants.” Let's take a look at some enum examples to see how this works.