Tampilkan postingan dengan label coding. Tampilkan semua postingan
Tampilkan postingan dengan label coding. Tampilkan semua postingan

Core Java coding question converting String to BigDecimal

There are times while coding you need to convert an entity of one data type to another or validate a given input.



Q. Can you write a generic function that converts an amount in String to double amount?
A.

Step 1: Ask the right questions and arrive at a more detailed requirements.
  • Handling negative amounts like -34.01 or (34.01) with a parenthesis. Parentheses denote a negative value. 
  • Handling commas in formatted values like 1,205.45, etc.
  • Handling negative scenarios like amount being  empty as in ( ).
Since, it is a requirement to write a generic function, all the above scenarios need to be taken care of.

Step 2: Lets use a TDD (Test Driven Development approach).

So, write a skeleton class so that all our unit tests fail.

  
package com.mycompany.app5;

import java.math.BigDecimal;
import java.text.ParseException;

public class ConvertingAmount
{

public BigDecimal convert(String amount) throws ParseException
{
BigDecimal result = null;
return result;
}
}

Next, write the unit tests based on the above requirements so that all fail, but cover the requirements.

  
package com.mycompany.app5;

import java.math.BigDecimal;
import java.text.ParseException;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;

public class ConvertingAmountTest
{
private ConvertingAmount ca;

@Before
public void setUp()
{
ca = new ConvertingAmount();
}

@Test
public void testPositiveAmount() throws ParseException
{
BigDecimal converted = ca.convert("2255.001");
Assert.assertEquals(new BigDecimal("2255.001"), converted);
}

@Test
public void testNegativeAmount() throws ParseException
{
BigDecimal converted = ca.convert("-2255.001");
Assert.assertEquals(new BigDecimal("-2255.001"), converted);
}

@Test
public void testNegativeAmountWithParanthes() throws ParseException
{
BigDecimal converted = ca.convert("(2255.001)");
Assert.assertEquals(new BigDecimal("-2255.001"), converted);
}

@Test
public void testPosiotiveAmountFormatted() throws ParseException
{
BigDecimal converted = ca.convert("2,255.001");
Assert.assertEquals(new BigDecimal("2255.001"), converted);
}

@Test
public void testNegativeAmountFormatted() throws ParseException
{
BigDecimal converted = ca.convert("-2,255.001");
Assert.assertEquals(new BigDecimal("-2255.001"), converted);
}

@Test
public void testNegativeAmountWithParenthesesFormatted() throws ParseException
{
BigDecimal converted = ca.convert("(2,255.001)");
Assert.assertEquals(new BigDecimal("-2255.001"), converted);
}

@Test(expected = ParseException.class)
public void testExceptionalScenario() throws ParseException
{
String amount = "()";
ca.convert(amount);
}

@Test(expected = ParseException.class)
public void testExceptionalScenario2() throws ParseException
{
String amount = "abc";
ca.convert(amount);
}
}




Step 3: Implement the functionality, so that all the above unit tests pass.

 
package com.mycompany.app5;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;

import org.apache.commons.lang.StringUtils;

public class ConvertingAmount
{

public BigDecimal convert(String amount) throws ParseException
{
BigDecimal result = null;

DecimalFormat df = new DecimalFormat("#,#00.00;-#,#00.00"); //positive;negative

//convert (2255.001) to -2255.001 and (2,255.001) to -2255.001
if (StringUtils.isNotBlank(amount) && amount.startsWith("(") && amount.endsWith(")"))
{
String valueStr = amount.substring(1, amount.length() - 1);
Number valInParenthesis = df.parse(valueStr.trim());
result = BigDecimal.valueOf(valInParenthesis.doubleValue()).negate();
amount = result.toPlainString();
}

//parse 2,255.001 and -2,255.001
Number val = df.parse(amount);
result = BigDecimal.valueOf(val.doubleValue());

return result;
}
}

Now, all green.


Read More..

Core Java multi thread coding printing odd and even numbers with two threads



Q. Can you write code to print odd and even numbers by two threads in sequence?
A. Even though this is not a practical question, a handy beginner level question test your ability to write multi-threaded code.

