r/javaexamples • • Jan 19 '18

Spring boot login example with JPA

4 Upvotes

Spring boot security example step by step using JPA.

https://www.ashtpoint.com/spring-boot/spring-boot-login-example.html!


r/javaexamples • • Nov 30 '17

Advent of Code - Helper Series: Permutations

4 Upvotes

Advent of Code - Helper Series: Permutations

This is part of a series of code for making your life easier in the yearly Advent of Code competitive coding challenge. It starts every year (since 2015) on December 1st, and posts a new, 2-part challenge every day until Christmas. We don't know what challenges are coming, but based on past years, we can form some idea. I will be posting some of the tools I developed and how to use them.

Permutations

Sometimes, you just have to brute force something. With any set of objects around 10 or less, you can usually get a brute-force solution in reasonable run time. Permutations gives you all possible combinations of a set of things, but remember: things get really, big, really really fast. The number of permutations is the factorial n! so for 3 items, there are only 6. For 9 items, there are 362, 880. For 10 it's over 3 million. But generally the AoC creator has been nice to us, and when the inevitable Travelling Salesman Problem comes, it can usually be brute-forced.

Unlike several programming languages, Java doesn't have a permutations function in it's standard library. So here we go:

Use like:

List<List<Integer>> permutations = Permutations.permuteIntArray(int[] nums);

For a primitive integer array or:

List<List<SomeObject>> permutations = Permutations.permute(SomeObject[] array);

This will give you a list of lists with the permutations like this:

    Integer[] array = { 1 , 2, 3 };
    List<List<Integer>> permutations = Permutations.permute(array);
    System.out.println(permutations);

Will give you:

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

And will work with any object type with a proper equals method.

Here's the code


r/javaexamples • • Feb 16 '17

A simple Stack in under 20 lines of code

4 Upvotes

A Stack is a linked data structure that uses a FIFO (First In - First Out) methodology. It is commonly used as a temporary data structure for processing different types of data.

Just for fun I have tried to boil it down to its absolute simplest form, which only contains 3 methods: push(), pop() and getSize(). Push inserts an item to the head of the stack, and Pop removes the head item from the stack.

Push can be done easily by setting the head variable to a new Node with the data you want to push, and setting the head.next variable to the previous head.

head = new Node(data, head);

Pop is done by setting head equal to head.next, effectively deleting the previous Node, however you need to save the original data element to a temporary variable first so you can return it:

 T t = head.data;
 head = head.next;

To iterate through the stack you would simply:

while (stack.getSize() > 0) {
    System.out.println(stack.pop());
}

Code:

/**
 * @author /u/Philboyd_Studge on 2/15/2017.
 */
public class QuickStack<T> {
    Node head;
    int size;

    class Node {
        T data;
        Node next;
        Node(T data, Node next) {
            this.next = next;
            this.data = data;
        }
    }
    
    int getSize() { return size; }

    void push(T data) {
        head = new Node(data, head);
        size++;
    }

    T pop() {
        if (size == 0) return null;
        T t = head.data;
        head = head.next;
        size--;
        return t;
    }

edit: add a peek() method:

T peek() {
    return head.data;
}

r/javaexamples • • Feb 16 '17

Writing Junit Integration Tests in Spring 4

4 Upvotes

r/javaexamples • • May 23 '15

Using a SQLite Database with Java

4 Upvotes

Using a SQLite Database with Java

Here are some examples on how to create/read from/save to a SQLite database in Java. Most of this is based on this excellent tutorial here, and you can follow the directions there for downloading the driver .jar file.

We will be using my Inventory item class used in other examples here, with a few fields and methods added to it:

Inventory.java

import java.sql.ResultSet;
import java.sql.SQLException;

public class Inventory implements Comparable<Inventory>
{
	private String partnum;
	private String item;
	private String description;
	private int qty;
	private float price;

	// creates a new instance from a result set from a SQL Connection
	public Inventory(ResultSet rs) throws SQLException
	{
		loadFromSQL(rs);
	}

	public Inventory(String partnum, String item, String description, int qty, float price)
	{
		this.partnum = partnum;
		this.item = item;
		this.description = description;
		this.qty = qty;
		this.price = price;
	}

	// make other getters/setters as needed
	public String getItem()
	{
		return item;
	}

	public float getTotal()
	{
		return qty * price;
	}

