Friday, 13 April 2018

String to Date Example




  •         Java String to Date Example.
            This Java String to Date example shows how to convert Java String to Date object.
     */
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class JavaStringToDate {
            public static void main(String args[]){

                    //Java String having date
                    String strDate = “21/08/2011”;

                    /*
                     * To convert Java String to Date, use
                     * parse(String) method of SimpleDateFormat class.
                     *
                     * parse method returns the Java Date object.
                     */

                    try{

                            /*
                             * Create new object of SimpleDateFormat class using
                             * SimpleDateFormat(String pattern) constructor.
                             */

                            SimpleDateFormat sdf = new SimpleDateFormat(“dd/MM/yyyy”);

                            //convert Java String to Date using parse method of SimpleDateFormat
                            Date date = sdf.parse(strDate);

                            //Please note that parse method throws ParseException if the String date could not be parsed.

                            System.out.println(“Date is: “ + date);

                    }catch(ParseException e){
                            System.out.println(“Java String could not be converted to Date: “ + e);
                    }
            }
    }

    /*
    Output of Java String to Date example would be
    Fri Jan 21 00:00:00 IST 2011
    */

String to Lower Case example



  1. /*
            Java String to Lower Case example.
            This Java String to Lower Case example shows how to change the string to lower case
            using toLowerCase method of String class.
    */
    public class StringToLowerCaseExample {

            public static void main(String[] args) {

                    String str = “STRING TOLOWERCASE EXAMPLE”;

                    /*
                     * To change the case of string to lower case use,
                     * public String toLowerCase() method of String class.
                     *
                     */

                     String strLower = str.toLowerCase();

                     System.out.println(“Original String: “ + str);
                     System.out.println(“String changed to lower case: “ + strLower);
            }
    }

    /*
    Output would be
    Original String: STRING TOLOWERCASE EXAMPLE
    String changed to lower case: string tolowercase example
    */

String to UpperCase example



  1. /*
            Java String to Upper Case example.
            This Java String to Upper Case example shows how to change the string to upper case
            using toUpperCase method of String class.
    */

    public class StringToUpperCaseExample  
    {

            public static void main(String[] args)  
    {

                    String str = “string touppercase example”;

                    /*
                     * To change the case of string to upper case use,
                     * public String toUpperCase() method of String class.
                     *
                     */

                     String strUpper = str.toUpperCase();

                     System.out.println(“Original String: “ + str);
                     System.out.println(“String changed to upper case: “ + strUpper);
            }
    }

    /*
    Output would be
    Original String: string touppercase example
    String changed to upper case: STRING TOUPPERCASE EXAMPLE*/

String Trim Example



  1. /*
            Java String Trim Example.
            This Java String trim example shows how to remove leading and trailing space
            from string using trim method of Java String class.
    */

    public class RemoveLeadingTrailingSpace  
    {

            public static void main(String[] args)  
    {

                    String str = ”   String Trim Example   “;

                    /*
                     * To remove leading and trailing space from string use,
                     * public String trim() method of Java String class.
                     */

                     String strTrimmed = str.trim();

                     System.out.println(“Original String is: “ + str);
                     System.out.println(“Removed Leading and trailing space”);
                     System.out.println(“New String is: “ + strTrimmed);
            }
    }

    /*
    Output would be
    Original String is:    String Trim Example  
    Removed Leading and trailing space
    New String is: String Trim Example
    */

String Split Example



