JSTL forTokens tag is another tag in core JSTL library to support Iteration or looping. It effectively complements, more useful <c:forEach> tag, by allowing you to iterate over comma separated or any delimited String. You can use this tag to split string in JSP and can operate on them individually. forTokens tag has similar attribute like forEach JSTL tag except one more attribute called delims, which specifies delimiter. For example to iterate over colon separated String "abc:cde:fgh:ijk", delims=":". By the way, forTokens tag also accept multiple delimiter, which means, you can split a big string into token based upon multiple delimiter e.g. colon(:) and pipe (|), This will be more clear, when we will see examples of JSTL forTokens tag in JSP. Rest of attribute e.g. items, var, varStatus, begin, end and step are same, as they are in case of <c:forEach> tag. For quick review, items specify String which needs to be split-ed in token and var hold current String.
Tampilkan postingan dengan label string. Tampilkan semua postingan
Tampilkan postingan dengan label string. Tampilkan semua postingan
Core Java coding question converting String to BigDecimal
Label:
bigdecimal,
coding,
converting,
core,
java,
question,
string,
to
And 0
komentar
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.
Step 2: Lets use a TDD (Test Driven Development approach).
So, write a skeleton class so that all our unit tests fail.
Next, write the unit tests based on the above requirements so that all fail, but cover the requirements.
Step 3: Implement the functionality, so that all the above unit tests pass.
Now, all green.
Read More..
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 ( ).
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.
Core Java Interview Questions and Answers String concatenation
Label:
and,
answers,
concatenation,
core,
interview,
java,
questions,
string
And 0
komentar
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"The line 0 shows that it has been optimized
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
}
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"The dissembled looks cryptic, but if you inspect it carefully the code within the public static java.lang.String withoutStringBuilder(int);
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
}
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"As you could see
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
}
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.
5 ways to check if String is empty in Java examples
String in Java is considered empty if its not null and it’s length is zero. By the way before checking length you should verify that String is not null because calling length() method on null String will result in java.lang.NullPointerException. Empty String is represented by String literal “”. Definition of empty String may be extended to those String as well which only contains white space but its an specific requirement and in general String with white space are not considered as empty String in Java. Since String is one of the most frequently used class and commonly used in method arguments, we often needs to check if String is empty or not. Thankfully there are multiple ways to find if String is empty in Java or not. You can also count number of characters in String, as String is represented as character arrayand decide if String is empty or not. If count of characters is zero than its an empty String. In this Java String tutorial we going to see 5 ways to find if any String in Java is empty or not. Here are our five ways to check empty String :
How to convert decimal to binary octal and hex String in Java Program
This article is about a simple java program which converts decimal number to binary, octal and hexadecimal format. When it was first came into my mind I though I would probably need to write whole code to convert decimal to various other radix or base numbers but when I looked Integer class and saw these two way of converting decimal to binary etc I was simple amazed. It’s indeed extremely easy to do this in java and you can also write this program or use at it is.
Converting decimal to binary in Java Example
Java has many ways to change number system of particular number, you can convert any decimal number into either binary system, hexadecimal system or octal system by following same procedure. here is code example of converting any decimal number into binary number in Java.//first way
//decimal to binary
String binaryString = Integer.toBinaryString(number);
System.out.println("decimal to binary: " + binaryString);
//decimal to octal
String octalString = Integer.toOctalString(number);
System.out.println("decimal to octal: " + octalString);
//decimal to hexadecimal
String hexString = Integer.toHexString(number);
System.out.println("decimal to hexadecimal: " + hexString);
//second way
binaryString = Integer.toString(number,2);
System.out.println("decimal to binary using Integer.toString: " + binaryString);
//decimal to octal
octalString = Integer.toString(number,8);
System.out.println("decimal to octal using Integer.toString: " + octalString);
//decimal to hexadecimal
hexString = Integer.toString(number,16);
System.out.println("decimal to hexadecimal using Integer.toString: " + hexString);
Nice and little tip to convert decimal to binary or decimal to Octal, hex. This comes very handy many times when we want to do a quick conversion.
Related Java Tutorials
Langganan:
Postingan (Atom)

