r/javaexamples • • Oct 22 '19

Java Creational Design Patterns – Prototype Pattern with Sample Code

2 Upvotes

Prototype pattern comes under creational design pattern. As we know, in Java object creation process is time consuming and costly, so instead of creating object every time we can create copy of existing object. So using this design pattern we can create object in easiest way. In prototype pattern object cloning is used to create object copies, which is implemented using clone() method.

You can use this pattern if any of the below point applies-

  • the client application wants to avoid subclasses of an object creator

  • in your application you find using ‘new’ keyword to create object pretty expensive.

Prototype pattern doesn’t create new object it just create clone of it. It takes all the necessary data and stored data in memory and whenever new object is required, prototype pattern creates clone of the object and can be customized later.

Prototype Pattern by Example

https://www.opencodez.com/java/prototype-pattern.htm


r/javaexamples • • Feb 11 '22

3 ways to convert String to JSON object in Java? Examples

2 Upvotes

r/javaexamples • • May 11 '22

Quiz #1

2 Upvotes
  1. Which of the following are true statements? (Choose all that apply.)

60 votes, May 12 '22
1 Java allows operator overloading.
9 Java code compiled on Windows can run on Linux.
0 Java has pointers to specific locations in memory.
0 Java is a procedural language.
50 Java is an object-oriented language.
0 Java is a functional programming language.

r/javaexamples • • May 12 '22

which one of the following topics would you like to see a video on

0 Upvotes
7 votes, May 13 '22
1 How to create a jar file in eclipse
3 How to create a jar file from java console
3 How to compile and run code from java console

r/javaexamples • • May 25 '22

Method Overloading in Java

2 Upvotes

A new video on Method Overloading is out now!!!. You can check it out here:


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 • • Feb 17 '17

Spring Boot Thymeleaf Integration Example

3 Upvotes

r/javaexamples • • Jun 14 '15

Simple Stack and Queue

3 Upvotes

Simple Stack and Queue

Two common implementations of Linked Lists are the Stack and the Queue. The main difference is that a Stack is LIFO - Last In, First Out (Picture a waiting line for an ATM), and a Stack is FIFO - First In, First Out (Picture a stack of plates in the sink).

They are both already available as implementations of LinkedList in java.util, but for educational purposes, we will be making them from scratch.

Both use the same inner class for Node:

/**
 * Inner Node Class
 */
class Node
{
	E value;
	Node next;

	public Node(E value, Node next)
	{
		this.value = value;
		this.next = next;
	}

	@Override
	public String toString()
	{
		return this.value + " ";
	}
}

The Stack

The Stack has three main methods: push(), pop() and peek():

  • push() places a new element at the top of the stack.

  • pop() removes and returns the element at the top of the stack,

  • peek() returns the top element without removing it.

The rest of the methods will be the same for both implementations:

  • clear() clears the list

  • isEmpty() true if list is empty

  • size() number of elements in the list

Here is the code for Stack:

import java.util.NoSuchElementException;

/**
 * Simple Stack
 * @author /u/Philboyd_Studge
 */
public class Stack<E>
{
	private Node root;
	private int length;

	/**
	 * Default - Create empty Stack
	 */
	public Stack()
	{
		root = null;
		length = 0;
	}

	/**
	 * @return length number of elements in the Stack
	 */
	public int size()
	{
		return length;
	}

	/**
	 * @return true if empty
	 */
	public boolean isEmpty()
	{
		return (root==null);
	}

/**
 * 
 */
public void clear()
{
	root = null;
	length = 0;
}
    
	/**
	 * Push an element E onto top of stack
	 * @param value element of type E to be pushed
	 */
	public void push(E value)
	{
		Node node = new Node(value, root);
		root = node;
		length++;
	}

	/**
	 * Pop the top value off of the stack and remove it
	 * @return E element of type E
	 */
	public E pop()
	{
		if (root==null) throw new NoSuchElementException("List is empty.");
		E value = root.value;
		root = root.next;
		length--;
		return value;
	}

	/**
	 * return the element from the top of the stack without removing it
	 * @return E element of type E
	 */
	public E peek()
	{
		if (root==null) throw new NoSuchElementException("List is empty.");
		return root.value;
	}

	/**
	 * Inner Node Class
	 */
	class Node
	{
		E value;
		Node next;

		public Node(E value, Node next)
		{
			this.value = value;
			this.next = next;
		}

		@Override
		public String toString()
		{
			return this.value + " ";
		}
	}

