·  JAVA – Syntax – Variables – String

 

- Info:

  - This tutorial shows how to create, convert to Primitive Types and use String Object.

  - Second example explains how parsing of regular expressions works.

 

- Example:

  - Create JAVA Console Application Test.java

 

Test.java

public class Test {

 

  public static void main(String[] args) { 

 

    //CREATE.--------------------------------------------------------------------------------------------

    String  text     = null;                         //Calling any function on text throws Exception

            text     = "";                           //Empty string.text.length()=0,text.equals("")==true

            text     = "text";                       //Creates string with constant text "text".

            text     = "Name\t\"Jo\"\n";             //Using escape character '\': \" \t \n \\

            text     = "Start"+"End";                //Connecting Strings.

 

            text     = new String();                 //Empty string.

            text     = new String("text");           //Creates string with constant text "text".

          text     = new String        (new byte[] {'C','a','r','s'}); //Creates String from byte array.

          text     = new String        (new char[] {'C','a','r','s'}); //Creates String from char array.

 

          text     = String.copyTextOf(new char[] {'C','a','r','s'}); //Creates String from char array.

            text     = String.copyTextOf(new char[] {'C','a','r','s'}, 1, 2); //From index=1 take 2.   

 

            text     = String.textOf (       false); //boolean          

            text     = String.textOf (        'A' ); //char               

            text     = String.textOf (        65  ); //int

            text     = String.textOf ((long65  ); //long       

            text     = String.textOf ((float) 65.0); //float       

            text     = String.valueOf(        65.0); //double   

 

    //DISPLAY.-------------------------------------------------------------------------------------------

    System.out.println(value);        

 

    //CONCATENATE.---------------------------------------------------------------------------------------

    String  text     = "START"+"END";                //Connects two strings into new one.

            text    += text;                         //Connects string with itself.

 

    //CONVERT TO.----------------------------------------------------------------------------------------

    boolean convert1 = Boolean.parseBoolean("true");        //All else is false including null.

   

    char    convert2 = "A"    .charAt      (0);

   

    byte    convert3 = new Byte   ("10").byteValue();       //Decimal     since default base is 10.

            convert3 = Byte   .parseByte   ("10");          //Decimal     since default base is 10.

            convert3 = Byte   .parseByte   ("1000001", 2);  //Binary      since base is set to   2.

            convert3 = Byte   .parseByte   ("101"    , 8);  //Octal       since base is set to   8.

            convert3 = Byte   .parseByte   ("41"     ,16);  //Hexadecimal since base is set to  16.

           

    short   convert4 = new Short  ("10").shortValue();      //Decimal     since default base is 10.

            convert4 = Short  .parseShort  ("10");          //Decimal     since default base is 10.

            convert4 = Short  .parseShort  ("1000001", 2);  //Binary      since base is set to   2.

            convert4 = Short  .parseShort  ("101"    , 8);  //Octal       since base is set to   8.

            convert4 = Short  .parseShort  ("41"     ,16);  //Hexadecimal since base is set to  16.

           

    int     convert5 = new Integer("10").intValue();        //Decimal     since default base is 10.

            convert5 = Integer.parseInt    ("10");          //Decimal     since default base is 10.

            convert5 = Integer.parseInt    ("1000001", 2);  //Binary      since base is set to   2.

            convert5 = Integer.parseInt    ("101"    , 8);  //Octal       since base is set to   8.

            convert5 = Integer.parseInt    ("41"     ,16);  //Hexadecimal since base is set to  16.

           

    long    convert6 = new Long   ("10").longValue();       //Decimal     since default base is 10.

            convert6 = Long   .parseLong   ("10");          //Decimal     since default base is 10.

            convert6 = Long   .parseLong   ("1000001", 2);  //Binary      since base is set to   2.

            convert6 = Long   .parseLong   ("101"    , 8);  //Octal       since base is set to   8.

            convert6 = Long   .parseLong   ("41"     ,16);  //Hexadecimal since base is set to  16.

           

    float   convert7 = Float  .parseFloat  ("2.5");

   

    double  convert8 = Double .parseDouble ("2.5");

 

  //ANALYZE.---------------------------------------------------------------------------------------------

  String   text    = "012345";

  int      index   = text.indexOf            ('3'     ); //First occurence of  '3'                 or -1.

           index   = text.indexOf            ('3' , 2 ); //First occurence of  '3' starting from 2 or -1.

           index   = text.indexOf            ("23"    ); //First occurence of "23"                 or -1.

           index   = text.indexOf            ("23", 2 ); //First occurence of "23" starting from 2 or -1.

           index   = text.lastIndexOf        ('3' , 2 ); //Last  occurence of  '3' starting from 2 or -1.

           index   = text.lastIndexOf        ('3' , 2 ); //Last  occurence of  '3' starting from 2 or -1.

           index   = text.lastIndexOf        ("23"    ); //Last  occurence of "23"                 or -1.

           index   = text.lastIndexOf        ("23", 2 ); //Last  occurence of "23" starting from 2 or -1.

           

  boolean  test    = text.startsWith         ("0123"  ); //true if text starts with "0123". Else false.

           test    = text.startsWith         ("234", 2); //true if there is string "234" at index 2.

           test    = text.endsWith           ("345"   ); //true if text ends with "345". Else false.

           test    = text.equals             ("012345"); //true if strings are equal.

           test    = text.equalsIgnoreCase   ("012345"); //true if strings are equal ignoring case.

           

  int      cmp     = text.compareTo          ("012345"); //0 if equal, <0 if text<"Second", else >0

           cmp     = text.compareToIgnoreCase("012345"); //Same as above ignoring case.

                   

  int      length  = text.length();                      //Returns number of characters in string.

 

  //GET SUBSTRINGS.--------------------------------------------------------------------------------------

           text    = "012345";

  String   sub     = text.substring (2);     //Take substring from index 2 till the end. Result is "2345"

           sub     = text.substring (2,5);   //Take substring from index 2 till 5-1=4.   Result is "234".

 

  String   changed = text.trim        ();    //Erases leading and trailing whitespaces: \t \n 

 

           text    = "zero<->one<->two<->three";

  String[] tokens  = text.split("<->"  );    //Split string around "<->" regex. Gives tokens[0]="one";

           tokens  = text.split("<->",3);    //Create maximum 3 tokens. Gives tokens[2]="two<->three";

           tokens  = text.split("[135]");    //Split string around 1,3 and 5.

           tokens  = text.split("/"    );    //Split string around '/'.

           tokens  = text.split("\\."  );    //Split string around '.'.

           tokens  = text.split("\\\\" );    //Split string around '\'.

           tokens  = ""  .split(";"    );    //One token  is  returned resulting in tokens.length=1.

           tokens  = ";" .split(";"    );    //No  tokens are returned resulting in tokens.length=0.

   

  //MODIFY.----------------------------------------------------------------------------------------------

           text    = "012345  \n";

  String   changed = text.toUpperCase ();           //Converts all characters to upper case.

           changed = text.toLowerCase ();           //Converts all characters to lower case.

           changed = text.replace     ('3', 'A' );  //Replace ALL   occurrences of char   '3'  with 'A'.

           changed = text.replaceFirst("23","AB");  //Replace FIRST occurrences of regex  "23" with "AB".

           changed = text.replaceAll  ("23","AB");  //Replace ALL   occurrences of regex  "23" with "AB".

           changed = text.replaceAll  ("[\n\r]","");//Remove all \n and \r characters.

 

  }

 

}

 

- Regular Expresions:

