7.31.2014

String: startsWith() - Tests if this string starts with the specified prefix

If you want to get whether a string starts with a specified string, you can use the java.lang.String class's two overloaded startsWith() method. It returns true if the string contains the prefix or false otherwise.

In single argument startsWith() method, the only argument is the string that is the prefix in the specified string.

In two argument startsWith() method, the first argument is the prefix and the second one is the position or offset, from where you would like to check.

Some points about the startsWith() method is given below:

  • You can use this method with string literal. Example: "Java".startsWith("J").
  • If you pass null as the first argument to this method, it will always return true.


Method Declaration:
public boolean startsWith(String prefix)
public boolean startsWith(String prefix, int toffset)

Live Example:
public class Demo {
    public static void main(String[] args) {
        String url = "Learn Java API";
        System.out.println("url: " + url);
        System.out.println("url.startsWith(\"Learn\"): " +url.startsWith("Learn"));
        System.out.println("url.startsWith(\"L\"): " + url.startsWith("L"));
        System.out.println("url.startsWith(\"\"): " + url.startsWith(""));
        System.out.println("url.startsWith(\"Java\"): " + url.startsWith("Java"));
        System.out.println("url.startsWith(\"Learn Java API Now\"): " + url.startsWith("Learn Java API Now"));
        
        System.out.println("url.startsWith(\"Learn\", 0): " + url.startsWith("Learn", 0));
        System.out.println("url.startsWith(\"Learn\", 1): " + url.startsWith("Learn", 1));
        System.out.println("url.startsWith(\"Java\", 6): " + url.startsWith("Java", 6));
        System.out.println("url.startsWith(\"Java\", 5): " + url.startsWith("Java", 5));
    }
}

Output:
url: Learn Java API
url.startsWith("Learn"): true
url.startsWith("L"): true
url.startsWith(""): true
url.startsWith("Java"): false
url.startsWith("Learn Java API Now"): false
url.startsWith("Learn", 0): true
url.startsWith("Learn", 1): false
url.startsWith("Java", 6): true
url.startsWith("Java", 5): false

Use the social sharing button below to spread the knowledge among others.

7.30.2014

Math: min() - Returns the smaller of two numbers

In order to return the smaller of two numbers, java.lang.Math class provides four static overloaded min() methods. The min() method takes two numbers as arguments and return the greater of the two.

The four overloaded min() methods are for int, long, float and double.

Some points about the min() method is given below:

  • If the two arguments are same, the method returns the same value.
  • The method always returns the value which is closer to the negative infinity or minimum value allowed for that data type.
  • For float and double, if one of the value is NaN, then the method returns NaN.
  • If one argument is positive zero and the other negative zero, the result is positive zero.
  • It is simple to nest multiple min() method.


Method Declaration:
public static int min(int a, int b)
public static long min(long a,long b)
public static float min(float a, float b)
public static double min(double a,double b)

Live Example:
import static java.lang.Double.NaN;

public class Demo {
    public static void main(String[] args) {
        System.out.println("Math.min(65, 20): " + Math.min(65, 20));
        System.out.println("Math.min(57L, 85L): " + Math.min(57L, 85L));
        System.out.println("Math.min(15.5F, 15.499F): " + Math.min(15.5F, 15.499F));
        System.out.println("Math.min(51.0, 51.01): " + Math.min(51.0, 51.01));
        System.out.println("Math.min(-0, +0): " + Math.min(-0, +0));
        System.out.println("Math.min(NaN, 45758345): " + Math.min(NaN, 45758345));
        System.out.println("Math.min(3, Math.min(7, 4)): " + Math.min(3, Math.min(7, 4)));
    }
}

Output:
Math.min(65, 20): 20
Math.min(57L, 85L): 57
Math.min(15.5F, 15.499F): 15.499
Math.min(51.0, 51.01): 51.0
Math.min(-0, +0): 0
Math.min(NaN, 45758345): NaN
Math.min(3, Math.min(7, 4)): 3

Use the social sharing button below to spread the knowledge among others.

Math: max() - Returns the greater of two numbers

In order to return the greater of two numbers, java.lang.Math class provides four static overloaded max() methods. The max() method takes two numbers as arguments and return the greater of the two.

The four overloaded max() methods are for int, long, float and double.

Some points about the max() method is given below:
  • If the two arguments are same, the method returns the same value.
  • The method always returns the value which is closer to the positive infinity or maximum value allowed for that data type.
  • For float and double, if one of the value is NaN, then the method returns NaN.
  • If one argument is positive zero and the other negative zero, the result is positive zero.
  • It is simple to nest multiple max() method.