	public static void main(String[] args)
	{
		try
		{
			// test with Integers
			Stack<Integer> s = new Stack<>();
			s.push(34);
			s.push(23);
			s.push(12);
			s.push(99);

			System.out.println(s.pop());
			System.out.println(s.peek());
			System.out.println(s.pop());

			while (!s.isEmpty())
			{
				System.out.println(s.pop());
			}

			// test with objects
			Stack<Person> people = new Stack<>();
			people.push(new Person("Bob jones", 34));
			people.push(new Person("Wilma Flintstone", 999));
			people.push(new Person("Adam West", 69));

			while (!people.isEmpty()) System.out.println(people.pop());

			// throw exception on purpose
			System.out.println(people.peek());
		}
		catch (NoSuchElementException e)
		{
			System.out.println(e.getClass() + " : " + e.getMessage());
		}


	}
}

The Queue

The three main methods of a Queue are add(), poll(), and peek():

  • add() adds a new element to the end of the queue

  • poll() returns and removes the element at the head of the queue

  • peek() returns the element at the head of the queue without removing it.

Here is the code for the Queue:

import java.util.NoSuchElementException;

/**
 * Simple Queue
 * @author /u/Philboyd_Studge
 */
public class Queue<E>
{
	private Node root;
	private Node end;
	private int length;

	/**
	 * Default - create empty Queue
	 */
	public Queue()
	{
		root = null;
		end = null;
		length = 0;
	}

	/**
	 * @return length number of elements E in Queue
	 */
	public int size()
	{
		return length;
	}

	/**
	 * @return true if empty
	 */
	public boolean isEmpty()
	{
		return (root==null);
	}

	/**
	 * 
	 */
	public void clear()
	{
		root = null;
		length = 0;
	}

	/**
	 * @param value element of type E
	 */
	public void add(E value)
	{
		if (root==null)
		{
			// first node
			root = new Node(value, null);
			end = root;
		}
		else
		{
			Node node = new Node(value, null);
			// link current end node to new node
			end.next = node;
			// make new node end node
			end = node;
		}
		length++;
	}

	/**
	 * Remove and return first element in queue
	 * @return E element of type E
	 */
	public E poll()
	{
		if (root==null) throw new NoSuchElementException("List is empty");
		E value = root.value;
		root = root.next;
		length--;
		return value;
	}

	/**
	 * Return first element in queue without removing it
	 * @return E element of type E
	 */
	public E peek()
	{
		if (root==null) throw new NoSuchElementException("List is empty");
		return root.value;
	}

	/**
	 * Inner Node Class
	 */
	class Node
	{
		E value;
		Node next;

		public Node(E value, Node next)
		{
			this.value = value;
			this.next = next;
		}

		@Override
		public String toString()
		{
			return this.value + " ";
		}
	}

	public static void main(String[] args)
	{
		try
		{
			// test with integers
			Queue<Integer> s = new Queue<>();
			s.add(34);
			s.add(23);
			s.add(12);
			s.add(99);

			System.out.println(s.poll());
			System.out.println(s.peek());
			System.out.println(s.poll());

			while (!s.isEmpty())
			{
				System.out.println(s.poll());
			}

			// test with objects
			Queue<Person> people = new Queue<>();
			people.add(new Person("Bob jones", 34));
			people.add(new Person("Wilma Flintstone", 999));
			people.add(new Person("Adam West", 69));

			while (!people.isEmpty()) System.out.println(people.poll());

			// throw exception on purpose
			System.out.println(people.poll());
		}
		catch (NoSuchElementException e)
		{
			System.out.println(e.getClass() + " : " + e.getMessage());
		}
	}
}

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 • • 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 • • May 12 '19

Java Concurrency API - Phaser

3 Upvotes

Java concurrency API - Phaser

Java Phaser with Examples


r/javaexamples • • Feb 17 '19

Do you think you know about java operators then watch this

4 Upvotes

Hey guys,

We all study syntax of different programming language but most of the time we just go through some tutorial and we will just start coding.

Even for simple operators in java we may face difficult to answer some questions.

So, this is a collection of such questions where you can really check your knowledge about operators in java.

Hope you guys will like it.

https://youtu.be/YLFQdWid0Zc


r/javaexamples • • Sep 12 '20

Is Varargs a datatype in java? | Varargs vs Array | JavaBeam |

0 Upvotes

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 26 '19

Java 12's Switch Expression

4 Upvotes

Java 12 Switch Expression with Code Examples

Java 12 Switch Expression


r/javaexamples • • Aug 28 '24

10 Examples of ArrayList in Java

4 Upvotes

