Posts

Showing posts with the label Java

What is the difference between the add and offer methods in a Queue in Java?

If a collection refuses to add a particular element for any reason other than that it already contains the element, it  must throw  an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns. offer  method - tries to add an element to a queue, and returns  false  if the element can't be added (like in case when a queue is full), or  true  if the element was added, and doesn't throw any specific exception. add  method - tries to add an element to a queue, returns  true  if the element was added, or throws an IllegalStateException if no space is currently available. There is no difference for the implementation of  PriorityQueue.add : public boolean add ( E e ) { return offer ( e ); } For  AbstractQueue  there actually is a difference: public boolean add ( E e ) { if ( offer ( e )) ret...

Reverse the string without using any temporary variable?

1. We can use XOR logic for swapping the variables. public String reverseString(String str) {       char[] a = str.toCharArray();       int len = a.length-1;       int half = a.length/2;            for  ( int  i = 0; i < half; i++)        {             a[i] ^= a[len - i];             a[len - i] ^= a[i];             a[i] ^= a[len - i];        }         return String.valueOf(a); } 2.  Using built-in reverse() method of the StringBuilder class.     public void reverseString(String input)     {         StringBuilder input1 = new StringBuilder();         // append a string into StringBuilder input1         input1.append(input); ...

Sum of Digits in a given String

Source code in Java: public class Demo {         public static void main(String arg[])         {                   String s = " good23bad4 ";                   int sum = 0;                   for (char c : s.toCharArray())                   {                          if (Character.isDigit(c))                           {                                sum += Character.getNumericValue(c);                          }             ...