*
  • Java String split example.
    This Java String split example describes how Java String is split into multiple
    Java String objects.
    */

    public class JavaStringSplitExample{

      public static void main(String args[]){
      /*
      Java String class defines following methods to split Java String object.
      String[] split( String regularExpression )
      Splits the string according to given regular expression.
      String[] split( String reularExpression, int limit )
      Splits the string according to given regular expression. The number of resultant
      substrings by splitting the string is controlled by limit argument.
      */
      /* String to split. */
      String str = “one-two-three”;
      String[] temp;

      /* delimiter */
      String delimiter = “-“;
      /* given string will be split by the argument delimiter provided. */
      temp = str.split(delimiter);
      /* print substrings */
      for(int i =0; i < temp.length ; i++)
        System.out.println(temp[i]);

      /*
      IMPORTANT : Some special characters need to be escaped while providing them as
      delimiters like “.” and “|”.
      */

      System.out.println(“”);
      str = “one.two.three”;
      delimiter = \\.”;
      temp = str.split(delimiter);
      for(int i =0; i < temp.length ; i++)
        System.out.println(temp[i]);

      /*
      Using second argument in the String.split() method, we can control the maximum
      number of substrings generated by splitting a string.
      */
      System.out.println(“”);
      temp = str.split(delimiter,2);
      for(int i =0; i < temp.length ; i++)
        System.out.println(temp[i]);

      }

    }

    /*
    OUTPUT of the above given Java String split Example would be :
    one
    two
    three
    one
    two
    three
    one
    two.three
    */

String Replace Example



  1. /*
    Java String replace example.
    This Java String Replace example describes how replace method of java String class
    can be used to replace character or substring can be replaced by new one.
    */
    public class JavaStringReplaceExample{

      public static void main(String args[]){

        /*
        Java String class defines three methods to replace character or substring from
        the given Java String object.
        1) String replace(int oldChar, int newChar)
        This method replaces a specified character with new character and returns a
        new string object.
        2) String replaceFirst(String regularExpression, String newString)
        Replaces the first substring of this string that matches the given regular
        expression with the given new string.
        3) String replaceAll(String regex, String replacement)
        Replaces the each substring of this string that matches the
        given regular expression with the given new string.
        */

        String str=“Replace Region”;

        /*
        Replaces all occourances of given character with new one and returns new
        String object.
        */
        System.out.println( str.replace( ‘R’,‘A’ ) );

        /*
        Replaces only first occourances of given String with new one and
        returns new String object.
        */
        System.out.println( str.replaceFirst(“Re”, “Ra”) );

        /*
        Replaces all occourances of given String with new one and returns
        new String object.
        */
        System.out.println( str.replaceAll(“Re”, “Ra”) );

      }

    }

    /*
    OUTPUT of the above given Java String Replace Example would be :
    Aeplace Aegion
    Raplace Region
    Raplace Ragion
    */

String Length Example



  1. /*
      Java String Length Example
      This example shows how to get a length of a given String object.
    */

    public class StringLengthExample 
    {

      public static void main(String[] args)  
    {
        //declare the String object
        String str = “Hello World”;

        //length() method of String returns the length of a String.
        int length = str.length();
        System.out.println(“Length of a String is : “ + length);
      }
    }

    /*
    Output of a program would be:
    Length of a String is : 11
    */

String Contains example





  •        This Java String contains examples shows how to use contains method of Java String class.
     */
    public class JavaStringContains {
            public static void main(String args[]){
                    String str1 = “Hello World”;
                    String str2 = “Hello”;

                    /*
                     * To check whether the string contains specified character sequence use,
                     * boolean contains(CharSequence sq)
                     * method of Java String class.
                     *
                     * This method returns true if the string contains given character sequence.
                     * Please note that contains method is added in Java 1.5  
                     */
                   
                    boolean blnFound = str1.contains(str2);
                    System.out.println(“String contains another string? : “ + blnFound);

                    /*
                     * Please also note that the comparison is case sensitive.
                     */
                   
            }
    }

    /*
    Output of Java String contains example would be
    String contains another string? : true
    */

