Wednesday, December 4, 2013

Java BigDecimal class tutorial: How to deal with monetary calculation in Java?

Lets take an example of computing a below mentioned financial operation using java program
 Chocolate cost = 5.52
                Tax = 0.84
 -----------------------------
Expected Total = 6.36

But if you do the above calculations using 'Double/float' primitive data type in Java, the total obtained will be 6.359999999999999.

We need to round of the total value to have a meaningful value in real life. Hence Java provides a class BigDecimal for this purpose.

Below is the simple program, which describes the usage of BigDecimal

----------------- BigDecimalExample.java -------------------------------
package blog.siddesh.basics;

import java.math.BigDecimal;

public class BigDecimalExample {

public static void main(String[] args) {
BigDecimal num = new BigDecimal("5.52");
BigDecimal tax = new BigDecimal("0.84");
BigDecimal total = num.add(tax); 

System.out.println("Total = "+total.toString());

double n = 5.52;
double t = 0.84;
double tot = n + t;
System.out.println("Double total = " + tot);


}

}
---------------------------------------------------------------------------

Thursday, October 31, 2013

FindMonth - A simple Java MVC WebApp using Servlet, JSP, eclipse

In this blog I'll explain with a simple example about creating a Java Web Application using MVC pattern. I'm using a simple java program as model, JSP as view and Servlet as controller. 
This application is developed using eclipse (Juno) IDE,  jdk1.6.0_43 and it is hosted on Apache tomcat 7.0.

What is MVC? 

Here is the definition from Wiki. 
Model–view–controller (MVC) is a software architecture pattern which separates the representation of information from the user's interaction with it.
The model consists of application data, business rules, logic, and functions. 
A view can be any output representation of data, such as a chart or a diagram. Multiple views of the same data are possible, such as a bar chart for management and a tabular view for accountants. The controller mediates input, converting it to commands for the model or view.

FindMonth is my first simple java webapp

How it looks?



Configuration in eclipse

  • Open eclipse -> Select Java EE perspective 
  • File -> New -> Dynamic Web Project
  • Provide ProjectName i.e. FindMonth 
  • Select Target run-time has Apache Tomcat 7.0 (or which ever version installed in your computer)
  • Click Next -> Next -> Select "Generate web.xml deployment descriptor -> Finish

Project layout in eclipse




The files ticked in RED font are the files created by me for this project.

  • NumberToMonth.java acts as Model
  • SelectMonth.java is the Servlet
  • FindMonth.html is the home page
  • result.jsp is the View
  • web.xml is a web descriptor file which links the Homepage to Servlet

Code

Model: NumberToMonth.java

I have created a package blog.sliceoffcodes.model which holds the file NumberToMonth.java
  • Right click on src (under Java Resources) -> New -> Package -> Provide package name
Create a java file
  • Right click on above created package -> New -> Class -> provide name NumberToMonth



package blog.sliceoffcodes.model;

public class NumberToMonth {
int month;
String monthString;

public NumberToMonth(int month) {
super();
this.month = month;
}

public int getMonth() {
return month;
}

public void setMonth(int month) {
this.month = month;
}

public String getMonthString() {
return monthString;
}

private void setMonthString(String monthString) {
this.monthString = monthString;
}

public void FindMonth() {
switch (getMonth()) {
case 1:
setMonthString("January");
break;
case 2:
setMonthString("February");
break;
case 3:
setMonthString("March");
break;
case 4:
setMonthString("April");
break;
case 5:
setMonthString("May");
break;
case 6:
setMonthString("June");
break;
case 7:
setMonthString("July");
break;
case 8:
setMonthString("August");
break;
case 9:
setMonthString("September");
break;
case 10:
setMonthString("October");
break;
case 11:
setMonthString("November");
break;
case 12:
setMonthString("December");
break;
default:
setMonthString("Invalid");
break;
}
}

}



Controller (Servlet): SelectMonth.java

I have created a package blog.sliceoffcodes.web which holds the file SelectMonth.java
  • Right click on src (under Java Resources) -> New -> Package -> Provide package name
Create a java file
  • Right click on above created package -> New -> Servlet -> provide name SelectMonth.java
package blog.sliceoffcodes.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import blog.sliceoffcodes.model.NumberToMonth;