ArrayList is an important class and every Java developer should be aware of. Here are 10 examples of ArrayList in Java to learn this class better https://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html


r/javaexamples • • Jul 21 '19

Top 5 Frameworks for Java Developers in 2019

5 Upvotes

Java is one of the widely used programming languages. There are many useful Java frameworks available to write any Java-based web and mobile apps, REST APIs and Microservices easily.

Frameworks are useful to focus on the main business logic of an application instead of writing other basic functionalities from scratch. These frameworks let you start a project easily and quickly. Java frameworks are available for both frontend and backend. Front end frameworks are for dealing with UI functionalities and backend frameworks are for server-side tasks.

There are plenty of frameworks and it is really not easy to find out the perfect one. In this post, we are listing down five mostly used Java frameworks with pros and cons for each. Go with a framework that fits your project requirement, not if it is used by everyone.

Let’s take a look at the list :

https://www.opencodez.com/java/top-5-frameworks-java-developers.htm


r/javaexamples • • Mar 30 '21

Java Developer Interview Questions

5 Upvotes

Just wanted to share interview questions that are being asked from experienced people having more than 3 years of experience.

Java Developer Interview Questions

Let me know in the comments what is your favourite question out of these?


r/javaexamples • • Jun 02 '20

Tricks.

5 Upvotes

Is there any trick to learn java the most effective way? I am facing problem with problem solving and also applying logic!! Please help.


r/javaexamples • • Dec 09 '22

3 ways to parse JSON in Java

5 Upvotes

Parsing JSON is a common task for Java programmers, but many of them don't know how to do it because JDK API doesn't provide a standard JSON parser, but you don't need to worry. There are a lot of excellent JSON parsing libraries like Jackson, Gson, and json-simple which you can use to parse JSON. In this tutorial, I have shared how to use them to parse a JSON String in Java

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


r/javaexamples • • Oct 09 '19

Top Spring Boot Advanced Interview Questions? [Article]

8 Upvotes

r/javaexamples • • May 16 '20

Anyone Interested in learning how to send email using java code ?

9 Upvotes

r/javaexamples • • May 27 '15

SQLite Database access with a Swing GUI

11 Upvotes

SQLite Database Access with a Swing GUI

Screenshot

Get full code here - Gist

This example builds upon this post here.

Developing a GUI program can be a challenge, and even though I like some of the builders out there (I like the NetBeans one specifically), I wanted to show how to develop it from scratch in a more Model-View-Controller style. I have split up the code into four classes:

  1. InventoryGUI.java - the 'View' which only creates and places the graphical components

  2. Inventory.java - The main object class that is used as the 'Model' in conjunction with

  3. InventoryDBAccessor.java - All of the database access code abstracted away from the rest

  4. InventoryController.java - Manages getting the data from the Model classes and controls the event handlers for the GUI, sending data to the GUI as requested, or back to the database.

The GUI is a simple one-record at a time CRUD program, that lets us step through the data forwards or backwards, add new records, edit the existing records, or delete records. Note that this is all extremely simplified for educational purposes and is not meant for large amounts of data, and does not even get into the relational aspect of DBMS.

The Database Accessor

Here we have our code that handles opening the database, reading all of the data into an ArrayList of Inventory objects, and handles adding, updating and deleting records from the table. Each method has to handle exceptions. Ideally, there shouldn't be any System.out/err.println messages here, they should be handled by a Logger, but for now I am sending the messages to the console.

class InventoryDBAccessor
{
    private final String JDBC_CONNECT = "jdbc:sqlite:Inventory.db";
    private final String JDBC_CLASS = "org.sqlite.JDBC";
    private final String DB_OPEN_SUCCESS = "Database connection opened successfully";
    private final String SQL_SELECT_ALL = "SELECT * FROM Inventory ORDER BY partnum ASC;";
    private final int SQL_DATABASE_ERROR = 1;

    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;

    public InventoryDBAccessor()
    {
        try
        {
            connection = getConnection();
            statement = connection.createStatement();			
        }
        catch (SQLException e )
        {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            JOptionPane.showMessageDialog(null, "Database error : " + e.getMessage());
        }   
    }

    private Connection getConnection()
    {
        try
        {
            Class.forName(JDBC_CLASS);
            Connection c = DriverManager.getConnection(JDBC_CONNECT);
            System.out.println(DB_OPEN_SUCCESS);
            return c;
        }
        catch (ClassNotFoundException | SQLException e )
        {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            JOptionPane.showMessageDialog(null, "Database error : " + e.getMessage());
        }
        return null;
    }