	public String toString()
	{
		return "===================\nPart #:" + partnum + "\tItem: " + item + "\n" + "Quantity: " + qty + "\n"
					+ "Description: " + description + "\nPrice: " + price + "\n====================\n";
	}

	public String toCSVString()
	{
		return partnum + ", " + item + "," + description + "," + qty + "," + price;
	}

	// creates a String to properly insert the object into the database
	public String getSQLInsert()
	{
		return "INSERT INTO Inventory (partnum, item, description, qty, price)"
				+ "VALUES ('" + partnum + "', '" + item + "', '" + description +
				"', " + qty + "," + price + ");";
	}

	// takes ResultSet from constructor and fills the instance variables
	public void loadFromSQL(ResultSet rs) throws SQLException
	{
        partnum = rs.getString("partnum");
		item = rs.getString("item");
        description = rs.getString("description");
		qty = rs.getInt("qty");
		price = rs.getFloat("price");			
	}

	@Override
	public int compareTo(Inventory obj)
	{
		return this.item.compareTo(obj.getItem());
	}
}

Create Database and Table

Now we need to create the database and table. This program will only need to be executed once.

import java.sql.*;

public class SQLCreateDB
{
	private static Connection connection;
	private static Statement statement;

	public static void main(String[] args)
	{
		// the 'Connection' is used to connect to the database
		connection = null;

		// the 'Statement' sends SQL command statements to the database
		statement = null;

		try
		{
			// Call the JDBC driver at runtime
			// use -classpath ".;sqlite-jdbc-3.8.7.jar" or whatever your version of sqlite is
			Class.forName("org.sqlite.JDBC");

			// connect to database - will create it if it does not exist
			connection = DriverManager.getConnection("jdbc:sqlite:Inventory.db");

			System.out.println("Database connection opened successfully");

			statement = connection.createStatement();

			// SQL statement to create table
			String sql = "CREATE TABLE Inventory (partnum STRING (6)" +  
							"UNIQUE ON CONFLICT FAIL PRIMARY KEY," +
							"item STRING (100), description STRING (250)," + 
							"qty INTEGER (6), price DOUBLE (8, 2));";

			// execute the statement string
			statement.executeUpdate(sql);

			// cleanup
			statement.close();
			connection.close();
		}
		catch ( Exception e)
		{
			System.err.println( e.getClass().getName() + ": " + e.getMessage() );
    		System.exit(0);
		}

		System.out.println("Table created successfully");
	}
}

Add Objects to Table

We will use the two new methods in the inventory class, getSQLInsert(), which creates a proper SQL statement string to perform the insert, and the special constructor that takes the ResultSet and calls 'loadFromSQL()' (See above)

import java.sql.*;
import java.util.ArrayList;

// java -classpath ".;sqlite-jdbc-3.8.7.jar" SQLTest

public class SQLTest
{
	public static ArrayList<Inventory> invList = new ArrayList<>();

