String reverse program in java

String Reverse using StringBuilder

Leap Year Program in Java

A Leap Year is a year which has 366 days. This year February is of 29 days. Leap years occurs in every four years.

A leap year has following constraints.

We can check in programming as below

  • A year is divisible by 400 then it is a leap year
  • A year is divisible by 4 and not divisible by 100 then the year is leap year

See another program

MySql Jdbc Operations for beginner

Database connection with java is one of the essential feature of java, In java to connect with database we use java database connectivity(JDBC) programs.

JDBC is an Application Program Interface(API) that is used to interact with database and java program in database independent way.

So JDBC (full form Java Database Connectivity) code to interact with mysql, oracle database and with other database.

Here we used jdbc with mysql to connect it we need a mysql jdbc driver to connect mysql with java.

Here we will see a java jdbc project to perform all basic operations involved in Database interaction.

Setting Up Project

JDBC project setup is in two part

  • create database
  • Write Java, Jdbc codes

Creating database

  • Create a database user name with password.
  • given all privileges to user.
  • created database and table for employee.

Above all details are set in following script.

Run this script before running java jdbc program

Writing Java Jdbc Code

  • Create Java Bean
  • Creating Main class (Execution starts from here)
  • Create Action class
  • Create DAO class

Java Bean

A Java Bean is a simple java class, that holds all properties, getter setter methods and constructors of the class.

Java Bean for Employee class is given below

Create Main Class

Below is main class for running all java jdbc examples

Here you find various examples like to insert in table, to update table ,delete a recored from mysql table and select a specific or all record from table.

To insert record see comment data Create Employee that is used to create table at that time comment all other below data.

When data is inserted then comment the create employee and uncomment the update employee.

similar for all.

Create Action Class

Above class will call method of below action class

Create DAO class

The above action class will call to below DAO class method

Here All JDBC Prepared statement are used to interact with mysql

Various JDBC operations used here are

  • Insert
  • Update
  • Delete
  • FetchById
  • FetchByEmailId
  • FetchByMobileNo
  • SearchByName
  • FetchByCity
  • FetchBySalaryRange
  • FetchByDob
  • FetchByDojRange
  • FetchAll

Download this Java Project with source code for github

How to Convert Java Object to/from JSON using GSON

Gson is Java JSON library that is used to convert Java object to/from JSON

GSON is developed by google.

GSON Maven dependency is as below

You can also download Gson Jar from here

Gson jar contains API to work with JSON

GOal of GSON is provide simple methods to convert and receive JSON, Provides extensive support for Generics, support complex objects

GSON provides simple functions to convert in to JSON it has toJSON() and from JSON to Java Object it has fromJSON()

Creating JSON Object

1. Gson gson=new Gson();
2. GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson1 = gsonBuilder.create();

Here Gson() is no argument constructor that will create Gson object.

Using GsonBuilder by calling create() we get Gson object

Converting Java to JSON value


Some times JSON is difficult to read to make JSON readable .setPrettyPrinting() can be used as below

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson1= gsonBuilder.setPrettyPrinting().create();

Replace line 40 of program with second line of above code.

Then output is as below.

Serializing a custom object

Here a student class is defined it contains Address class. Create object of student and serializing it as below


Reading Json Data from file

Parsing JSON to Java is prerformed as here.

We have saved JSON of a student (same as above structure few parameter changed) in student.json file then we are reading its content from student.json.