    private void createTable()
    {
        try
        {
            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);                
        }
        catch ( SQLException e)
        {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            JOptionPane.showMessageDialog(null, "Database error : " + e.getMessage());                
        }


    }

    public ArrayList<Inventory> loadInventoryFromDB()
    {
        try
        {
            System.out.println("Loading data from table...");
            ArrayList<Inventory> invList = new ArrayList<>();

            resultSet = statement.executeQuery( SQL_SELECT_ALL );

            while (resultSet.next())
            {
                    invList.add(new Inventory(resultSet));
            }
            System.out.println("Loaded " + invList.size() + " records.");
            return invList;			
        }
        catch ( SQLException e)
        {
            if (e.getErrorCode() == SQL_DATABASE_ERROR)
            {
                createTable();
                loadInventoryFromDB();
            }
            else
            {
                System.err.println( e.getClass().getName() + ": " + e.getErrorCode() );
                JOptionPane.showMessageDialog(null, "Database error : " + e.getMessage());
            }
        }
        return null;
    }

    public void addToDB(Inventory item)
    {
            try
            {
                statement.executeUpdate(item.getSQLInsert());
            }
            catch ( SQLException e)
            {
                System.err.println( e.getClass().getName() + ": " + e.getMessage() );
                JOptionPane.showMessageDialog(null, "Database error : " + e.getMessage());
            }
    }

    public void updateDB(Inventory item)
    {
        try
        {
            statement.executeUpdate(item.getSQLUpdate());
        }
        catch ( SQLException e)
        {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            JOptionPane.showMessageDialog(null, "Database error : " + e.getMessage());
        }
    }

    public void deleteFromDB(String partnum)
    {
        try
        {
            statement.executeUpdate("DELETE from Inventory WHERE partnum ='" + partnum + "';");
        }
        catch ( SQLException e)
        {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            JOptionPane.showMessageDialog(null, "Database error : " + e.getMessage());
        }
    }

    public void close()
    {
        try
        {
            statement.close();
            connection.close();	
            System.out.println("Database successfully closed.");		
        }
        catch (SQLException e)
        {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            JOptionPane.showMessageDialog(null, "Database error : " + e.getMessage());
        }   
    }
}

The GUI class

I decided to use a GroupLayout combined with a BorderLayout. The BorderLayout is used to put the text label at the top and the navigation buttons at the bottom. The group layout takes two definitions of the layout: the Horizontal Group and the Vertical group. See Oracle's tutorial here for more.

Here is the part of the code that defines the group layout:

	dataView = new JPanel();

	group = new GroupLayout(dataView);
		group.setAutoCreateGaps(true);
		group.setAutoCreateContainerGaps(true);
	dataView.setLayout(group);

	group.setHorizontalGroup(group.createSequentialGroup()
		.addGroup(group.createParallelGroup(GroupLayout.Alignment.TRAILING)
			.addComponent(lblPartnum)
			.addComponent(lblItem)
			.addComponent(lblDescription)
			.addComponent(lblQty)
			.addComponent(lblPrice))
		.addGroup(group.createParallelGroup(GroupLayout.Alignment.LEADING)
			.addComponent(scrollDesc)
			.addGroup(group.createSequentialGroup()
				.addGroup(group.createParallelGroup(GroupLayout.Alignment.LEADING)
					.addComponent(txtPartnum, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE)
					.addComponent(txtItem, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE)
					.addComponent(txtQty, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
					.addGroup(group.createSequentialGroup()
						.addComponent(txtPrice, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblTotal)))))
		);

	group.setVerticalGroup(group.createSequentialGroup()
		.addGroup(group.createParallelGroup(GroupLayout.Alignment.BASELINE)
			.addComponent(lblPartnum)
			.addComponent(txtPartnum))
		.addGroup(group.createParallelGroup(GroupLayout.Alignment.BASELINE)
			.addComponent(lblItem)
			.addComponent(txtItem))
		.addGroup(group.createParallelGroup(GroupLayout.Alignment.BASELINE)
			.addComponent(lblDescription)
			.addComponent(scrollDesc))
		.addGroup(group.createParallelGroup(GroupLayout.Alignment.BASELINE)
			.addComponent(lblQty)
			.addComponent(txtQty))
		.addGroup(group.createParallelGroup(GroupLayout.Alignment.BASELINE)
			.addComponent(lblPrice)
			.addComponent(txtPrice)
			.addComponent(lblTotal))
			);

	this.add(dataView, BorderLayout.CENTER);

Another important part of the GUI is to set up methods so that another class can create the button action listeners, like this:

// methods for Controller to create listeners
public void addNextButtonActionListener(ActionListener listener)
{
    btnNext.addActionListener(listener);
}
public void addPrevButtonActionListener(ActionListener listener)
{
    btnPrevious.addActionListener(listener);
}

Now from our InventoryController class we can use anonymous inner classes to add the code for the listeners:

	// next button
   	frame.addNextButtonActionListener(new ActionListener()
   	{
        public void actionPerformed(ActionEvent evt)
        {
        	index++;
        	if (index >= invList.size()) index = 0;
        	getDataEntry();
        }
    });	

   	// previous button
    frame.addPrevButtonActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent evt)
        {
        	index--;
        	if (index < 0) index = invList.size()-1;
        	getDataEntry();
        }
    });	

