Posts in the “java” category

A simple Java JDBC example that shows SQL insert, update, delete, and select

As a little tip today, here’s a short Java/JDBC example program where I show how to perform SQL SELECT, INSERT, UPDATE, and DELETE statements with JDBC:

package com.devdaily.sqlprocessortests;

import java.sql.*;

public class BasicJDBCDemo
{
  Connection conn;

  public static void main(String[] args)
  {
    new BasicJDBCDemo();
  }
 
  public BasicJDBCDemo()
  {
    try
    {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      String url = "jdbc:mysql://localhost/coffeebreak";
      conn = DriverManager.getConnection(url, "username", "password");
      doTests();
      conn.close();
    }
    catch (ClassNotFoundException ex) {System.err.println(ex.getMessage());}
    catch (IllegalAccessException ex) {System.err.println(ex.getMessage());}
    catch (InstantiationException ex) {System.err.println(ex.getMessage());}
    catch (SQLException ex)           {System.err.println(ex.getMessage());}
  }

  private void doTests()
  {
    doSelectTest();

    doInsertTest();  doSelectTest();
    doUpdateTest();  doSelectTest();
    doDeleteTest();  doSelectTest();
  }

  private void doSelectTest()
  {
    System.out.println("[OUTPUT FROM SELECT]");
    String query = "SELECT COF_NAME, PRICE FROM COFFEES";
    try
    {
      Statement st = conn.createStatement();
      ResultSet rs = st.executeQuery(query);
      while (rs.next())
      {
        String s = rs.getString("COF_NAME");
        float n = rs.getFloat("PRICE");
        System.out.println(s + "   " + n);
      }
    }
    catch (SQLException ex)
    {
      System.err.println(ex.getMessage());
    }
  }

  private void doInsertTest()
  {
    System.out.print("\n[Performing INSERT] ... ");
    try
    {
      Statement st = conn.createStatement();
      st.executeUpdate("INSERT INTO COFFEES " +
                       "VALUES ('BREAKFAST BLEND', 200, 7.99, 0, 0)");
    }
    catch (SQLException ex)
    {
      System.err.println(ex.getMessage());
    }
  }

  private void doUpdateTest()
  {
    System.out.print("\n[Performing UPDATE] ... ");
    try
    {
      Statement st = conn.createStatement();
      st.executeUpdate("UPDATE COFFEES SET PRICE=4.99 WHERE COF_NAME='BREAKFAST BLEND'");
    }
    catch (SQLException ex)
    {
      System.err.println(ex.getMessage());
    }
  }

  private void doDeleteTest()
  {
    System.out.print("\n[Performing DELETE] ... ");
    try
    {
      Statement st = conn.createStatement();
      st.executeUpdate("DELETE FROM COFFEES WHERE COF_NAME='BREAKFAST BLEND'");
    }
    catch (SQLException ex)
    {
      System.err.println(ex.getMessage());
    }
  }
}

This code is taken from this Simple JDBC Example on an older version of my website. I’m including it here so I can search for it more easily.

The database that this code uses is the Coffee Break database from Sun’s original JDBC tutorial.

Java: How to perform a case-insensitive search using the String ‘matches’ method

Problem: In a Java program, you want to determine whether a String contains a pattern, you want your search to be case-insensitive, and you want to use String matches method than use the Pattern and Matcher classes.

Solution: Use the String matches method, and include the magic (?i:X) syntax to make your search case-insensitive. (Also, remember that when you use the matches method, your regex pattern must match the entire string.)

Java instanceof interface example

Java instanceof FAQ: How does the Java instanceof operator work with a Java Interface?

The instanceof operator supports inheritance, which I can demonstrate through a simple "instanceof interface" example.

A Java “instanceof null” example

You might think that when the Java instanceof operator is used to test a null reference, such as a null reference to a String, instanceof would realize that even though the reference is currently null, it is a reference to a String, so you might expect instanceof to return true ... but it doesn't.

Java file open, read, and write utilities

Java file utilities FAQ: Do you have any Java file utilities you can share?

As I was working on another Java/Swing application this weekend, I ran across my "Java file utilities" class, and I thought I'd share that class here today. It's nothing too major, but it does include Java methods that let you open, read, write, and copy files using Java.

How to iterate (loop) over the elements in a Map in Java 8

If you need to iterate over the elements in a Map in Java 8, this source code shows how to do it:

Map<String, String> map = new HashMap<String, String>();
map.put("first_name", "Alvin");
map.put("last_name",  "Alexander");

// java 8
map.forEach((k,v)->System.out.println("key: " + k + ", value: " + v));

Java: How to get an image off the system clipboard

Java clipboard FAQ: How do I get an image off the clipboard using Java?

I guess timing is everything ... I just received this Java clipboard question as I am working on a Java Swing application that does a lot of graphics and image work, so I have a little source code here I can share.

AlPad - A simple “scratchpad” editor

Over the course of a few hours this past week I created a little “scratchpad” text editor I named AlPad. It’s gone through several names, but since I’m just writing it for me, the name seems appropriate.

It’s not really correct to call AlPad an “editor”; it’s really just an app where I can keep a collection of miscellaneous notes I usually make when I’m working. It has very few features, just some ones I want and can implement easily:

Java/Scala: How to determine the monitor sizes of multiple displays

Note: This code is currently a work in progress. I know of possible approaches, but I don’t know of a perfect working solution yet.

I’m currently trying to find the right way to find the current monitor size, when you’re writing a Java Swing application to work in a multiple-monitor configuration. I always use three monitors, so I can test this pretty easily.

Java: Examples of the Java list/array `subList` method (list subset)

As a little note today, if you ever need to extract a subset of a Java list or array, here are some examples of the Java subList method:

import java.util.*;

public class SubList {

    public static void main(String[] args) {

        List<String> x = new ArrayList<>();
        x.add("a");
        x.add("b");
        x.add("c");
        x.add("d");
        x.add("e");

        // `subList(int fromIndex, int toIndex)`
        // array indexes start at 0.
        // 1st arg is inclusive (included), 2nd arg is exclusive (not included).
        List a = x.subList(0,1);  // [a]
        List b = x.subList(0,2);  // [a, b]
        List c = x.subList(0,4);  // [a, b, c, d]      # same as `x.subList(0,x.size()-1)`
        List d = x.subList(0,5);  // [a, b, c, d, e]   # same as `x.subList(0,x.size())`
        List e = x.subList(0,6);  // IndexOutOfBoundsException
        List f = x.subList(1,1);  // f []
        List g = x.subList(1,2);  // g [b]
        List h = x.subList(2,5);  // h [c, d, e]
        
    }
}

If you print the results of each line you’ll see the results on the right side of the comments. As shown:

  • The first element in a list or array is at index 0
  • The toIndex is exclusive, meaning it won’t be included in the results
  • If you go outside the size of the initial list, you’ll get an IndexOutOfBoundsException
  • The original list isn’t modified; if you print x, you’ll see that it still includes all of the original elements

If you ever need to extract a subset of a Java list or array into another list or array, I hope these Java subList examples are helpful.

A Java “Extract Interface” refactoring example

Java Refactoring FAQ: Can you provide an example of the Extract Interface refactoring process?

While working on a Java Swing development project recently, I had written a couple of controllers (as in controllers from the Model/View/Controller pattern), and I was about to write some more, when I realized that if I refactored my Java source code I would have a much better design -- source code I code more easily maintain.

The pattern I saw repeated in my Java controller classes was that they all had similar method names, something like this:

Java compile FAQ: How to compile a Java program

Java compile FAQ: How do I compile my first Java program?

To compile a Java program you first need to download a Java development kit (see java.sun.com) if you don't already have one. Next, assuming you have a program named MyProgram.java that you want to compile, you compile it like this with the javac:

javac MyProgram.java

Assuming that there are no errors, this will create a file named MyProgram.class. This file contains the Java bytecode representing the instructions of your program.