Method Declaration:
public static int max(int a, int b)
public static long max(long a,long b)
public static float max(float a, float b)
public static double max(double a,double b)

Live Example:
import static java.lang.Double.NaN;

public class Demo {
    public static void main(String[] args) {
        System.out.println("Math.max(65, 20): " + Math.max(65, 20));
        System.out.println("Math.max(57L, 85L): " + Math.max(57L, 85L));
        System.out.println("Math.max(15.5F, 15.499F): " + Math.max(15.5F, 15.499F));
        System.out.println("Math.max(51.0, 51.01): " + Math.max(51.0, 51.01));
        System.out.println("Math.max(-0, +0): " + Math.max(-0, +0));
        System.out.println("Math.max(NaN, 45758345): " + Math.max(NaN, 45758345));
        System.out.println("Math.max(3, Math.max(7, 4)): " + Math.max(3, Math.max(7, 4)));
    }
}

Output:
Math.max(65, 20): 65
Math.max(57L, 85L): 85
Math.max(15.5F, 15.499F): 15.5
Math.max(51.0, 51.01): 51.01
Math.max(-0, +0): 0
Math.max(NaN, 45758345): NaN
Math.max(3, Math.max(7, 4)): 7

Use the social sharing button below to spread the knowledge among others.

7.27.2014

Arrays: sort() – Sorts an array

In order to sort an array, java.util.Arrays class provides 18 overloaded sort() method for not only primitive types(excluding boolean) and Object, but also your custom sort implementation for your own objects.

For single argument (primitive types) sort() method, it sorts the specified array in ascending numerical order.

For three argument (primitive types) sort() method, the first argument is the array to be sorted, the second argument is the starting index fromIndex, inclusive, and the third index is the last index toIndex, exclusive. If fromIndex == toIndex, the range to be sorted is empty.

By passing Object array to the sort() method, it sorts the specified array in ascending numerical order, according to the natural ordering of its elements. All elements must implement the Comparable interface. Furthermore, all elements in this range must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

Exception:
IllegalArgumentException - if fromIndex > toIndex
IllegalArgumentException - (optional) if the natural ordering of the array elements is found to violate the Comparable contract
ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > array.length
ClassCastException - if the array contains elements that are not mutually comparable (for example, strings and integers)

Method Declaration:
public static void sort(byte[] a)
public static void sort(short[] a)
public static void sort(int[] a)
public static void sort(long[] a)
public static void sort(float[] a)
public static void sort(double[] a)
public static void sort(char[] a)
public static void sort(Object[] a)

public static void sort(byte[] a,  int fromIndex, int toIndex)

public static void sort(short[] a, int fromIndex, int toIndex)
public static void sort(int[] a, int fromIndex, int toIndex)
public static void sort(long[] a, int fromIndex, int toIndex)
public static void sort(float[] a, int fromIndex, int toIndex)
public static void sort(double[] a, int fromIndex, int toIndex)
public static void sort(char[] a, int fromIndex, int toIndex)
public static void sort(Object[] a, int fromIndex, int toIndex)

public static <T> void sort(T[] a, Comparator<? super T> c)

public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)

Live Example:
import java.util.Arrays;

public class Demo {
    public static void main(String[] args) {
        byte[] byteArray = {7, 0, 2, 6, 1 , 5, 1};
        short[] shortArray = {10, 7, 12, 0, 4, 15, 20};
        int[] intArray = {30, 25, 16 , 26, 40, 35};
        long[] longArray = {111L, 256L, 55L, 280L, 180L};
        float[] floatArray = {3.5F, 0.1F, 6.2F, 2.8F, 4.3F};
        double[] doubleArray = {10.15, 12.40, 7.5, 11.50, 8.9, 6.3};
        char[] charArray = {'x', 'c', 'd', 'a', 'm', 'k', 'j'};
        String[] stringArray = {"egg", "doll", "bat", "cat", "flower", "apple"};
        
      
        System.out.println("byteArrary: " + Arrays.toString(byteArray));
        Arrays.sort(byteArray);
        System.out.println("Arrays.sort(byteArray): " + Arrays.toString(byteArray) + "\n");
        System.out.println("shortArrary: " + Arrays.toString(shortArray));
        Arrays.sort(shortArray, 0, shortArray.length);
        System.out.println("Arrays.sort(shortArrary, 0, 4): " + Arrays.toString(shortArray) + "\n");
        System.out.println("intArrary: " + Arrays.toString(intArray));
        Arrays.sort(intArray, 2, 6);
        System.out.println("Arrays.sort(intArray, 2, 6): " + Arrays.toString(intArray) + "\n");
        System.out.println("longArrary: " + Arrays.toString(longArray));
        Arrays.sort(longArray, 0, 0);
        System.out.println("Arrays.sort(longArray, 0, 0): " + Arrays.toString(longArray) + "\n");
        System.out.println("floatArrary: " + Arrays.toString(floatArray));
        Arrays.sort(floatArray, 4, 4);
        System.out.println("Arrays.sort(floatArray, 4, 4): " + Arrays.toString(floatArray) + "\n");
        try {
            System.out.println("doubleArrary: " + Arrays.toString(doubleArray));
            Arrays.sort(doubleArray, 4, 1);
        } catch(IllegalArgumentException illArgExp) {
            System.out.println("Arrays.sort(doubleArray, 4, 1): " + illArgExp.getMessage() + "\n");
        }
        try {
            System.out.println("charArrary: " + Arrays.toString(charArray));
            Arrays.sort(charArray, 0, 10);
        } catch(ArrayIndexOutOfBoundsException arrIndOutBndExp) {
            System.out.println("Arrays.sort(charArray, 0, 10): " + arrIndOutBndExp.getMessage() + "\n");  
        }
        System.out.println("stringArrary: " + Arrays.toString(stringArray));
        Arrays.sort(stringArray);
        System.out.println("Arrays.sort(stringArray): " + Arrays.toString(stringArray));
    }  
}


