Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (4k points)

Consider the code below:

DummyBean dum = new DummyBean();



// prints 'foo' DummyBean dumtwo = dum; System.out.println(dumtwo.getDummy());

// prints 'foo' dum.setDummy("bar"); System.out.println(dumtwo.getDummy());

// prints 'bar' but it should print 'foo'

So, I want to copy the dum to dumtwo and change dumwithout affecting the dumtwo. But the code above is not doing that. When I change something in dum, the same change is happening in dumtwo also.

I guess, when I say dumtwo = dum, Java copies the reference only. So, is there any way to create a fresh copy of dum and assign it to dumtwo?

1 Answer

0 votes
by (46k points)

Using Apache Commons StringUtils.isNumeric() to verify if String is valid number

Here are a couple of examples for different input to check if String is a valid number or not, this will give you a good idea of how this method works and what you can expect from this method.

StringUtils.isNumeric(null) = false

StringUtils.isNumeric("") = false

StringUtils.isNumeric(“ '') = false

StringUtils.isNumeric("123") = true

StringUtils.isNumeric("ab2c") = false

StringUtils.isNumeric("-123") = false

StringUtils.isNumeric("+123") = false

StringUtils.isNumeric("12 3") = false

StringUtils.isNumeric("12-3") = false

StringUtils.isNumeric("12.3") = false

Just note there are a couple of interesting changes in Apache commons-lang 2.5 and 3.0, the 3.0 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence). The Apache commons-lang 3.0 also changed empty String " " to return false and not true, which is a very important change.

Now, let's use the isNumber() method to check if String is a valid number or not

NumberUtils.isNumber(null) = false

NumberUtils.isNumber("") = false

NumberUtils.isNumber(" ") = false

NumberUtils.isNumber("123") = true

NumberUtils.isNumber("ab2c") = false

NumberUtils.isNumber("-123") = true

NumberUtils.isNumber("+123") = false

NumberUtils.isNumber("12 3") = false

NumberUtils.isNumber("12-3") = false

NumberUtils.isNumber("12.3") = true

Since Apache commons-lang 3.3 this process also supports hex 0Xhhh and octal 0ddd validation. As I said before, you can also use a regular expression to check if given String is empty or not but you need to be very careful about covering all scenarios covered by these libraries. I would not recommend you to reinvent the wheel. Even Joshua Bloch has advised in "Effective Java" that always prefer library method than writing your routine. One of the main reasons for that is testing exposure, your routing will not get the free testing by millions of programs which a library method is exposed too.

Related questions

0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories