Understanding Java Recursion...Factorial Example

In one line if someone wanted to explain,
"Recursion is, the method that call itself". Easy enough ehy...

If the input number is 0 or 1, we are returning 1 else we are going to compute the result as
n! = n * (n-1)!
A simple mathematics formula.

Here I am going to create the static method so, I don't have to create an instance of the method and can call just with the method name.

Note:
Here the datatype that I'm using is int so, ofcourse it may have some limitations and hence you can't go beyond certain limit however you guys may go ahead and have it double, long etc.

Let's have a look at the way we can code for any factorials using Java Recursion concept.

public class RecursionExample {

 private static int factorial(int input) {
  int fact = 0;
  if (input <= 1)
   fact = 1;
  else
   fact = input * factorial(input - 1);

  return fact;
 }

 public static void main(String[] args) {
  System.out.println(factorial(5));
 }
}
The above example will print out 120 as an output.

Create and write content into CSV file / Spread-sheet

Below example will illustrate how to create a csv or excel file and write any desired content into it. In this example we are going to use the FileWriter object and which is available in java.io package.

package com.amzi.xml;

import java.io.FileWriter;
import java.io.IOException;

public class CreateCsvFile {
 private static void generateCsvFile(String fileName) {
  FileWriter writer = null;
  try {
   writer = new FileWriter(fileName);
   writer.append("Name");
   writer.append(',');
   writer.append("ID");
   writer.append('\n');

   writer.append("Amzi");
   writer.append(',');
   writer.append("001");
   writer.append('\n');

   writer.append("Bond");
   writer.append(',');
   writer.append("007");
   writer.append('\n');

   System.out.println("CSV file is created...");

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    writer.flush();
    writer.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

 public static void main(String[] args) {
  String location = "/users/Amzi/test.csv";
  generateCsvFile(location);
 }
}

Validate phone number using java regular expression

In this example we are going to be validating any phone number. We are going to put following checks against any phone number under test.

  • The phone number should be 10 digit number.
  • Splitted by hi-fen(-) and the end result should look like xxx-xxx-xxxx

package com.amzi.xml;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidatePhoneNumber {
 public static void main(String[] args) {

  String phNumber = "123-222-3333";
  //String phNumber = "123 123 1234";

  Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
  Matcher matcher = pattern.matcher(phNumber);

  if (matcher.matches()) {
   System.out.println("Phone Number is Valid");
  } else {
   System.out
   .println("Phone Number isn't in this formate XXX-XXX-XXXX");
  }
 }
}

Output
Phone Number is Valid

How to get any webpage/URL content and save it on local drive using java code.

Alright, so today we are going to be coding to get the snapshot of any website. Here, we are using two jdk inbuilt packages java.io and java.net
This code is pretty self explanatory however, wherever required I've added the comments.
package com.amzi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class GetWebpageContent {
 public static void main(String[] args) {

  URL url;

  try {
   // enter any url to get its content
   url = new URL("http://www.javaandj2eetutor.blogspot.com");
   URLConnection conn = url.openConnection();

   // open the stream and put it into BufferedReader
   BufferedReader br = new BufferedReader(new InputStreamReader(
     conn.getInputStream()));
   String inputLine;

   // save it anywhere in local machine for offline use
   String fileName = "/users/Amzi/test.html";
   File file = new File(fileName);
   if (!file.exists()) {
    file.createNewFile();
   }

   FileWriter fw = new FileWriter(file.getAbsoluteFile());
   BufferedWriter bw = new BufferedWriter(fw);

   while ((inputLine = br.readLine()) != null) {
    bw.write(inputLine);
   }

   bw.close();
   br.close();

   System.out.println("Your file is saved in " + fileName
     + " location.");

  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }
}

Once we run the above program, if everything goes fine then the URL content supposed to be saved in the location we specified in the program and in the console weare supposed to see something like this.
Your file is saved in /users/Amzi/test.html location.

JAXB example for Unmarshalling – Convert XML content into a Java Object.

First of all, let's get started with the java DTO with some fields and annotations we will complete the object.

package com.java.example;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Employee {

    private String firstName;
    private String lastName;
    private long ssn;
    private int eId;

    @XmlElement
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @XmlElement
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @XmlElement
    public long getSsn() {
        return ssn;
    }

    public void setSsn(long ssn) {
        this.ssn = ssn;
    }

    @XmlAttribute
    public int geteId() {
        return eId;
    }

    public void seteId(int eId) {
        this.eId = eId;
    }

    @Override
    public String toString() {
        return "Employee [firstName=" + firstName + ", lastName=" + lastName
                + ", ssn=" + ssn + ", eId=" + eId + "]";
    }
   
}


You can copy the employee.xml file to your C:\Temp\employee.xml and your file should look something like this.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee eId="7">
    <firstName>James</firstName>
    <lastName>Bond</lastName>
    <ssn>123456789</ssn>
</employee>


Now, let's write the core logic which will convert the xml into the java object. In new file object I've mentioned the location for the employee.xml file. Make sure you have the file at the same location with same content otherwise you may have to change the coding.

package com.java.example;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class XmlToJava {

    public static void main(String[] args) {
        try {
            File file = new File("C:\\Temp\\employee.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Employee employee = (Employee) jaxbUnmarshaller.unmarshal(file);
            System.out.println(employee);

        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}


Once after we run XmlToJava class we are going to get the following output into the console.

Employee [firstName=James, lastName=Bond, ssn=123456789, eId=7]

Java code for school grade book

Here, I am going to write java code which will do following:
  • Will print the number of students along with their score.
  • The entire class average.
  • Lowest grade in the class.
  • Highest grade in the class.
So, let's get it started with the first java class.

public class GradeBook {
    private String courseName;
    private int[] grades;

    public GradeBook(String name, int[] gradesArray) {
        courseName = name;
        grades = gradesArray;
    }

    public void setCourseName(String name) {
        courseName = name;
    }

    public String getCourseName() {
        return courseName;
    }

    public void displayMessage() {
        System.out.printf("Welcome to the grade book for\n%s!\n\n",
                getCourseName());
    }

    public void processGrades() {
        outputGrades();
        System.out.printf("\nClass average is %.2f\n", getAverage());
        System.out.printf("Lowest grade is %d\nHighest grade is %d\n\n",
                getMinimum(), getMaximum());
        outputBarChart();
    }

    public int getMinimum() {
        int lowGrade = grades[0];
        for (int grade : grades) {
            if (grade < lowGrade)
                lowGrade = grade;
        }
        return lowGrade;
    }

    public int getMaximum() {
        int highGrade = grades[0];
        for (int grade : grades) {
            if (grade > highGrade)
                highGrade = grade;
        }
        return highGrade;
    }

    public double getAverage() {
        int total = 0;
        for (int grade : grades)
            total += grade;
        return (double) total / grades.length;
    }

    public void outputBarChart() {
        System.out.println("Grade distribution: ");
        int[] frequency = new int[11];
        for (int grade : grades)
            ++frequency[grade / 10];
        for (int count = 0; count < frequency.length; count++) {
            if (count == 10)
                System.out.printf("%5d: ", 100);
            else
                System.out.printf("%02d-%02d: ", count * 10, count * 10 + 9);
            for (int stars = 0; stars < frequency[count]; stars++)
                System.out.print("*");
            System.out.println();
        }
    }

    public void outputGrades() {
        System.out.println("The grades are:\n");
        for (int student = 0; student < grades.length; student++)
            System.out.printf("Student %2d: %3d\n", student + 1,
                    grades[student]);
    }
}


Now, let's create the other java class which will enable us to test the above class and methods

public class GradeBookTest {

    public static void main(String[] args) {

        // array of student grades. This is the data that we will use to
        // populate the array.
        // There are many ways of obtaining data to populate arrays, and some of
        // those ways are by user-input,
        // or by reading from a file, or in this case, we provide the data using
        // an array initializer list.
        int[] gradesArray = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };

        GradeBook myGradeBook = new GradeBook("Java Programming", gradesArray);

        myGradeBook.displayMessage();
        myGradeBook.processGrades();
    }
}


Output:

Welcome to the grade book for
Java Programming!

The grades are:

Student  1:  87
Student  2:  68
Student  3:  94
Student  4: 100
Student  5:  83
Student  6:  78
Student  7:  85
Student  8:  91
Student  9:  76
Student 10:  87

Class average is 84.90
Lowest grade is 68
Highest grade is 100

Grade distribution:
00-09:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
  100: *

How to read and manipulate values from text file by using java code

First of all create a text file and call it "txtFile.txt", now add the following values into the text file.

10
50.1
Amzi

Now, create a java class into the same folder where you have stored the txtFile.txt
The java class will be as follows.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ManipulateTxtfile {

    public static void main(String[] args) {
        try {
            Scanner in = new Scanner(
                    new File("txtFile.txt"));
            int first = in.nextInt();
            double second = in.nextDouble();
            String name = in.next();
            double sum = first + second;
            System.out.println("Hello " + name + "\nThe sum of " + first
                    + " and " + second + " is = " + sum);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}


The output of the above program will look something like this:

Hello Amzi
The sum of 10 and 50.1 is = 60.1

Run some task periodically using core java concepts

In this example we are going to write a java program which will run every 2 seconds and will perform some task for us. In our example we are simply going to print the new date time stamp after every two seconds but in a real world there could be plenty of scenarios one can think of. One example could be updating the user interface after every few seconds and fetch the latest data from the database.

The code is pretty self explanatory, by looking at the embedded comments it will be even easier. 

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * @author Amzi
 */
public class Scheduler extends TimerTask {

    Date currentTime;

    // Add your core logic/business use case
    public void run() {
        currentTime = new Date();
        System.out.println("The current Time is :" + currentTime);
    }

    public static void main(String args[]) throws InterruptedException {

        Timer timer = new Timer(); // Step 1 - Instantiate Timer Object
        Scheduler sc = new Scheduler(); // Step 2 - Instantiate the class
        timer.schedule(sc, 0, 2000); // Step 3 - Create task for every 2 seconds
        // Using the for loop along with the System.exit to terminate the
        // program otherwise it will keep on running
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread..." + i);
            // Make thread sleep for 2 seconds
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("We are getting out of here...");
                System.exit(0);
            }
        }
    }
}


The above code will print the following output into the console.

Execution in Main Thread...0
The current Time is :Mon Nov 25 14:33:07 EST 2013
Execution in Main Thread...1
The current Time is :Mon Nov 25 14:33:09 EST 2013
Execution in Main Thread...2
The current Time is :Mon Nov 25 14:33:11 EST 2013
Execution in Main Thread...3
The current Time is :Mon Nov 25 14:33:13 EST 2013
Execution in Main Thread...4
The current Time is :Mon Nov 25 14:33:15 EST 2013
The current Time is :Mon Nov 25 14:33:17 EST 2013
Execution in Main Thread...5
We are getting out of here...
The current Time is :Mon Nov 25 14:33:19 EST 2013




Java RESTful example using jersey api

Before we proceed, we need almost four things up and running as part of our dev environment. Here I will be using following resources in order to design the simple RESTful service.
  1. Eclipse
  2. Tomcat
  3. Jersey library
  4. Maven
Jersey api is based on JAX-RS (JSR 311).

In nearly 4 steps we can configure and build the complete RESTful API.

  1. Open up your Eclipse IDE and create a dynamic web project and then convert it into the Maven project.
  2. Add the jersey-server dependency.
  3. Configure the jersey-server class and package entry into the web.xml file.
  4. Create the java class which will configure the url and request type and also will prepare the response.
 Maven Dependency:

Add below code snippet inside your pom.xml file. This will add the jersey-server library into the project.

      <dependency>
          <groupId>com.sun.jersey</groupId>
          <artifactId>jersey-server</artifactId>
          <version>1.8</version>
      </dependency>


web.xml

Add the below code snippet in your web.xml file.

<servlet>
        <servlet-name>my-jersey</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.services.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>my-jersey</servlet-name>
        <url-pattern>/restful/*</url-pattern>
    </servlet-mapping>


Java Class:

Add the below java code into your java file.

package com.services.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class FirstRestService {
   
    @GET
    @Path("/{param}")   
    public Response sendMsg(@PathParam("param") String msg){
       
        String output = "<h1>Hello! this is a : </h1>" + "<p>"+msg+"</p>";
        return Response.status(200).entity(output).build();
    }
   
    @GET
    @Path("/greeting")
    public String response(){
       
        return "<h1>Hello World</h1>";
    }

}


That's pretty much it guys, now you may go ahead and run the server and run the below url

http://localhost:8080/MyProject/restful/hello/greeting
OR
http://localhost:8080/MyProject/restful/hello/restFulWorld

Simple balance transfer java program

In this example we are going to code a simple balance transfer java program. Here is how the code looks like. You can try and pass the different parameters for initialBalance and transfer amount and check the result also, you can pass the different accNumber, input values and analyze how the result output is changing.

package com.mybank.transfer;

public class BalanceTransfer {

    private double initialBalance;
    private double remainingBalance;
    private double transfer;

    BalanceTransfer() {
        initialBalance = 5000.0;
        transfer = 20000;
    }

    public BalanceTransfer(double initialBalance, double transfer) {
        super();
        this.initialBalance = initialBalance;
        this.transfer = transfer;
    }

    private double makeTransfer(boolean isActive) {
        if (accountExists(101)) {
            System.out.println("We found your account...");
            if (isActive) {
                System.out
                .println("Congratulations!!! your account is active...");
                if (initialBalance >= transfer) {
                    remainingBalance = initialBalance - transfer;
                    System.out.println("Your remaining balance is: "
                            + remainingBalance);
                } else {
                    System.out
                    .println("Your total balance must be greter than or equal to the transfer amount");
                }
            } else {
                System.out
                .println("Your account isn't active! Please visit the nearest branch...");
            }
        } else {
            System.out.println("Sorry account doesn't exist!");
        }
        return remainingBalance;
    }
   
    private boolean accountExists(int input) {
        int accNumber[] = { 101, 102, 103, 104, 105 };
        boolean found = false;
        for (int index : accNumber) {
            if(index == input)
            found = true;
        }
        return found;
    }

    public static void main(String[] args) {

        BalanceTransfer bt = new BalanceTransfer(1000, 500);
        bt.makeTransfer(true);
    }
}


Output:

We found your account...
Congratulations!!! your account is active...
Your remaining balance is: 500.0

Print factorials for any given number

In this example we are going to write a java class which will enable us to print factorial for any given number.
A quick refresher: 
  • The factorial of 0 and 1 is always 1.
  • Formula to find a factorial is: n! = n*(n-1)!
  • Exp: 5 = 5*4*3*2*1 = 120

import java.util.Scanner;

public class PrintFactorials {

    public int factorials() {
        int factorial = 1;
        int input;
        System.out.print("Please enter any integer value. ");
        Scanner scanner = new Scanner(System.in);
        input = scanner.nextInt();

        if (input < 0)
            System.out
            .println("The entered number is not positive!!! Please re-try...");
        else {
            for (int counter = 1; counter <= input; counter++)
                factorial = counter * factorial;
            System.out
            .println("The factorial of " + input + " is " + factorial);
        }
        return factorial;
    }

    public static void main(String[] args) {

        PrintFactorials pf = new PrintFactorials();
        pf.factorials();
    }
}


Output:

Please enter any integer value. 5
The factorial of 5 is 120