Output: 
byteArrary: [7, 0, 2, 6, 1, 5, 1]
Arrays.sort(byteArray): [0, 1, 1, 2, 5, 6, 7]

shortArrary: [10, 7, 12, 0, 4, 15, 20]
Arrays.sort(shortArrary, 0, 4): [0, 4, 7, 10, 12, 15, 20]

intArrary: [30, 25, 16, 26, 40, 35]
Arrays.sort(intArray, 2, 6): [30, 25, 16, 26, 35, 40]

longArrary: [111, 256, 55, 280, 180]
Arrays.sort(longArray, 0, 0): [111, 256, 55, 280, 180]

floatArrary: [3.5, 0.1, 6.2, 2.8, 4.3]
Arrays.sort(floatArray, 4, 4): [3.5, 0.1, 6.2, 2.8, 4.3]

doubleArrary: [10.15, 12.4, 7.5, 11.5, 8.9, 6.3]
Arrays.sort(doubleArray, 4, 1): fromIndex(4) > toIndex(1)

charArrary: [x, c, d, a, m, k, j]
Arrays.sort(charArray, 0, 10): Array index out of range: 10

stringArrary: [egg, doll, bat, cat, flower, apple]
Arrays.sort(stringArray): [apple, bat, cat, doll, egg, flower]

Use the social sharing button below to spread the knowledge among others.

7.26.2014

Arrays: toString() – Returns string representation of an array

Normally if you want to get  the string representation of the contents of an array, you need to traverse the array using loop constructs. But java.util.Arrays class provides nine overloaded toString() methods to return the string representation of the contents of the specified array which is passed as the only argument to the method.

The string representation consists of a list of the array's elements, enclosed in square brackets ([]). Adjacent elements are separated by the characters “, ” (a comma followed by a space). Elements are converted to strings as by String.valueOf(array_type). Returns "null" if the passed array is null.

Method Declaration:
public static String toString(boolean[] a)
public static String toString(byte[] a)
public static String toString(short[] a)
public static String toString(int[] a)
public static String toString(long[] a)
public static String toString(float[] a)
public static String toString(double[] a)
public static String toString(char[] a)
public static String toString(Object[] a)

Live Example:


import java.util.Arrays;

public class Demo {
    public static void main(String[] args) {
        boolean[] booleanArray = {true, false, false, true, false};
        byte[] byteArray = {7, 0, 2, 6, 1 , 5, 1};
        short[] shortArray = {10, 7, 12, 0, 4, 15, 20};
        int[] intArray = {30, 25, 16 , 26, 40, 35};
        long[] longArray = {111L, 256L, 55L, 280L, 180L};
        float[] floatArray = {3.5F, 0.1F, 6.2F, 2.8F, 4.3F};
        double[] doubleArray = {10.15, 12.40, 7.5, 11.50, 8.9, 6.3};
        char[] charArray = {'x', 'c', 'd', 'a', 'm', 'k', 'j'};
        String[] stringArray = {"egg", "doll", "bat", "cat", "flower", "apple"};
        
        System.out.println("booleanArrary: " + Arrays.toString(booleanArray));
        System.out.println("byteArrary: " + Arrays.toString(byteArray));
        System.out.println("shortArrary: " + Arrays.toString(shortArray));
        System.out.println("intArrary: " + Arrays.toString(intArray));
        System.out.println("longArrary: " + Arrays.toString(longArray));
        System.out.println("floatArrary: " + Arrays.toString(floatArray));
        System.out.println("doubleArrary: " + Arrays.toString(doubleArray));
        System.out.println("charArrary: " + Arrays.toString(charArray));
        System.out.println("stringArrary: " + Arrays.toString(stringArray));
    }  
}


