Posts in the “java” category

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:

Java JFrame size: How to set the JFrame size

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

Solution: There are several different ways to set the size of a Java JFrame, but I generally use the setPreferredSize method of the JFrame class in combination with the Java Dimension class, like this:

jframe.setPreferredSize(new Dimension(400, 300));

A JFrame size example

Here's the source code for a complete "JFrame size" example, showing how to use this setPreferredSize method call in an actual Java program.

Java: How to create and throw a custom exception

[toc]

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

As a solution, here’s a quick example that shows how to create and throw a custom exception class in Java. In this tutorial I'll demonstrate how to:

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

A Java enum switch/case statement example

Java enum FAQ: Can you share a Java enum switch example, i.e., how to use an enum with a Java switch statement?

In my earlier Java enum examples tutorial, I demonstrated how to declare a simple Java enum, and then how to use a Java enum with a variety of Java constructs, including a Java switch statement, a for loop, and an if/then statement.

Java “file exists” testing

Java file FAQ: How can I test to see if a file or directory exists in Java (or Scala)?

Solution: Use the Java File.exists method. Here’s an example that shows the basic technique:

File tmpDir = new File("/var/tmp");   // create a File object
boolean exists = tmpDir.exists();     // call its 'exists' method

The exists method of the Java File class returns true if the file or directory exists, and false otherwise.

Tomcat connection pool - a Tomcat JNDI DBCP connection pool example

Here's a quick demonstration of how to create a Tomcat connection pool (database connection pool) using the Tomcat DBCP library.

I'm not going to go into a detailed explanation here of how Tomcat DBCP works, other than to say that it works for me, and I've tried to include everything here that you'll need to implement your own Tomcat DBCP database connection pool in your web applications.

Java temporary file: How to create and delete temporary files

Java File I/O FAQ: How do I create a Java temporary file? Also, after I create a temporary file, when is it deleted?

I just ran into this question on the Mac/Java mailing list, so I thought I'd write a quick "Java temporary file" test to explore this. Here are the results.

Java JMX tutorial: A “Hello world” JMX application

Java JMX FAQ: Can you share a simple Java JMX example?

Here is some sample Java source code for some JMX tests that I created recently. I got a large percentage of this code from Sun's JMX MBean tutorial when I first started working with JMX, and I think it's some decent "Hello World" starter code. The main thing I've done here is (a) clarify what they've written and (b) added a shell script to start the JMX application. (I'm also about to publish some other JMX source code that I know I wrote myself.)

The Java ‘keytool’ command, keystore files, and certificates

[toc]

Java keytool/keystore FAQ: Can you share some Java keytool and keystore command examples?

Sure. As a little bit of background, in creating my "Hyde (Hide Your Mac Desktop)" software application, I decided to venture into the world of commercial software, selling my app for a whopping 99 cents. While that price is trivial, creating the “software licensing” code for this application was anything but trivial.

I finally decided to use a Java licensing tool named TrueLicense to assist with the software licensing, and TrueLicense quickly led me down the path of learning about the Java keytool and keystore path. So that’s what this article is about: How to use the Java keytool command to work with private and public keys, and work with intermediate certificate files.

Java enum examples/tutorial (an enum reference page)

[toc]

Java enum 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.

Java: How to list of all the available Java/Swing fonts

Java Fonts FAQ: How do I create a list of all the fonts available on the current platform?

Answer: To list all the fonts available to you in a Java application (a Java Swing application), I use the GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames() method of the GraphicsEnvironment class, which technically returns an array of all the font family names it finds on the local system.

Java memory test - How to consume all the memory (RAM) on a computer

Here’s the source code for a Java “memory eating” program I wrote. Its purpose is to consume all of the memory (RAM) on a PC by allocating 1 MB byte arrays until it runs out of RAM:

import java.util.Vector;

public class MemoryEater
{
  public static void main(String[] args)
  {
    Vector v = new Vector();
    while (true)
    {
      byte b[] = new byte[1048576];
      v.add(b);
      Runtime rt = Runtime.getRuntime();
      System.out.println( "free memory: " + rt.freeMemory() );
    }
  }
}

It’s also important to run this Java memory eating program with the -Xmx option to make sure your JVM gets all the memory you want it to have:

$ java -Xmx1024M MemoryEater

The example shown above will try to consume up to 1,024 MB RAM (1 GB). As I write about in this How to control Java heap size (memory) allocation (xmx, xms) post, you can also specify the Xmx parameter in gigabytes, such as this setting for one gigabyte:

-Xmx1g or -Xmx1G

I wrote a program similar to this when I started getting the Windows blue screen of death several times. I figured there was some type of hardware failure going on, so I tried to consume all the RAM in the system and then read it back in to see if the hardware failure was related to the RAM.