Converting Strings to Number in Javascript: Pitfalls

There are many ways to convert a String to a Number. I can think of at least 5 ways to convert a string into a number! parseInt(num); // default way (no radix) parseInt(num, 10); // parseInt with radix (decimal) parseFloat(num) // floating point Number(num); // Number constructor ~~num //bitwise not num / 1 // diving…

java String intern

What is String Interning ? String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. In Java, String class has a public method intern() that returns a canonical representation for the string object. Java’s String class privately maintains a pool of strings, where String literals are automatically interned. When the intern() method is invoked on a String object it…

convert string to json object

In JS To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in…

inputstream from/to string

Fast way I can think of is using the apache common api: StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, encoding); String theString = writer.toString(); Copy method can either use Charset.forName(“UTF-8”) or take String “UTF-8” directly. Or Even easier: String myString = IOUtils.toString(myInputStream, “UTF-8”);     Opposite: public class StringToStream {     public static void main(String[] args)…

generate random alpha-numeric string in Java

1. Manually generate: static final String AB = “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ”; static Random rnd = new Random(); String randomString( int len ) {    StringBuilder sb = new StringBuilder( len );    for( int i = 0; i < len; i++ )       sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );    return sb.toString(); } 2. Dollar provides…

Difference between StringTokenizer and split

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the splitmethod of String or the java.util.regex package instead.   String.split() returns an array (String[]) and Tokenizer returns one token at a time.