Tampilkan postingan dengan label core. Tampilkan semua postingan
Tampilkan postingan dengan label core. Tampilkan semua postingan

Personal pc Discount Acer Veriton Core i5 500GB HDD 4GB DDR3 Desktop PC

Inexpensive Acer Veriton Core i5 500GB HDD 4GB DDR3 Desktop PC Motivate it These days

Evaluations: Acer Veriton Core i5 500GB HDD 4GB DDR3 Desktop PC

Acer Veriton Core i5 500GB HDD 4GB DDR3 Desktop PC

Acer Veriton Core i5 500GB HDD 4GB DDR3 Desktop PC Understand it Now

Create a clear view to your bottom line with the Veriton X Series. These compact desktops handle challenging tasks with powerful components and advanced technologies, and they provide ample support and security for your company's network. Accessibility is easy with the modular, tool-less design. Energy savings are also great for cutting costs-Features-Full power - Creating more desk space than a standard PC, the Veriton X Series proves its value with every task. Everything goes faster with up to the latest Intel Core processing and efficient graphics-Managed - System setup is effortless with Veriton ControlCenter. Optimize energy settings, set frequently used applications to automatically load, transfer data and personal settings to another PC, and protect your data from threats with handy utilities and an easy-to-use interface. Achieve better asset management, reduce downtime, and minimize desk-side MIS calls with Acer Smart Client Manager-Specifications-Windows 7 Professional - Windows 8 Pro - 64-bit dual-load OS - 3GHz Intel Core i5-3330 Processor (6MB Intel Smart Cache, 4-Core), up to 3.2GHz with Intel Turbo Boost - 4GB DDR3-1600 SDRAM - 500GB 7200RPM hard drive - Intel HD Graphics 2500 - Intel B75 Express chipset - DVD R/RW DL Writer - Gigabit LAN - 1 PCIe x1, 1 PCIe x16 - 4 USB 3.0, 2 USB 2.0, DVI, Audio in/out - USB keyboard and optical mouse - 3-year limited warranty Monitor is not included

Read more »
Read More..

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 Interview Questions and Answers String concatenation



It is a very common beginner level question on String concatenation. Its imperative to understand that NOT all String concatenations are  bad. It depends on how you are using it. You need to have the basic understanding that in Java, String is an immutable object and StringBuilder (not thread-safe) and StringBuffer (thread-safe) are mutable. In, Java you can concatenate strings a number of ways with the "+" operator, using the append( ) in StringBuilder and StringBuffer classes, and the other methods like concat( ) in String class.

Q1. Is anything wrong with the following code?

public class StringConcat {
public static String withStringBuilder(int count) {
String s = "Hello" + " " + " peter " + count;
return s;
}

}
 
A1. No, the compiler internally uses a StringBuilder to use two append( ) calls to append the string and converts it to a String object using the toString( ) method.

Note: you can try the javap command  described below to see why.


Q2. Is anything wrong with the following code?
public class StringConcat {
public static String withStringBuilder() {
String s = "Hello" + " " + " peter " + " how are you";
return s;
}

}
 
A2. No, the compiler is smart enough to work out that it is a static concatenation and it uses its optimization to concatenate the string during compile-time. If you verify this by using a Java decompiler like jd-gui.exe to decompile the compiled class back, you will get the source code as below.
 
public class StringConcat
 {
public static String withStringBuilder(int count)
{
String s = "Hello peter how are you";
return s;
}
}

You can also use the javap command to dissemble the compiled class file using the following command
 
C:workspacesprojTestsrc>javap -c StringConcat

Gives the following output
 
Compiled from "StringConcat.java"
public class StringConcat extends java.lang.Object{
public StringConcat();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return

public static java.lang.String withStringBuilder(int);
Code:
0: ldc #2; //String Hello peter how are you
2: astore_1
3: aload_1
4: areturn

}

The line 0 shows that it has been optimized


Q3. Is anything wrong with the following code snippet