String Concat Example



  1. /*
            Java String Concat Example.
            This Java String concat example shows how to concat String in Java.
     */
    public class JavaStringConcat {
            public static void main(String args[]){
                    /*
                     * String concatenation can be done in several ways in Java.
                     */

                    String str1 = “Hello”;
                    String str2 = ” World”;

                    //1. Using + operator
                    String str3 = str1 + str2;
                    System.out.println(“String concat using + operator : “ + str3);

                    /*
                     * Internally str1 + str 2 statement would be executed as,
                     * new StringBuffer().append(str1).append(str2)
                     *
                     * String concatenation using + operator is not recommended for large number
                     * of concatenation as the performance is not good.
                     */
                   
                    //2. Using String.concat() method
                    String str4 = str1.concat(str2);
                    System.out.println(“String concat using String concat method : “ + str4);

                    //3. Using StringBuffer.append method
                    String str5 = new StringBuffer().append(str1).append(str2).toString();
                    System.out.println(“String concat using StringBuffer append method : “ + str5);
            }

    }

    /*
    Output of Java String concat example would be
    String concat using + operator : Hello World
    String concat using String concat method : Hello World
    String concat using StringBuffer append method : Hello World
    */

String Compare Example



  1. /*
    Java String compare example.
    This Java String compare example describes how Java String is compared with another
    Java String object or Java Object.
    */

    public class JavaStringCompareExample{

      public static void main(String args[]){

      /*
      Java String class defines following methods to compare Java String object.
      1) int compareTo( String anotherString )
      compare two string based upon the unicode value of each character in the String.
      Returns negative int if first string is less than another
      Returns positive int if first string is grater than another
      Returns 0 if both strings are same.
      2) int compareTo( Object obj )
      Behaves exactly like compareTo ( String anotherString) if the argument object
      is of type String, otherwise throws ClassCastException.
      3) int compareToIgnoreCase( String anotherString )
      Compares two strings ignoring the character case of the given String.
      */

      String str = “Hello World”;
      String anotherString = “hello world”;
      Object objStr = str;

      /* compare two strings, case sensitive */
      System.out.println( str.compareTo(anotherString) );
      /* compare two strings, ignores character case  */
      System.out.println( str.compareToIgnoreCase(anotherString) );
      /* compare string with object */
      System.out.println( str.compareTo(objStr) );

      }

    }

    /*
    OUTPUT of the above given Java String compare Example would be :
    -32
    0
    0
    */

String Array Length Example



  1. /*
            Java String Array Length Example
            This Java String Array Length example shows how to find number of elements
            contained in an Array.
     */

    public class JavaStringArrayLengthExample {

            public static void main(String args[]){

                    //create String array
                    String[] strArray = new String[]{“Java”, “String”, “Array”, “Length”};

                    /*
                     * To get length of array, use length property of array.
                     */
                    int length = strArray.length;

                    System.out.println(“String array length is: “ + length);

                    //print elements of an array
                    for(int i=0; i < length; i++){
                            System.out.println(strArray[i]);
                    }
            }
    }

    /*
    Output of above given Java String length example would be
    String array length is: 4
    Java
    String
    Array
    Length
    */

String Array Contains Example



  1. /*
            Java String Array Contains Example
            This Java String Array Contains example shows how to find a String in
            String array in Java.
     */

    import java.util.Arrays;

    public class StringArrayContainsExample {

            public static void main(String args[]){

                    //String array
                    String[] strMonths = new String[]{“January”, “February”, “March”, “April”, “May”};

                    //Strings to find
                    String strFind1 = “March”;
                    String strFind2 = “December”;

                    /*
                     * There are several ways we can check whether a String array
                     * contains a particular string.
                     *
                     * First of them is iterating the array elements and check as given below.
                     */
                   
                    boolean contains = false;

                    //iterate the String array
                    for(int i=0; i < strMonths.length; i++){

                            //check if string array contains the string
                            if(strMonths[i].equals(strFind1)){

                                    //string found
                                    contains = true;
                                    break;

                            }
                    }

                    if(contains){
                            System.out.println(“String array contains String “ + strFind1);
                    }else{
                            System.out.println(“String array does not contain String “ + strFind1);
                    }

                    /*
                     * Second way to check whether String array contains a string is to use
                     * Arrays class as given below.
                     */

                    contains = Arrays.asList(strMonths).contains(strFind1);
                    System.out.println(“Does String array contain “ + strFind1 + “? “ + contains);

                    contains = Arrays.asList(strMonths).contains(strFind2);
                    System.out.println(“Does String array contain “ + strFind2 + “? “ + contains);

            }
    }

    /*
    Output of above given Java String Array Contains example would be
    String array contains String March
    Does String array contain March? true
    Does String array contain December? false
    */