  - Create JAVA Console Application Test.java

 

    Test.java

    public class Test {

   

      public static void main(String[] args) {

        

        String   text;

        String[] tokens;

   

        //Character "/" is not special character in neither Java or Regex Compiler.

        text   = "First/second";      //After Java  Compiler text      is left unchanged.

        tokens = text.split("/");     //Delimiter is unchanged after both Java and Regex Compilers.

        System.out.println(tokens[0]);

        

        //Character "." is special character only in Regex Compiler.

        text   = "First.second";      //After Java  Compiler text      is left unchanged.

        tokens = text.split("\\.");   //After Java  Compiler delimiter is "\."

        System.out.println(tokens[0]);//After Regex Compiler delimiter is "."

   

        //Character "\" is special character in both Java ans Regex Compiler.

        text   = "First\\second";     //After Java  Compiler text      is "First\second"

        tokens = text.split("\\\\");  //After Java  Compiler delimiter is "\\"

        System.out.println(tokens[0]);//After Regex Compiler delimiter is "\"

   

        //Characters "-","/" are not special characters in neither Java or Regex Compiler.

        text   = "First-second/third";//After Java  Compiler text      is left unchanged.

        tokens = text.split("[-/]") ; //Delimiter is unchanged after both Java and Regex Compilers.

        System.out.println(tokens[0]);

        

      }

   

    }