Friday 13 April 2018

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
    */

Search String using index Of Example



  1. /*
      Java Search String using indexOf Example
      This example shows how we can search a word within a String object using
      indexOf method.
    */

    public class SearchStringExample  
    {

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

        /*
          To search a particular word in a given string use indexOf method.
          indexOf method. It returns a position index of a word within the string
          if found. Otherwise it returns -1.
        */

        int intIndex = strOrig.indexOf(“Hello”);

        if(intIndex == 1){
          System.out.println(“Hello not found”);
        }else{
          System.out.println(“Found Hello at index “ + intIndex);
        }

        /*
          we can also search a word after particular position using
          indexOf(String word, int position) method.  
        */

        int positionIndex = strOrig.indexOf(“Hello”,11);
        System.out.println(“Index of Hello after 11 is “ + positionIndex);

        /*
          Use lastIndexOf method to search a last occurrence of a word within string.
        */
        int lastIndex = strOrig.lastIndexOf(“Hello”);
        System.out.println(“Last occurrence of Hello is at index “ + lastIndex);

      }
    }

    /*
    Output of the program would be :
    Found Hello at index 0
    Index of Hello after 11 is 12
    Last occurrence of Hello is at index 12
    */

Reverse String Array Example



  1. /*
            Java Reverse String Array Example
            This Java Reverse String Array example shows how to find sort an array of
            String in Java using Arrays and Collections classes.
     */

    import java.util.Collections;
    import java.util.List;
    import java.util.Arrays;

    public class ReverseStringArrayExample {

            public static void main(String args[]){

                    //String array
                    String[] strDays = new String[]{“Sunday”, “Monday”, “Tuesday”, “Wednesday”};

                    /*
                     * There are basically two methods, one is to use temporary array and
                     * manually loop through the elements of an Array and swap them or to use
                     * Arrays and Collections classes.
                     *
                     * This example uses the second approach i.e. without temp variable.
                     *
                     */
                   
                    //first create a list from String array
                    List<String> list = Arrays.asList(strDays);

                    //next, reverse the list using Collections.reverse method
                    Collections.reverse(list);

                    //next, convert the list back to String array
                    strDays = (String[]) list.toArray();

                    System.out.println(“String array reversed”);

                    //print the reversed String array
                    for(int i=0; i < strDays.length; i++){
                            System.out.println(strDays[i]);
                    }

            }

    }

    /*
    Output of above given Java Reverse String Array example would be
    String array reversed
    Wednesday
    Tuesday
    Monday
    Sunday
    */

Input Stream to String Example



  • /*
            Java InputStream to String Example
        This Java InputStream to String example shows how to convert InputStream to String in Java.
     */
    public class ConvertInputStreamToStringExample  
    {

            public static void main(String args[]) throws IOException{

                    //get InputStream of a file
                    InputStream is = new FileInputStream(“c:/data.txt”);
                    String strContent;

                    /*
                     * There are several way to convert InputStream to String. First is using
                     * BufferedReader as given below.
                     */

                    //Create BufferedReader object
                    BufferedReader bReader = new BufferedReader(new InputStreamReader(is));
                    StringBuffer sbfFileContents = new StringBuffer();
                    String line = null;

                    //read file line by line
                    while( (line = bReader.readLine()) != null) 
    {
                            sbfFileContents.append(line);
                    }

                    //finally convert StringBuffer object to String!
                    strContent = sbfFileContents.toString();

                    /*
                     * Second and one liner approach is to use Scanner class. This is only supported
                     * in Java 1.5 and higher version.
                     */

                    strContent = new Scanner(is).useDelimiter(\\A”).next();
            }
    }

Date to String Example



  1. /*
            Java Date to String Example
            This Java Date to String example shows how to convert java.util.Date to
            String in Java.
     */

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class ConvertDateToStringExample
     {

            public static void main(String args[]) 
    {

                    //create new java.util.Date object
                    Date date = new Date();

                    /*
                     * To convert java.util.Date to String, use SimpleDateFormat class.
                     */

                    /*
                     * crate new SimpleDateFormat instance with desired date format.
                     * We are going to use yyyy-mm-dd hh:mm:ss here.
                     */
                    DateFormat dateFormat = new SimpleDateFormat(“yyyy-mm-dd hh:mm:ss”);

                    //to convert Date to String, use format method of SimpleDateFormat class.
                    String strDate = dateFormat.format(date);

                    System.out.println(“Date converted to String: “ + strDate);

            }
    }

    /*
    Output of above given java.util.Date to String example would be
    Date converted to String: 2011-17-10 11:17:50
    */

Char Array To String Example






Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (113) C (77) C# (12) C++ (82) Course (60) Coursera (176) coursewra (1) Cybersecurity (22) data management (11) Data Science (85) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (18) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (43) Meta (18) MICHIGAN (4) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (726) Python Coding Challenge (169) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

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