Showing posts with label Simple Java Codes. Show all posts
Showing posts with label Simple Java Codes. Show all posts

Saturday, June 29, 2019

My Sql + Spring Boot JPA - One to many, many to one example

This is a simple spring boot JPA (hibernate) example. It will demonstrate how one to many, many to one mapping can be done

Below are the tables created in MySQL

create table department
(
 department_id int not null auto_increment,primary key (department_id),
 department_name  varchar(50) not null
);


create table employee
(
 employee_id int not null auto_increment, primary key (employee_id),
 employee_name varchar(50) not null, 
 department_id int not null, foreign key (department_id) references department(department_id)
);

pom.xml


application.yml


Friday, June 6, 2014

Java - To Load a property file

Property files are used to store static information in a key-value pair. Things that you do not want to hard code in your Java code, which tend to change in future goes into properties files. Also as it is a static information you do not want to load the property file for each and every request as it may hamper performance. You may need it to be loaded only once at the begining of the loading of application.

You can load properties file using below methods. You can provide absolute path as well as relative path however mostly relative path is preferred.

prop.load(AppProperties.class.getClassLoader().getResourceAsStream("app.properties"));
OR
prop.load(new FileInputStream(new File("C:/temp/app.properties")));

Please see the self explanatory java code below - 

Monday, January 27, 2014

Java program to print a-z, A-Z sequentially

// PrintAlphabets.java

public class PrintAlphabets {

public static void main(String[] args) {

for (char alphabet = 'a'; alphabet <= 'z'; alphabet++) {
System.out.print(alphabet + " ");
}

System.out.println();

for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
System.out.print(alphabet + " ");
}
}

}

Output

a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 

Wednesday, November 13, 2013

Java program to play an audio sound

These are the following ways in which you play a sound in Java.

Toolkit - If you just want a beep or quick alert you can use beep() finction of class java.awt.Toolkit. It Emits an audio beep.
AudioClip - The AudioClip interface is a simple abstraction for playing a sound clip.
Clip - The Java Sound API provides functionality for the capture, processing, and playback of sampled audio data & the sequencing and synthesis of MIDI data.
MIDI Sequences - The javax.sound.midi package provides an interfaces and classes for I/O, sequencing, and synthesis of MIDI (Musical Instrument Digital Interface) data.

Please see the sample code of each type


Tuesday, October 29, 2013

Java program to take screen shots of your desktop

This example is used to take screen shots of your desktop and save the file in specific format in your machine. This example uses java.awt.Robot class to capture the screen pixels and returns a BufferedImage. Java.awt.Robot class is used to take the control of mouse and keyboard, see API for more options. Once you get the control, you can do any type of operation related to mouse and keyboard through your java code.

Please see the self explanatory java code below. This example takes screen shot of your desktop after an interval of every 5 second, you can customize it as per your requirement.

Saturday, September 21, 2013

Java program to check IP address range

This is a simple java program to check IP address range. Here we provide a IP address to check whether it lies between start and end IP address.

Please see the self explanatory java code below. Just provide the IP address and see the output.


Monday, May 20, 2013

Java - Read excel file with blank cells

If you use normal cellIterator to iterate through excel cells it will skip blank cells. If you need to read blank cells as well you can use below method -

Thursday, March 21, 2013

Java : Function to return type of Object

Below is the java program which shows how to detect type of object in an ArrayList containing different types of Object.


Output :

Mike String
999 Integer
99.0 Double
Thu Mar 21 17:31:29 IST 2013 Date
true Boolean
java.lang.Object@3e25a5 String
null null
 

Friday, January 11, 2013

Java program to ping an IP address

Below is the Java program to ping an IP address.


Also note that you can use below syntax to check if remote IP address is is reachable or not.

String ip = "google.com";
InetAddress address = InetAddress.getByName(ip);
boolean chkConnection = address.isReachable(1000);

Thursday, January 10, 2013

Java program to read a text file

Below java program can be used to read a text (.txt) file or any other text based file like .xml, .properties etc


Java function to reverse a String

Please see below, a simple java function to reverse a String. You can use it to check for palindrome as well.

Simple java program to send Mail using JavaMail API

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. to know more, click here.

For below program to run, please add mail.jar in your application's classpath. Download mail.jar.


Monday, January 7, 2013

Java - Various ways to iterate a Map (Hashtable, HashMap, TreeMap, LinkedHashMap)


A Map is collection that maps keys to values. A map cannot contain duplicate keys, each key can map to at most one value. Map comes with 4 different version - Hashtable, HashMap, TreeMap, LinkedHashMap.

Hashtable - Key methods of Hashtable are synchronized. Hashtable doesn't allow a null key or null values.

HashMap - HashMap allows one null key and multiple null values in a collection.

TreeMap - TreeMap is a sorted Map.

LinkedHashMap - LinkedHashMap maintains insertion order.

Below are the methods in which you can iterate a Map.

1. Iterator - Using Iterator you can iterate HashMap, TreeMap, LinkedHashMap.

2. Enumeration - Using Enumeration you can iterate Hashtable.

3. Also you can iterate values of a Map using values() and elements() method.

Java - Various ways to iterate a Set


A Set is a collection that contains no duplicate elements. Below are the methods in which you can iterate a Set

1. For each loop (introduced from Java 5)
2. Array and While loop (here you can use for loop as well)
3. Using Iterator

Please see the below code.

Different type of ways to iterate a List in java


As List is dynamically growable array. Below are the methods in which you can iterate a List

1. Basic for loop
2. For each loop (introduced from Java 5)
3. While loop
4. Using Iterator
5. Using ListIterator (Unlike Iterator which traverse list in forward direction, ListIterator is used to traverse the list in either direction)

Please see the below code.

Thursday, January 3, 2013

Spring - How to inject List or Map using bean?

In this example we will see how to How to inject List or Map using Spring bean. For complete setup using eclipse you can refer my previous article, Spring Hello World Example.

About the example - We have a class Country.java with two instance variables city as Map and president as List. We will set those values using Spring bean with the help of Spring configuration file  applicationContext.xml. Please see the self explanatory codes below

Country.java.


Serialization in Java


Serialization is used to save the object and all of its instance variables (except transient) in an external file mostly with .ser extension. With the help of Serialization you can reconstruct the same object latter.

The Serialization is done with the help of below two methods

// serialize objects and write them to a stream
ObjectOutputStream.writeObject() 

// read the stream and deserialize objects
ObjectInputStream.readObject()

About the example - We have a Dog class, which we will be Serializing. Note that Class which to be serialize must implements the Serializable interface. Serializable is a marker interface, it has no methods to implement. In SerializeDog.java we will create a Dog object d1 serialize it and write it to a dog.ser file and latter we will deserialize the object.

Please see the java codes below



Friday, December 28, 2012

Java - Get content type of a particular file



In many occasion you may require to check content type of a particular file. For example if a file is uploaded, it's not enough to check only file extension. For additional security you should also check the actual content type of a file so latter while processing the file no exception occurs. File could be Image, Excel, Text etc.

Let's see how this can be achieved in Java.

URL - This class represents a Uniform Resource Locator. It point to a particular resource, resource can be either a file , directory or an object. Here it refers to a file.

URLConnection - This is the super class of all classes that represent a communication link between an application and a URL.

openConnection() - This is the method of URL class which represents a connection to the remote object referred to by the URL.

getContentType() - This method of URLConnection class returns the content type of the file.