Friday, 13 April 2018

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






ArrayList to String Array Example



  1. /*
            Java ArrayList to String Array Example
            This Java ArrayList to String Array example shows how to convert ArrayList to String array
            in Java.
     */

    import java.util.ArrayList;
    import java.util.Arrays;

    public class ArrayListToStringArrayExample {

            public static void main(String args[]){

                    //ArrayList containing string objects
                    ArrayList<String> aListDays = new ArrayList<String>();
                    aListDays.add(“Sunday”);
                    aListDays.add(“Monday”);
                    aListDays.add(“Tuesday”);

                    /*
                     * To convert ArrayList containing String elements to String array, use
                     * Object[] toArray() method of ArrayList class.
                     *
                     * Please note that toArray method returns Object array, not String array.
                     */
                   
                    //First Step: convert ArrayList to an Object array.
                    Object[] objDays = aListDays.toArray();

                    //Second Step: convert Object array to String array
                    String[] strDays = Arrays.copyOf(objDays, objDays.length, String[].class);

                    System.out.println(“ArrayList converted to String array”);

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

    /*
    Output of above given ArrayList to String Array example would be
    ArrayList converted to String array
    Sunday
    Monday
    Tuesday
    */

Convert String to Character Array Example



  1. /*
     Convert String to Character Array Example
     This example shows how to convert a given String object to an array
     of character
     */

    public class StringToCharacterArrayExample  
    {

      public static void main(String args[]) 
    {
        //declare the original String object
        String strOrig = “Hello World”;
        //declare the char array
        char[] stringArray;

        //convert string into array using toCharArray() method of string class
        stringArray = strOrig.toCharArray();

        //display the array
        for(int index=0; index < stringArray.length; index++)
          System.out.print(stringArray[index]);

      }

    }

    /*
    Output of the program would be :
    Hello World
    */

Popular Posts

Categories

100 Python Programs for Beginner (56) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (174) C (77) C# (12) C++ (82) Course (67) Coursera (228) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (21) 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 (60) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (935) Python Coding Challenge (368) Python Quiz (27) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

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