We also add public getters and setters for the text fields in the GUI so they can be accessed by the Controller class. We also add a method that sets up the screen for editing/adding records by enabling/disabling the proper fields and buttons.

The Inventory Class

We have our Inventory.java class file from previous examples, to which I have added a few minor things such as a default constructor, a full set of getter/setter methods, and I have added a 'getSQLUpdate()' method to create a SQL command statement to do an UPDATE action, and a bit of ugly code to generate the Part Number primary key:

// creates a SQL command string to update object
// part number is not updateable
public String getSQLUpdate()
{
    return "UPDATE INVENTORY "
        + "SET item = '" + item + "', description = '" + description
        + "', qty = " + qty + ", price = " + price
        + " WHERE partnum ='" + partnum + "';";
}

// generate part number
// if possible, uses first three letters
// of the first two words, 
// or fills with random digits
public String generatePartnum()
{
    Random rand = new Random();
    String retval = "";
    String[] words = item.toUpperCase().split(" ");
    for (int i = 0; i < words.length; i++)
    {
        if (i > 1) break;
        if (words[i].length() < 3)
        {
            retval += words[i];
            for (int j = 0; j < 3 - words[i].length(); j++)
            {
                retval += "" + rand.nextInt(10);
            }
        }
        else retval += words[i].substring(0,3);
        
    }
    return retval;
}

The Inventory Controller Class

We start the Controller class by instantiating the GUI class, creating the event listeners as described above, and then instantiating the Database Accessor class and loading all the data into an ArrayList. (In a real-world situation you would probably only load chunks of the data at a time. You could also use Dependency Injection here, but that's the topic for another example.)

public class InventoryController
{
	private final InventoryGUI frame = new InventoryGUI();
	private InventoryDBAccessor dao;
	private ArrayList<Inventory> invList;
	// current displayed record index
	private int index;
	// flag for whether 'save' and 'cancel' commands should treat as an 'add' or 'edit'
	private boolean editNotAdd;

	public InventoryController() throws SQLException
	{

		initListeners();

       	dao = new InventoryDBAccessor();
		invList = dao.loadInventoryFromDB();
		dao.close();
		index = 0;
		editNotAdd = false;
		frame.setVisible(true);
	}

We add the rest of the button listeners (see rest of code on Gist), and add very simple methods to use the DB Accessor:

public void addToDB(Inventory obj) throws SQLException
{
	System.out.println("Adding record to database...");
	dao = new InventoryDBAccessor();
	dao.addToDB(obj);
	dao.close();
}

public void updateDB(Inventory obj) throws SQLException
{
	System.out.println("Updating record...");
	dao = new InventoryDBAccessor();
	dao.updateDB(obj);
	dao.close();
}

public void deleteFromDB(String partnum) throws SQLException
{
	System.out.println("Deleting " + partnum + "...");
	dao = new InventoryDBAccessor();
	dao.deleteFromDB(partnum);
	dao.close();
}

We add a setDataObject() method used for add/edit records which does some minor validation and then sends the object either to the update or insert methods, and a getDataEntry() method which simply grabs the Inventory object from the ArrayList and populates the GUI fields with the info. The controller class also houses the main method.

Thanks for reading!!!

Full code here - Gist


r/javaexamples • • Mar 18 '23

Website with Java examples

12 Upvotes

Hello everyone,

I am a software developer with several years of experience. As my side project and hobby I created a website with Java tutorials. If you are interested, please visit: https://simplecoding.net/

This project has the sole purpose of showing some examples of Java programs.

I will be happy if you manage to learn something from it :)

Have a nice day!


r/javaexamples • • Mar 31 '26

Ujorm3: Lightning-fast, minimalist ORM for Java Records and JavaBeans

Thumbnail reddit.com
2 Upvotes