Output: 
booleanArrary: [true, false, false, true, false]
byteArrary: [7, 0, 2, 6, 1, 5, 1]
shortArrary: [10, 7, 12, 0, 4, 15, 20]
intArrary: [30, 25, 16, 26, 40, 35]
longArrary: [111, 256, 55, 280, 180]
floatArrary: [3.5, 0.1, 6.2, 2.8, 4.3]
doubleArrary: [10.15, 12.4, 7.5, 11.5, 8.9, 6.3]
charArrary: [x, c, d, a, m, k, j]
stringArrary: [egg, doll, bat, cat, flower, apple]



Use the social sharing button below to spread the knowledge among others.

7.25.2014

String: contains() - Checks whether a CharSequence is present in a String

If you want to check whether a string contains a specified character sequence that implements CharSequence interface (String, StringBuffer, StringBuilder), you can use contains() method defined in java.lang.String class. This method takes a character sequence as single argument and return true if the specified argument is present in the string or false if it doesn’t.

Some critical points to be noted:
  • A CharSequence must be enclosed in double quotes (“a” and “abc” both are CharSequence).
  • If you pass empty string (“”), the method will always return true.

Exception:
If the passed argument is null, NullPointerException will be thrown.

Method Declaration:
public boolean contains(CharSequence s)

Live Example:


public class Demo {
    public static void main(String[] args) {
          String blogTitle = "Learn Java API";
          System.out.println("blogTitle: " + blogTitle);
          System.out.println("blogTitle.contains(\"Java\"): " + blogTitle.contains("Java"));
          System.out.println("blogTitle.contains(\"java\"): " + blogTitle.contains("java"));
          System.out.println("blogTitle.contains(\"j\"): " + blogTitle.contains("j"));
          System.out.println("blogTitle.contains(\"J\"): " + blogTitle.contains("J"));
          System.out.println("blogTitle.contains(\"\"): " + blogTitle.contains(""));
          System.out.println("blogTitle.contains(\"\\n\"): " + blogTitle.contains("\n"));
          try {
              System.out.println("blogTitle.contains(null): " + blogTitle.contains(null));
          } catch (NullPointerException nullPtrExp) {
              System.out.println("blogTitle.contains(null): " + "You can't pass null!!!");
          }       
    }  
}
Output: 
blogTitle: Learn Java API
blogTitle.contains("Java"): true
blogTitle.contains("java"): false
blogTitle.contains("j"): false
blogTitle.contains("J"): true
blogTitle.contains(""): true
blogTitle.contains("\n"): false
blogTitle.contains(null): You can't pass null!!!



Use the social sharing button below to spread the knowledge among others.

Math: abs() - Returns the absolute value of a number

To get the absolute value of a number, java.lang.Math class defines four static overloaded abs() methods that takes an int or long or float or double as its only argument and returns the absolute value of that passed argument.

The following rules apply for this methods:
  • If the passed argument is positive, then this method returns the argument.
  • If the passed argument is negative, this method returns the negation of the argument.
  • If the argument is positive zero or negative zero, the result is positive zero.
  • If the argument is infinite, the result is positive infinity.
  • If the argument is NaN, the result is NaN.

Method Declaration:
public static int abs(int a)
public static long abs(long a)
public static float abs(float a)
public static double abs(double a)

Live Example:
import static java.lang.Double.NaN;

public class Demo {
    public static void main(String[] args) {
        System.out.println("Absolute value of -0 is " + Math.abs(-0));
        System.out.println("Absolute value of 0 is " + Math.abs(0));
        System.out.println("Absolute value of 2 is " + Math.abs(2));
        System.out.println("Absolute value of -111L is " + Math.abs(-111L));
        System.out.println("Absolute value of 5.96 is " + Math.abs(5.96));
        System.out.println("Absolute value of -20.5F is " + Math.abs(-20.5F));
        System.out.println("Absolute value of NaN is " + Math.abs(NaN));
    }  
}

Output: 
Absolute value of -0 is 0
Absolute value of 0 is 0
Absolute value of 2 is 2
Absolute value of -111L is 111
Absolute value of 5.96 is 5.96
Absolute value of -20.5F is 20.5
Absolute value of NaN is NaN

Use the social sharing button below to spread the knowledge among others.