public class StringConcat {

public static String withoutStringBuilder(int count) {
String str = "";
for (int i = 0; i < count; i++) {
str += i;
}

return str;
}

}
 
A3. Yes. it consumes more memory and can have performance implications. This is because, a String object in Java is immutable. This means, you cant modify a String. If the value of count is 100, then the above code will create 100 new StringBuilder objects, of which 99 of them will be discarded for garbage collection. Creating new objects unnecessarily is not efficient, and the garbage collector needs to clean up those unreferenced 99 objects. StringBuffer and StringBuilder: are mutable and use them when you want to modify the contents. StringBuilder was added in Java 5 and it is identical in all respects to StringBuffer except that it is not synchronized, which makes it slightly faster at the cost of not being thread-safe. The code below creates only two new objects, the StringBuilder and the final String that is returned.
public class StringConcat {

public static String withStringBuilder(int count) {
StringBuilder sb = new StringBuilder(100);
for (int i = 0; i < count; i++) {
sb.append(i);
}

return sb.toString();
}

}
 
Now, if you want to be more pedantic as to how we know that the 100 StringBuilder objects are created, we can use the javap option to our rescue. The javap is a class file dissembler. If you compile the codebase in the question and then run the javap command with the StringConcat.class file as shown below
C:workspacesproj_blueTestsrc>javap -c StringConcat

You will get an output as shown below
 
Compiled from "StringConcat.java"
public class StringConcat extends java.lang.Object{
public StringConcat();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return

public static java.lang.String withoutStringBuilder(int);
Code:
0: ldc #2; //String
2: astore_1
3: iconst_0
4: istore_2
5: iload_2
6: iload_0
7: if_icmpge 35
10: new #3; //class java/lang/StringBuilder
13: dup
14: invokespecial #4; //Method java/lang/StringBuilder."<init>":()V
17: aload_1
18: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
21: iload_2
22: invokevirtual #6; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
25: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
28: astore_1
29: iinc 2, 1
32: goto 5
35: aload_1
36: areturn

}

The dissembled looks cryptic, but if you inspect it carefully the code within the public static java.lang.String withoutStringBuilder(int);

Line 5 to 32: is the code within the for loop. The "goto 5" indicates looping back.
Line 10: creates a new StringBuilder object every time
Line 18: uses the StringBuilders append method to concatenate the String.
Line 25: uses the toString( ) method to convert the StringBuilder back to the existing String reference via toString( ) method.

If you run the improved code snippet in the answer through javap, you get the following output
Compiled from "StringConcat.java"
public class StringConcat extends java.lang.Object{
public StringConcat();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return

public static java.lang.String withStringBuilder(int);
Code:
0: new #2; //class java/lang/StringBuilder
3: dup
4: bipush 100
6: invokespecial #3; //Method java/lang/StringBuilder."<init>":(I)V
9: astore_1
10: iconst_0
11: istore_2
12: iload_2
13: iload_0
14: if_icmpge 29
17: aload_1
18: iload_2
19: invokevirtual #4; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
22: pop
23: iinc 2, 1
26: goto 12
29: aload_1
30: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
33: areturn

}

As you could see

Line 0 to 6: initializes one StringBuilder object outside the for loop.
Line 12 to 26: is the for loop.
Line 19: indicates that since the StringBuilder is mutable, the string is appended via the append method.


Important: The creation of extra strings is not limited to the overloaded mathematical operator "+", but there are several other methods like concat( ), trim( ), substring( ), and replace( ) in the String class that generate new string instances. So use StringBuffer or StringBuilder for computation intensive operations to get better performance. Experiment with javap for the String methods like concat( ), trim( ), substring( ), and replace( ) .

Note: So, javap and jd-gui.exe are handy tools for debugging your application for certain issues. For example, the java decompiler is handy for debugging generics to see how the java source code with generics is converted after compilation by decompiling the .class file back to source code.
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..