How do I append data to a text file?

One of the common task related to a text file is to append or add some contents to the file. It’s really simple to do this in Java using a FileWriter class. This class has a constructor that accept a boolean parameter call append. By setting this value to true a new data will be appended at the end of the file when we write a new data to it.

Let’s see an example.

package org.kodejava.io;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class AppendFileExample {
    public static void main(String[] args) {
        File file = new File("user.txt");

        try (FileWriter writer = new FileWriter(file, true)) {
            writer.write("username=kodejava;password=secret" + System.lineSeparator());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I change the cursor shape in Swing?

Using the following code snippet you can change the shape of mouse cursor in your Java Swing desktop application. The cursor is represented by the java.awt.Cursor class. Create an instance of Cursor using the new operator and pass the cursor type to the Cursor class constructor.

We can change Swing’s objects (JLabel, JTextArea, JButton, etc) cursor using the setCursor() method. In the snippet below, for demonstration, we change the cursor of the JFrame. Your mouse pointer or cursor shape will be changed if you positioned inside the frame.

A collections of cursor shape defined in the java.awt.Cursor class, such as:

  • Cursor.DEFAULT_CURSOR
  • Cursor.HAND_CURSOR
  • Cursor.CROSSHAIR_CURSOR
  • Cursor.WAIT_CURSOR
  • etc
package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Cursor;

public class ChangeCursor extends JFrame {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ChangeCursor frame = new ChangeCursor();
            frame.setTitle("Change Cursor");
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setSize(500, 500);

            // Here we create a hand shaped cursor!
            Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
            frame.setCursor(cursor);
            frame.setVisible(true);
        });
    }
}

What’s needed to be prepared for learning Java programming?

At the time you decided to start to learn Java Programming you can start by downloading the Java Development Kit (JDK) from Java Download website. There are three different types of JDK, the Java SE (Java Standard Edition), Java EE (Java Enterprise Edition), Java ME (Java Mobile Edition).

From the website you can also download the Java API documentations which will sure be your first companion when learning the language. It is better also to download the Java Tutorial Series that was written by the Java experts.

In the tutorial you can learn from the basic of Java programming, introduction of the fundamental of Object-Oriented Programming (OOP) which is Java all about. Next you can also find trails in each subject of the API (Application Programming Interface) provided by Java library, such as the core package, how to communicate with a database, Java GUI programming, image manipulation, RMI, Java Beans Framework, etc.

When you want to write a code, you might wonder what editor or IDE you will need to use to start learning. A good text editor that supports a coloring will be a good candidate, colorful screen is better than just a black and white, isn’t it?

There are a lot of good text editor available today such as the VIM, NotePad++, TextPad, Editplus, UltraEdit. If you already have your preferred editor, you can use it of course.

If you’re ready for the big stuff, a bigger homework project, you might consider using an IDE (Integrated Development Environment) as you’ll be working with lots of Java classes, configuration files and build script for examples. There are many great IDE on the Java world from the free to the commercial product.

What IDE to use is really a developer decision, use whatever tools that can help you to improve your learning and programming activities. You can find IDE such as NetBeans, Eclipse, IntelliJ IDEA, etc.

Beside learning from the Java tutorials there are also many forums on the internet where you can discuss your doubts or your problems. Forums like JavaRanch, Stack Overflow are great forums with Java gurus that can help you to clarify your doubts and help you to solve your problem. Remember one thing when you ask for help, be polite, elaborate your problem clearly.

Good Java books on your desktop are good resources to study Java, from good books you can learn the nuts and bolts of the Java programming languages. When you have all your arsenal you can get the best out of you in learning Java. Have fun!

How do I delete record from a table?

In this example we are showing you how to delete a record from table in the database. We use a standard JDBC library for this purpose. For the database we use MySQL, you can use any type of database you want. All you need to do is to find the JDBC driver for the database and configure it accordingly.

So here is the code example for deleting records from a table in a database.

package org.kodejava.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DeleteRecordExample {

    public static void main(String[] args) {
        // This is our connection url to MySQL database, where jdbc is the
        // prefix for all jdbc connection. The mysql sub telling that we
        // are using MySQL database. Localhost is where our database is
        // resided and kodejava is our database name.
        String url = "jdbc:mysql://localhost/kodejava";

        // To connect to a database we will need a username and a password
        // for the database server to allow us to manipulate its data.
        String username = "kodejava";
        String password = "s3cr*t";

        // Then we ask a connection from the DriverManager by passing
        // the connection URL, the username and the password.
        try (Connection connection =
                     DriverManager.getConnection(url, username, password)) {

            // To delete records from tables we create an SQL delete command.
            // The question mark that we used in the where clause will be the
            // holder of value that will be assigned by PreparedStatement
            // class.
            String sql = "DELETE FROM book WHERE isbn = ?";
            String isbn = "9781617294945";

            // Create a statement object. We use PreparedStatement here.
            PreparedStatement statement = connection.prepareStatement(sql);

            // Pass a value of an ISBN that will tell the database which
            // record in the database to be deleted. Remember that when
            // using a statement object the index parameter is start from
            // 1 not 0 as in the Java array data type index.
            statement.setString(1, isbn);

            // Tell the statement to execute the command. The executeUpdate()
            // method for a delete command returns number of records deleted
            // as the command executed in the database. If no records was
            // deleted it will simply return 0
            int rows = statement.executeUpdate();

            System.out.println(rows + " record(s) deleted.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Maven dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I reverse a string?

Below is an example code that reverse a string. In this example we use StringBuffer.reverse() method to reverse a string. In Java 1.5, a new class called StringBuilder also has a reverse() method that do just the same, one of the difference is StringBuffer class is synchronized while StringBuilder class is not.

And here is the string reverse in the StringBuffer way.

package org.kodejava.lang;

public class StringReverseExample {
    public static void main(String[] args) {
        // The normal sentence that is going to be reversed.
        String words =
                "Morning of The World - The Last Paradise on Earth";

        // To reverse the string we can use the reverse() method in
        // the StringBuffer class. The reverse() method returns a
        // StringBuffer so we need to call the toString() method to
        // get a string object.
        String reverse = new StringBuffer(words).reverse().toString();

        // Print the normal string
        System.out.println("Normal : " + words);
        // Print the string in reversed order
        System.out.println("Reverse: " + reverse);
    }
}

Beside using this simple method you can try to reverse a string by converting it to character array and then reverse the array order.

And below is the result of the code snippet above.

Normal : Morning of The World - The Last Paradise on Earth
Reverse: htraE no esidaraP tsaL ehT - dlroW ehT fo gninroM