student = gson.fromJson(new FileReader(“d://student.json”), Student.class);

To read file from student.json File reader is used. after reading file it is converted to Student type.


Reading JSON data from URL

  1. Open Connection with url
  2. Read Data using InputStreamReader
  3. Pass InputStreamReader to fromJson()

Working code is as below

@Expose annotation to serialize and de serialize fields

Annotation Export is used to serialize and deserialize fields it is defined in import

@Expose(serialize = true, deserialize = true) is used serialize true represents it has to be serialize same for deserialize. false value is used to not include the field in process of serialize or deserialize.

Above code and is modified as below

in main method to create object we have to use GsonBuilder as below call a method excludeFieldWithoutExposeAnnotation()

ExclusionStrategy Interface

This interface is also used to exclude any field in serializing and deserialization.

To implement ExcludeStrategy a class has to implement this.

Below is an example to remove fname field from serialization

To create Gson object use GsonBuilder as below

Exception handling in Java

Exception Handling in java

To learn about exception handling first you must know what is an exception

An exception is run time error that can occur due to wrong user input or due to logical error in programming.

Consider a simple example.

Take two integer number from command prompt and divide the number.

The code is

We complice above program

c:\> javac

while running this program we will pass

two values to program as below

  > java division 10 2

Above two values 10 and 2 known as command  line argument these values are accessed in string [] s.

There s is string array  first value 10 is stored in s[0] and second value is stored in s[1]

S is string array so we converted these string values to integer by calling Integer.parseInt(value)

Here Integer is a class and parseInt is static method used to convert string value to int value.

The converted value is stroed in a and in b

The result of division operation is

                                C= a/b;   //c = 10/2 =5 

It will store value 5 in c.

  Next statement print division is 5

This is our desired result.

What happen if user enters value 10 and 0.

What happen if user enters value 10 and 0.

  Then the statement

                                C= a/b; // c= 10/0 –

   This statement throw arithmetic exception.

    The output is a below.

Exception in thread “main” java.lang.ArithmeticException: / by zero
at division.main(

The above exception is due to Wrong user input.

To handle above situation we can use user input validation or exception handling.

Lets see user input validation here before division operation check whether the value of b is zero or not.

If it is zero information to user and stop the program else perform the division as below.

>javac 10 0

divisor should not be zero

This program validate the denominator is zero then print message to user else perform division operation.

Here validation is used to avoid the exception. This is good practice to validate user input to avoid exceptions.

Here we want to learn exception handling so lets see the above program with java exception handling

lets run again above code

>java Division 10 2

Division is 3

>java Division 10 0

Arithmetic Exception

In above program to handle exception try and catch blocked is used.

Inside try block the code is written which can throw exception.

The statements which can throw expection is written inside try block.

To catch the exception a catch block is used with exception type . inside the catch block appropriate exception handling is done.

Catch block executes when exception is thrown from code inside try block.

In above program int c= a/b;

exception is thrown when the value of b is zero so it should be inside try block.

The statement System.out.println(“division is “ + c); is not throwing an exception it is also inside the try block.

If division statement throw an exception. The control is passed to catch block and necessary action is performed inside catch block.

The catch block is only executed if statements inside try block throws an exception.

Lets again execute above program with value 10 and String value lets a 

>javac Division 10 a

Exception in thread "main" java.lang.NumberFormatException: For input string: "a" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at division.main(

Here second value is string so throwing above exception

Integer.parseInt (s[1]) throw an exception  because it is unable to convert string to int.

In our program we handled only arithmetic exception

To handle this exception lets modify our code

again compiling and running this code

>javac Division 10 a

Please enter valid number

System.exit(1) is used to exit from program.

Here denominator is not a number so no need to continue the program.

here we used two try block and its corrosponding catch blocks.

If you want we can use one try block and multiple catch block.

Lets again change this code to handle multiple catch in single try block.

Here all type of exceptions are checked in try block when an exception is thrown based on exception a catch block is executed.

Exception is parent class for all exceptions.

Any exception thrown can handle by catching exception.

Standing multiple exceptions in program, then general exception should be last catch statement otherwise specific exception catch statement will not reached.

Concatenate & Buffer File in Java

Concatenate: It is possible to concatenate two or more files and save in a different file.

In java, by using SequenceInputStream class we can concatenate two or more files.

Buffer Files: In java, we can create a buffer to store temporary data that is read from & written to a stream and this process known as i/o buffer operation.

Buffer is  sit between programmer and source/destination file.

Buffer can be created by using following classes:

  • BufferedInputClass
  • BufferedOutputClass

Example: write a program to concatenate two file A & B and concatenated data print on output screen.

Suppose we have a File “A.txt”

Hello students I am aditya.  

 and                         File “B.txt”


Output: Hello students I am aditya.                                                                                           Hello

Example: Write a program to copy the content of one file to another file using buffer/BufferReader.                                                                

Suppose we have a File “A .txt”                               

Hello students I am aditya.  

Output:                                              File “B”

Hello students I am aditya.  

Note: If there is no file “B” it will be create automatically.

Example: Write a program to concatenate two file A & B and save the concatenated data on a file C.

Suppose we have a File “A.txt” and File “B.txt”

Hello students I am aditya.  

Output:               File “C”

Hello students I am aditya. Hello  

Note: Ifthere is no file “C” it will be create automatically.

File I/O with Primitive Data Type In Java

In java, basic input-output stream provides a method for reading & writing bytes or character in a file. If we want to read-write primitive data typa(such as int , float etc.) than we can use filter classes to filter data in the original stream.

DataInputStream & DataOutputStream are two filter classes used for creating “data streams” for handling primitive data type.

Example: Write a program to write & read a primitive data on a same file.

Character Stream I/O in Java

In a java programming, like a Byte stream Character stream is also used for input-output for 16 bit. But Byte streams are used to perform input and output of 8-bit.

Most common Character streams classes are, FileReader and FileWriter.

 FileReader- FileReader uses for reads two bytes at a time.

 FileWriter– FileWriter uses for writes two bytes at a time.

Example: Write a program, to copy the content of file A into file B using Byte stream class.

Note: if there is only file A in which data is written and no file B then, file B will be create automatically.

Suppose we have a File “A”

Hello students I am aditya.  

Output: When we run above program one new file create with Name “B” and content of file “A” will be copy into file “B”.

            File “B”

Hello students I am aditya.  

Byte Streams in Java

In java programming, to perform input and output of 8-bit, Byte stream is used.

Most common byte streams classes are, FileInputStream and FileOutputStream.

FileInputStream : FileInputStream is used for reads one byte at a time .

FileOutputStream : FileOutputStream is used for writes one byte at a time

Writing Bytes

Example: Write a program, to write a bytes to a  file using Byte stream class.


checking file A.txt it will show following content.

Note: If there is no file A then, file A will be create automatically

Reading bytes from a file

Suppose we have a file “A.txt”

Hello Students I am Aditya

Example: Write a program, to read a bytes from file A using Byte stream class and print on output screen.

Example: Write a program, to copy the content of file A into file B using Byte stream class.

Note: if there is only file A in which data is written and no file B then, file B will be create automatically.

Suppose we have a File “A”

Hello students I am aditya.  

Output: When we run above program one new file create with Name “B” and content of file “A” will be copy into file “B”.

File “B”

Hello students I am aditya.  

File and Input Output in Java

In Java programming, to perform the input-output in file handling  Java has a package which contain contains nearly every class you might ever need.

In file handling streams represent an input source and an output destination.


In java programming, a sequence of data defined as a “stream”.

Simply  there are two type of streams:

  1. InputStream −  To read data from a source InputStream is used.
  2. OutputStream-  To write a data to a destination OutputStream is used.

Stream Classes

In java,  package “”  contains a large number of stream classes and these classes can be divided into two groups:

  1. Byte stream
  2. Character stream