Here are the considerations.

  • It needs to be atomic so that the numbers can be printed in sequence. You can use either the AtomicInteger class or maintain two boolean flags like oddPrinted and evenPrinted  to coordinate between the two threads.
  • Both threads need to have a lock to coordinate odd and even printing. In Java, every object has a lock. So, we can create a Object lock = new Object( ) as the lock for both threads to use.
  • The Java Object class has wait and notify/notifyAll methods to facilitate inter thread communication via the Object lock. The notify/notifyAll methods notify the waiting threads to get hold of the lock. Only one thread can execute the code snippet that is synchronized on the lock.
  • You need a main method that creates a main thread and then spawn two new threads to print odd and even numbers respectively. 
 Here is the sample code.

Step 1: The main thread class PrintOddEvenNumbersWithTwoThreads that spawns the two new threads via the thread pool.

  
package com.mycompany.app6;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
* main thread
*/
public class PrintOddEvenNumbersWithTwoThreads
{
public static void main(String[] args)
{
final int max = 10;
final AtomicInteger i = new AtomicInteger(1); //start with 0
Executor dd = Executors.newFixedThreadPool(2);

final Object lock = new Object();

//the main thread spawns two threads to print odd and even numbers respectively
dd.execute(new OddNumber(max, i, lock));
dd.execute(new EvenNumber(max, i, lock));

do
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}

while (i.get() != max + 1);

System.out.println("
Done");
System.exit(0);
}
}


Step 2: The OddNumber thread that prints odd numbers.

  
package com.mycompany.app6;

import java.util.concurrent.atomic.AtomicInteger;

public class OddNumber implements Runnable
{
private int maxNumber;
private AtomicInteger number;
private Object lock;

public OddNumber(int maxNumber, AtomicInteger number, Object lock)
{
this.maxNumber = maxNumber;
this.number = number;
this.lock = lock;
}

public void run()
{
print();
}

public void print()
{
while (number.get() < maxNumber + 1)
{
if (number.get() % 2 == 0)
{
System.out.println(Thread.currentThread().getName() + " --> " + number.getAndAdd(1));

synchronized (lock)
{
lock.notifyAll();//notify all waiting threads on this lock to resume
}
}
else
{
synchronized (lock)
{
try
{
lock.wait(); //wait for the lock
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}

}



Step 3: The EvenNumber thread that prints even numbers. The implementation is very similar except for the boundary condition that checks for odd or even number.

  
package com.mycompany.app6;

import java.util.concurrent.atomic.AtomicInteger;

public class EvenNumber implements Runnable
{
private int maxNumber;
private AtomicInteger number;
private Object lock;

public EvenNumber(int maxNumber, AtomicInteger number, Object lock)
{
this.maxNumber = maxNumber;
this.number = number;
this.lock = lock;
}

public void run()
{
print();
}

public void print()
{
while (number.get() < maxNumber + 1)
{
if (number.get() % 2 != 0)
{
System.out.println(Thread.currentThread().getName() + " --> " + number.getAndAdd(1));

synchronized (lock)
{
lock.notify(); //notify all waiting threads on this lock to resume
}
}
else
{
synchronized (lock)
{
try
{
lock.wait(); //wait for the lock
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}

}





Step 4: Run the main thread class PrintOddEvenNumbersWithTwoThreads to execute the code.

The output:

  
pool-1-thread-2 --> 1
pool-1-thread-1 --> 2
pool-1-thread-2 --> 3
pool-1-thread-1 --> 4
pool-1-thread-2 --> 5
pool-1-thread-1 --> 6
pool-1-thread-2 --> 7
pool-1-thread-1 --> 8
pool-1-thread-2 --> 9
pool-1-thread-1 --> 10

Done



There are other alternative approaches as described in the NumberGenerator class.
Read More..

Why use Override annotation in Java Coding Best Practice

@Override annotation was added in JDK 1.5 and it is used to instruct compiler that method annotated with @Override 
is an overridden method from super classor interface. Though it may look trivial @Override is particularly useful while
overriding methods which accept Object as parameter just like equals, compareToor compare() method of Comparator 
interface. @Override is one of the three built in annotation provided by Java 1.5, other two are @SuppressWarnings and @Deprecated. Out of these three @Override is most used because of its general nature, while @SuppressWarnings is also used while using Generics, @Deprecated is mostly for API and library. If you have read my article common errors while overriding equals method than you have see that one of the mistake Java programmer makes it,  write equals method with non object argument type as shown in below example:
Read more »
Read More..