Java Code Snippets

Below are some useful Java code snippets for use in everyday projects.

Here is an example of how to generate a random number between two values, in this case 1 and 59, then display it.

public class Demo {

    public static void main(String[] args) {

        //  Minimum and maximum values for random number.
        int minVal = 1;
        int maxVal = 59;

        // Generate random number.
        int randomNumber =
                (int)Math.floor(Math.random() * (maxVal - minVal + 1) + minVal);

        // Display the result in the console.
        System.out.println(randomNumber);

    }

}

Here, a random password is generated from a specified set of characters. The length of the password is also randomly selected from a given minimum and maximum length.

public class Demo {

    public static void main(String[] args) {

        // Possible characters in password.
        String alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String numbers = "0123456789";
        String nonAlpha = "{]+-[*=@:)}$^%;(_!&#?>/|.";

        // Combine possible password characters into a single string.
        String charSet = alpha + numbers + nonAlpha;

        // Minimum and maximum password length.
        int minLength = 20;
        int maxLength = 30;

        // Select a random password length between the minimum and maximum.
        int length =
                (int)Math.floor(Math.random() * (maxLength - minLength + 1) + minLength);

        // Variable for new password.
        String result = "";

        // Construct new password.
        for (int i = 1; i <= length; i++)
        {

            // Add a randomly selected character to the new password.
            result += charSet.charAt((int)Math.floor(Math.random() *
                        ((charSet.length()-1) + 1) + 0));

        }

        // Display the password.
        System.out.println(result);

    }

}