	public static void main(String[] args) 
	{
		Connection connection = null;
		try
		{
			// call the JDBC driver at runtime
			Class.forName("org.sqlite.JDBC");

			// create a conection to the database
			connection = DriverManager.getConnection("jdbc:sqlite:Inventory.db");

			System.out.println("Database connection opened successfully");


    		Statement statement = connection.createStatement();

            Inventory newitem = new Inventory("COFMUG", "Coffee Mug", "White, generic coffee mug", 300, 9.99f);
            statement.executeUpdate(newitem.getSQLInsert());

            newitem = new Inventory("BLUHAT", "Blue Hat", "Baseball Cap Size Large, Blue with White piping", 10, 14.95f);
            statement.executeUpdate(newitem.getSQLInsert());

            newitem = new Inventory("COOHAT", "Cool Hat", "Baseball cap, even cooler than the blue ones", 25, 19.99f);
            statement.executeUpdate(newitem.getSQLInsert());

 
      		ResultSet rs = statement.executeQuery( "SELECT * FROM Inventory ORDER BY partnum ASC;" );
    		while (rs.next())
    		{
    			invList.add(new Inventory(rs));
    		}	


		}
		catch ( ClassNotFoundException | SQLException e ) 
		{
      		System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      		System.exit(0);
    	}   

    	for (Inventory each : invList)
    	{
    		System.out.println(each.toString());
    	} 	
	}
}

Output

Database connection opened successfully
===================
Part #:BLUHAT   Item: Blue Hat
Quantity: 10
Description: Baseball Cap Size Large, Blue with White piping
Price: 14.95
====================

===================
Part #:COFMUG   Item: Coffee Mug
Quantity: 300
Description: White, generic coffee mug
Price: 9.99
====================

===================
Part #:COOHAT   Item: Cool Hat
Quantity: 25
Description: Baseball cap, even cooler than the blue ones
Price: 19.99
====================

This just scratches the surface, but should be a good start to learning how to use Java objects with a SQL database. next I will show how to make a simple GUI for this.


r/javaexamples • • May 19 '15

Reverse Digits of Integer

4 Upvotes

Reverse Digits of Integer

This is a popular problem for beginners:

Given an integer n, reverse the digits, for example 123 becomes 321.

Here are a bunch of different ways to accomplish this.

Using String Manipulation

Most people's first idea is to do it this way: Simply convert the int to a String, and reverse it using substring()

public static String reverseString(int n)
{
	// convert to string by concatenation
	String input = "" + n;
	String result = "";

	// count backwards from length of string
	for (int i = input.length(); i > 0; i--)
	{
		//snag one character
		result += input.substring(i - 1, i);

		//or you could say
		// result += input.charAt(i - 1);
	}
	return result;
}

All of these examples will assume the main is something like this:

public static void main( String [] args )
{
	System.out.println(reverseString(12345));
}

I don't really like this way. for example, 100 becomes 001 when, as an integer it should just be 1.

Let's do it using only math:

public static int reverseLooped(int n)
{
	int rev = 0;

	while (n > 0)
	{
		// get rightmost digit
		int digit = n % 10;

		// move last digit read over and add current
		rev = (rev * 10) + digit;

		// chop off right digit
		n = n / 10;
	}
	return rev;
}

The basic idea is that MOD 10 will give you the rightmost digit of an integer, and dividing by 10 will remove that digit. Then you multiply that number by increasing powers of ten, and add to the next digit.

Now, let's take the same idea and use recursion:

public static int reverseRecursive(int n, int r)
{
	if (n==0) return r;
	r = (r * 10) + n % 10;
	return reverseRecursive(n/10, r);
}

This bothers me because of the extra parameter, you have to call it from main like:

	System.out.println(reverseRecursive(12345678, 0));

Another thing we can do is use Math.log10 to get the number of digits of the input number: (In conjunction with Math.floor and Math.pow)

Looping solution using log10:

public static int reverseLog(int n)
{
	int r = 0;
	int d = (int) Math.floor(Math.log10(n));
	for (int i = d; i >= 0; i--)
	{
		r += (n % 10) * ((int)Math.pow(10, i));
		n /= 10;
	}
	return r;
}

...and then recursive (changed to long to handle larger numbers):

public static long reverseLogRecursive(long n)
{
	if (n==0) return 0;
	return ((n % 10) * ((long) Math.pow(10, Math.floor(Math.log10(n))))) 
			+ reverseLogRecursive(n/10);
}

We can combine Strings and math for a really simple recursive function:

public static String reverseStringRecursive(int n)
{
	if (n==0) return "";
	return (n % 10) + reverseStringRecursive(n/10);
}

Which you could use with a helper function to return an integer value:

public static int reverseRecursive(int n)
{
	return Integer.parseInt(reverseStringRecursive(n));
}

public static String reverseStringRecursive(int n)
{
	if (n==0) return "";
	return (n % 10) + reverseStringRecursive(n/10);
}

can anyone come up with other solutions?


r/javaexamples • • May 07 '15

Hello, World!

4 Upvotes

public class HelloWorld{

