Check if a String is a Balanced String

A balanced String is a String with equal number of opening and closing matched brackets. In other words, an expression consisting of matching opening and closing brackets are called balanced strings. For instance, "adf(aew)23[34v3a*23]ade(we{wefave}qwef)ad[e[qew]]" is a balanced string, because after removing all the characters it is left with "()[]({})[[]]". How to check the expression To check if an expression contains balanced brackets we can use Stack. A stack has push() for insertion and pop() for deletion. We can use this to check if a closing bracket is matched with the last element of the stack (top of the stack). Steps to check the expression: 1. Create a Character Stack and push the character if it matches '(' or '[' or '{'. 2. If the character of the expression contains either…
Read More

Difference between equals operator == and equals() method

For comparison of two variable for their equality Java offers two methods. Equals operator ==, and equals() method in Object class. Since both of them checks the equality of L.H.S. and R.H.S. then what is the difference between them? Difference lies in the definition The difference lies in the definition of the operator and the method. The definition of == says that the operator compares the value inside the variable available on both sides. And the definition of the equals() method changes as per the implementation in the corresponding class. To understand the difference take a scenario of String objects. We have three String variables viz. s1, s2 and s3. String s1 = "hello"; String s2 = "hello"; String s3 = new String("hello"); Based on the above initialization, what would…
Read More

Difference between concat() and concat operator ‘+’ in java

When there is a need to concatenate two or more strings in java we generally use the concatenation operator '+'. But, for the same purpose we should prefer using concat() method from String class. After a closer look at the size of .class files which is generated after compiling the code, it is revealed that the size of the .class file containing '+' operator exceeds by a greater margin than the .class file performing the same concatenation but by using concat() method. ConcatFunDemo uses the concat() of String class: class ConcatFunDemo { public static void main(String[] s) { String s1 = "www."; String s2 = "pcsalt."; String s3 = "com"; System.out.println(s1.concat(s2).concat(s3)); } } ConcatOpDemo uses the concatenation operator (+): class ConcatOpDemo { public static void main(String[] s) { String s1…
Read More