public class SelectMonth extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String m = request.getParameter("inputMonth");
/* response.setContentType("text/html");
PrintWriter out = response.getWriter(); 
out.println("Month Input = " + m); */
NumberToMonth nm = new NumberToMonth(Integer.parseInt(m));
nm.FindMonth();
String result = nm.getMonthString();
//out.println("Month output = " + result);
request.setAttribute("monthExtract", result);
RequestDispatcher view = request.getRequestDispatcher("result.jsp");
view.forward(request, response);
}

}

view (Home page): FindMonth.html

  • Right click on WebContent -> New -> HTML file -> provide name FindMonth.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Find Month</title>
</head>
<body>
<h1 align="center">Find Month</h1>
<form method="POST" action="FetchMonth.do">
Select Month Type: <select name="inputMonth" size=1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select> <br>
<br>
<center>
<input type="Submit">
</center>
</form>
</body>
</html>

view (jsp): result.jsp

  • Right click on WebContent -> New -> JSP file -> provide name result.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Result of Month Finder </title>
</head>
<body>
<h1 align="center">Month</h1>
<p>
<%
  String month = (String) request.getAttribute("monthExtract");
  out.print("<b> Month in English: " + month);
  
%>

<br> <br>
<A HREF="FindMonth.html" align="center">HOME</A>
</body>
</html>

web descriptor : web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>FindMonth</display-name>
  <welcome-file-list>
    <welcome-file>FindMonth.html</welcome-file>    
  </welcome-file-list>
  
  <servlet>
    <servlet-name>Month</servlet-name>
    <servlet-class>blog.sliceoffcodes.web.SelectMonth</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Month</servlet-name>
    <url-pattern>/FetchMonth.do</url-pattern>
  </servlet-mapping>
  
</web-app>

Monday, September 2, 2013

Printing Unicode characters from eclipse (example to print kannada letters)

Do you want to print your name in your native language (other than English) ?
You need to find the equivalent Unicode characters and change the eclipse settings to display UTF-8 encoding.

Problem statement: 
    Print my name Siddesh in Kannada

Solution:
  Step 1: Find Unicode characters.        
             Refer http://symbolcodes.tlt.psu.edu/bylanguage/kannadachart.html
             Here
              Sa = 0CB8 
             To make it Si = Sa + 0CBF i.e "\u0CB8\u0CBF"
  Step 2: Change eclipse settings
             Window -> Preferences -> General -> Workspace -> Text file encoding -> Other -> Choose UTF-8 from drop down

Program:

public class Kannada {
public static void main(String[] args) {
System.out.println("Hello \u0CB8\u0CBF \u0CA6\u0CC7 \u0CB6\u0CCD");
System.out.println("");

}

}
           
Output:
Hello ಸಿದ್ದೇಶ್            



Friday, August 2, 2013

Running maven project through eclipse

As a build engineer, I got first exposed to maven through command line interface. Since Java development is done better through IDE, it is good to run maven projects from eclipse. This blog explains step by step guide to run a maven project from eclipse.

Note: I'm using Eclipse Juno.

1) Install m2eclipse plugin
          Open Eclipse IDE ->  Help -> Eclipse Marketplace -> Find -> Maven
          Select either
             Maven Integration for Eclipse by Eclipse.org  or
             Maven Integration for Eclipse WTP by by Eclipse.org
           and click 'Install' and follow the links.

      Verification: Eclipse IDE -> Window -> Preferences -> You should notice maven in left panel

2) Import maven project in Eclipse
    Eclipse IDE -> File -> Import -> Maven -> Existing Projects -> Next
    'Root Directory' -> Browse -> Select your maven project and 'Finish'

3) Building maven project in Eclipse
    Eclipse IDE -> Right click on your project -> Run as ->  Maven clean / Maven install

Wednesday, July 31, 2013

Writing distributive Perl Modules - Binary/Decimal Converter

You can write a Perl script in a single file. If your script is very simple and it doesn't have any re-usable code, then it is the right choice. But if you have some piece of code, which can be re-used in other scripts or by other persons and still it is single file, then it is called a naive script.

Write the reusable code as modules and 'use' that module in your script and encourage others to use it. In this post I'll demonstrate how to create Perl module with a simple example and how to package it, such a way that, it can be installed like any CPAN perl modules.

Problem Statement:
Write a script which either
  1) Accepts a Binary number and converts it into Decimal number
  2) Accepts a Decimal number and converts it into Binary number

Write Decimal and Binary converter functions in a separate module and 'use' it in a controller script.

Know-how: Perl modules
*) How to create Perl modules? Learn about EXPORT, EXPORT_OK, etc

Sample invocation
$ ./converter.pl
         Welcome to Slice Off Codes number converter
         A Utility to convert Binary to Decimal number
                and Decimal to Binary number


Press 1:  to select Binary to Decimal Converter
Press 2:  to select Decimal to Binary Converter
Press 3:  to quit
Choice : 1

Enter Binary number
101
Decimal value of Binary number 101 = 5

Press 1:  to select Binary to Decimal Converter
Press 2:  to select Decimal to Binary Converter
Press 3:  to quit
Choice : 2

Enter Decimal number
6
Binary value of Decimal number 6 = 110

Press 1:  to select Binary to Decimal Converter
Press 2:  to select Decimal to Binary Converter
Press 3:  to quit

Choice : 3

Source code

Saturday, July 27, 2013

Illustrating Perl threads with simple Maths script

Why do we use threads? 
   One of the reason is to perform tasks in parallel and get better turn-around-time.
   Also a server program which accepts data from user's and assign the task to a thread. Once the task is assigned, server goes back to accept new requests.

Problem statement
Write a script which accepts 2 numbers from user and performs addition, subtraction, multiplication and division operations on it in parallel. The main scripts performs all the 4 arithmetic operations using threads and it returns back waiting for next input.

Sample invocation
   ./math2.pl
Output
Welcome to Slice Off Codes Math Calculator
Enter Number 1
89
Enter Number 2
37
soc_add thread started ...
soc_sub thread started ...
soc_mul thread started ...
soc_div thread started ...
Main thread ....
Press 1 to Continue
Press 2 to Quit
89 / 37 = 2.40540540540541
89 - 37 = 52
89 * 37 = 3293
89 + 37 = 126

Know-how: Threads
use threads;  #Perl thread module
#Creating threads
my $thr1 = threads->create(\&soc_add, $num1, $num2);
# Collecting return data from threads. It also waits for thread to exit
$my @return_data=$thr1->join();
#Don't wait for thread return, don't have return data, just detach
$thr1->detach();

Source code
Method 1: Using detach

Tuesday, June 25, 2013

Convert Rupees to Paises

Hooray!!! Here is the first post of this blog. I'm a newbie java programmer and hence will start with a basic program.

Problem statement

Write a program to convert a given Rupees ( it may include paises also) into paises. Rupee and Paise are Indian currency denominations ( 1 Rupee = 100 paises).

Sample invocation 

             paiseConverter 34.565

Output

                Amount entered = 34.565 Rupees
                Total paises = 3965.0 Paises

Learning

  • How to split string?
  • Converting String to Double
  • Reading command line arguments
  • How to check a string is numeric type ? 

Know-how: Reading command line arguments - How it works?

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
amount = br.readLine();
  • System.in : It allows you to read from the standard input (mainly, the console)
  • InputStreamReader : It is a bridge from byte streams to character streams.It reads bytes and decodes them into characters using a specified charset. 
         It reads single character each time from console and groups characters.
  • BufferedReaders: It read large chunks of data from a file at once, and keep this data in a buffer. When you ask for the next character or line of data, it is retrieved from the buffer. In addition BufferedReader provides more convenient methods such as readLine(), that allow you to get the next line of characters from a file.
        It reads a line of data from InputStreamReader.

Tips

  • To display line numbers in eclipse : Window -> preferences -> General -> Text Editors -> Show Line numbers
  • Debugging in eclipse:  Place break points by double clicking on left most end on editor, select Debug perspective, run in debug mode (select cockroach symbol), once it reaches break point  select Step over (F6) or Step Into (F5) and keep watching the variable values.
  • Providing command line arguments through eclispe Run Configurations : Run -> Run Configurations -> Arguments -> Program arguments. To make eclipse to prompt for arguments every time we run, add ${string_prompt} in Program arguments. 
  • This program accepts input from eclipse console.

Source code