6 Useful Java Snippets

December 5th, 2012 Leave a comment 1 comment
Like the article?
6 useful Java Snippets

Sometimes it’s not worth reinventing the wheel and trying to remember the way you did something last time around. It’s also true that sometimes you have simple tasks that you simply can’t figure out how to get done- or, even worse, you That said, here are some really useful Java code snippets that you can use and reuse to help make some tasks that you’re doing often a bit easier!

1. Converting Strings to ints and ints to Strings

Here’s a handy little string converter that you can use to turn strings to ints and vice versa!

int y = 10;
String x = String.valueOf(y); // int to string
int z = Integer.parseInt(x); // string to int

2. Getting the Current Method Name

Sometimes you need to find out the name of the method you’re currently using. Here’s a handy way to do so!

String name = Thread.currentThread().getStackTrace()[1].getMethodName();

3. Convert A String To Date

Quite often you’ll need to convert a string date into a Date variable. Here’s a quick way of doing so with SimpleDateFormat!

String dateString = "July 1st, 2009";
Date dateVar = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
System.out.println(dateVar); 

4. Take A Screen Shot

Here’s how to take a screen shot in Java- useful if you want to pop a screenshot button in somewhere!

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.awt.Toolkit;

public void takeScreenshot(String file) throws Exception {
    Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
    Rectangle rect = new Rectangle(size);
    Robot robot = new Robot();
    BufferedImage image = robot.createScreenCapture(rect);
    ImageIO.write(image, "png", new File(fileName));
}

5. Get A Directory Listing

Sometimes you need to get a directory listing, and you’re not entirely sure how to get one. Here’s a way to get a directory listing in Java!

File directory = new File("directoryName");
String[] subdirs = dir.list();

for (int x = 0; x < subdirs.length; x++) {
    String filename = subdirs[x];
}

6. Generic Static Initializer

Sometimes you need a generic static initializer, but you don’t want to write one yourself. Here’s a generic snippet to help you build up faster!

public class MyClass {
    public static String[] strings;
    public static int index = 100;

    static {
        strings = new String[index]; 

        for (int x = 0; x < index - 1; x++) {
            strings[x] = null;
        }
    }
}

Conclusion

Writing code is as much being smart as it is being inspired. These code snippets here are all functions you might find yourself using in many different applications, and hopefully they’ll help you to make your code writing process faster and easier!

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
If you liked this article, consider enrolling in one of these related courses:
Don't miss another post! Receive updates via email!
  1. Eric Jablow says:

    In Java 7, the directory listing task becomes:
    Path dir = …
    try (DirectoryStream stream = Files.newDirectoryStream(dir)) {
    for (Path entry: stream) {
    // Do something with entry.
    }
    }

    This uses try-with-resources and the new classes in java.nio.file, Files, Path, and DirectoryStream.

Comment