  public static void main(String[] args){

  //prints "Hello, World!" to the console.
     System.out.println("Hello, World!");

  }

}


r/javaexamples • • Apr 27 '15

How to properly compare Strings in Java

4 Upvotes

Simple answer:

Don't use "==" or "!=", use .equals() or .equalsIgnoreCase().

Explanation:

In Java, Strings are Objects, not (as commonly assumed, or as in other languages) primitive types.

For Objects, "==" compares the Object references (pointers to the memory locations of the actual objects), not the contents.

So, to compare Object contents, the special .equals(), or .equalsIgnoreCase() methods need be used. Same applies for greater/less than comparisons, here the .compareTo() (or .compareToIgnoreCase()) method needs be used.

Another caveat with using the .equals() (or .equalsIgnoreCase() methods is a null String (i.e. a String variable that has never been assigned any value). Trying to compare a null String results in a NullPointerException.

The following results in a NullPointerException:

String test;
if (test.equals("Hello")) { // This line will produce a NullPointerException as the String has not yet been assigned a value
    // continue code here
}

The same situation as above, but with Yoda code testing:

String test;
if ("Hello".equals(test)) { // No NullPointerException here as "Hello" is a valid String
    // continue code here
}

Therefore it is common to either test the String against being null (!=null or ==null), or to use "Yoda code", i.e. putting the String literal (the constant String between the "") up front.

So, instead of writing:

if (answer.equals("n")) {

it is common to use:

if ("n".equals(answer)) {

If the case (upper/lower/mixed) does not matter, it's always better to use .equalsIgnoreCase() to avoid unnecessary or joins:

if("n".equalsIgnoreCase(answer)) {

r/javaexamples • • May 25 '25

[Java] Built a High-Performance File Processor With Multi-threading, Backpressure, and Stats Export šŸ“Š

3 Upvotes

Hey performance heads – I just launched a Java lib for parallel file processing called SmartFileProcessor.

⚔ Highlights:

  • Parallel batch processing with custom thread pools

  • BlockingQueue with backpressure for safe producer-consumer flow

  • Buffered writing with configurable flush thresholds

  • Built-in stats reporter: per-thread operation timings, memory, batch counters

  • Export stats to JSON or CSV – great for profiling

Example Use Cases:
ā˜‘ Processing large log files
ā˜‘ Preprocessing for data ingestion pipelines
ā˜‘ ETL batch jobs in Java microservices

šŸ”— GitHub: https://github.com/MayankPratap/Samchika
Would appreciate your thoughts, perf tips, or ways to break it! šŸ”

#java #concurrency #threading #fileio #perfmatters


r/javaexamples • • Sep 02 '24

OpenFGA for Spring Boot applications

3 Upvotes

How to add Fine-Grained Authorization (FGA) to a Spring Boot API using the OpenFGA Spring Boot starter.

Read more…


r/javaexamples • • Aug 27 '24

3 ways to parse JSON in Java?

3 Upvotes

You got a JSON string from API and want to parse? Well, there are many options in Java, from simply getting key value to converting it into an object, I have shared 3 of most common of them using Jackson, Gson and Json simple

https://javarevisited.blogspot.com/2022/03/3-examples-to-parse-json-in-java-using.html


r/javaexamples • • Jan 07 '23

Decompile Java JAR using JD-GUI tutorial for beginners

3 Upvotes

Screen recording about how to use the JD-GUI Java decompiler https://www.youtube.com/watch?v=HXgZZz3M3sQ


r/javaexamples • • Jul 12 '21

How to use Jshell ( Java shell tool) ?

3 Upvotes

Jshell is a great tool to explore large code bases and try out snippets. It is available from JDK 9 and learning to use it will definitely improve productivity.

A lot of folks are using JDK 8 (mostly) but this shouldn't stop anyone from using Jshell. It is a great tool to have in one's arsenal.

How to use Jshell ( Java shell tool )


r/javaexamples • • Apr 09 '20

How to secure and test java rest API with keycloak

3 Upvotes

r/javaexamples • • Sep 18 '19

[Article] Learn to avoid repetitive boilerplate codes using Project Lombok

3 Upvotes

Wrote an article on how project Lombok helps in reducing the boilerplate code, please share your feedback on this. Thought this will be helpful to java programmers.

https://jstobigdata.com/java/introduction-to-project-lombok


r/javaexamples • • Aug 21 '19

Simple Guide to Spark Framework for Microservices

3 Upvotes

We have discussed the Microservices concepts like What are Microservices? Why to use it? When to use it? in our previous article ā€ An Introduction to Microservices Architectureā€

Every modern enterprise application is supported by microservices. These services form the core of the application. To develop these services fast we need an easy and simple framework. In this article, we will have a brief introductionĀ to Spark Framework.

https://www.opencodez.com/java/spark-framework-for-microservices.htm


r/javaexamples • • Jul 25 '19

Java Behavioral Design Patterns - Iterator Design Pattern

3 Upvotes

Iterator Design Pattern is one of the Behavioural design patterns in Java. It is used for traversing through the collection of data in a particular class.

This pattern hides the actual implementation of traversal through the collection. TheĀ application programs just use iterator methods for different purposes.Ā Iterator pattern allows accessing the elements of a collection object in a sequential manner without knowledge of its structure. Key points to remember about this interface are:

  • This pattern is used when you foresee a collection is traversed with different types of criteria.

  • The collection object should be accessed and traversed without exposing itsĀ data structure.

  • New traversal operations should be defined for collection object without changing its interface.

https://www.opencodez.com/java/iterator-design-pattern.htm


r/javaexamples • • Jun 14 '19

Simple and Easy way to Upload and Download Files in Java with Spring Boot - Source Code on GitHub

3 Upvotes

r/javaexamples • • May 12 '19

Java Concurrency API - Phaser

3 Upvotes

Java concurrency API - Phaser

Java Phaser with Examples


r/javaexamples • • Sep 20 '18

Static Block in Java | Example Program & Advantage

3 Upvotes

r/javaexamples • • May 28 '18

I Created a Basic AI in Java (on GitHub!)

Thumbnail
self.learnjava
3 Upvotes

r/javaexamples • • Dec 01 '17

Advent of Code - Helper Series: Tuples

3 Upvotes

Advent of Code - Helper Series: Tuples

This is part of a series of code for making your life easier in the yearly Advent of Code competitive coding challenge. It starts every year (since 2015) on December 1st, and posts a new, 2-part challenge every day until Christmas. We don't know what challenges are coming, but based on past years, we can form some idea. I will be posting some of the tools I developed and how to use them.

Tuples

If you have used Python at all, you will know one of the handiest things it has are tuples, a data structure that holds 2 object, of different or the same types. This is handy in many situations, especially if you need to return more than one item from a method.

In java, we can't do the slick indexing stuff that python lets you do with tuples, but we can at least set up a very simple class to approximate them.

I have set up 2 classes, Tuple2 and Tuple3. These are immutable objects, and cannot be altered once created. They can have either different or the same object types.

Use like:

Tuple2<String, Integer> tuple = new Tuple2<>( "farts", 12345);

Use the methods getFirst() and getSecond() to retrieve the values.

Equals and Hashcode have been overridden.

That's all there is to it, very simple but saves you the time if you need it.

I have also implemented a simple zip method, similar to python. This takes two arrays, and zips them together, adding the items at each index to a tuple, up to the index of the shortest array, and then returns a List of tuples with those items.

So, to use:

    String[] a = { "1", "poop", "farts"};
    Integer[] b = { 4, 5};

    List<Tuple2<String, Integer>> zipped = Tuple2.zip(a, b);
    System.out.println(zipped);

will return

[{ 1, 4 }, { poop, 5 }]

I have also included a Tuple3 class, which does the same but also has a third object.

Tuple2.java

Tuple3.java


r/javaexamples • • Aug 24 '17

Java 8 Streams Cookbook

3 Upvotes

Ive been experimenting with the tech.io site which lets you create executable code tutorials -

https://tech.io/playgrounds/3312/java-8-streams-cookbook/streams-cookbook

I like the approach, and am looking for feedback whether people like this style of tutorial


r/javaexamples • • Jun 19 '17

4 Ways To Control Access to Spring Data REST

3 Upvotes

This is my latest post on Spring Data REST -

https://www.javabullets.com/4-ways-to-control-access-to-spring-data-rest/

Let me know any feedback


r/javaexamples • • May 05 '17

How to handle Byte order mark in Java file

3 Upvotes

Recently I came in to a situation to handle Byte order mark in Java file.While opening and checking file everything was ok, however when we were processing these file through our program, we were getting some strange char set at the beginning of the file.

This is how I handled it in my code using org.apache.commons.io.input.BOMInputStream

FileInputStream fis = new FileInputStream("/filewithBOMData.csv");

BOMInputStream bomIn = new BOMInputStream(fis);
if(bomIn.hasBOM()){  		
		
   //work to do
}

Apache Commons IO BOMInputStream provide efficient way to detect BOM in file along with ability to optionally exclude it.

More can be found here BOMInputStream

You can also use this small utility in place of Apache Commons UnicodeBOMInputStream

Hope this will be helpful!!