Stack trace to String Example



  1. /*
            Java Stacktrace to String Example
            This Java Stacktrace to String example shows how to get Stacktrace of any exception
            to String.
     */
    import java.io.PrintWriter;
    import java.io.StringWriter;

    public class StackTraceToStringExample {

            public static void main(String args[]){

                    try{

                            //this will throw NumberFormatException
                            Integer.parseInt(“Not a number”);

                    }catch(NumberFormatException e){

                            /*
                             * To convert Stacktrace to String in Java, use
                             * printStackTrace(PrintWrite pw) method of Throwable
                             * class.
                             */
                           
                            //create new StringWriter object
                            StringWriter sWriter = new StringWriter();

                            //create PrintWriter for StringWriter
                            PrintWriter pWriter = new PrintWriter(sWriter);

                            //now print the stacktrace to PrintWriter we just created
                            e.printStackTrace(pWriter);

                            //use toString method to get stacktrace to String from StringWriter object
                            String strStackTrace = sWriter.toString();

                            System.out.println(“Stacktrace converted to String: “ + strStackTrace);
                    }
            }

    }

    /*
    Output of above given Java Stacktrace to String would be
    Stacktrace converted to String: java.lang.NumberFormatException: For input string: “Not a number”
            at java.lang.NumberFormatException.forInputString(Unknown Source)
            at java.lang.Integer.parseInt(Unknown Source)
            at java.lang.Integer.parseInt(Unknown Source)
            at StackTraceToStringExample.main(StackTraceToStringExample.java:16)
    */

Sort String Array Example



  1. /*
            Java Sort String Array Example
            This Java Sort String Array example shows how to sort an array of Strings
            in Java using Arrays.sort method.
     */
    import java.util.Arrays;

    public class SortStringArrayExample 
    {

            public static void main(String args[]) 
    {

                    //String array
                    String[] strNames = new String[]{“John”, “alex”, “Chris”, “williams”, “Mark”, “Bob”};

                    /*
                     * To sort String array in java, use Arrays.sort method.
                     * Sort method is a static method.               *
                     */

                    //sort String array using sort method
                    Arrays.sort(strNames);

                    System.out.println(“String array sorted (case sensitive)”);

                    //print sorted elements
                    for(int i=0; i < strNames.length; i++)
     {
                            System.out.println(strNames[i]);
                    }

                    /*
                     * Please note that, by default Arrays.sort method sorts the Strings
                     * in case sensitive manner.
                     *
                     * To sort an array of Strings irrespective of case, use
                     * Arrays.sort(String[] strArray, String.CASE_INSENSITIVE_ORDER) method instead.
                     */

                    //case insensitive sort
                    Arrays.sort(strNames);

                    System.out.println(“String array sorted (case insensitive)”);
                    //print sorted elements again
                    for(int i=0; i < strNames.length; i++) 
    {
                            System.out.println(strNames[i]);
                    }

            }
    }

    /*
    Output of above given Java Sort String Array example would be
    String array sorted (case sensitive)
    Bob
    Chris
    John
    Mark
    alex
    williams
    String array sorted (case insensitive)
    Bob
    Chris
    John
    Mark
    alex
    williams
    */

Popular Posts

Categories

100 Python Programs for Beginner (53) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (358) Python Quiz (23) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses