Sunday, 31 December 2017

Methods on String Object in Java Part-2


public class StringMethodsTest2 {

    public static void main(String[] args) {
        String test="java programme with string";
        //getBytes---returns byte array of string. it returns sequence of bytes
        byte[] sArray = test.getBytes();
        for (int i = 0; i < sArray.length; i++) {
            System.out.println(sArray[i]);
        }
        System.out.println(new String(sArray));
       
        //getChars() --does not return any value but we can copy content of string to an char array
        // it required 4 iput parameters sArray
        //srcBegin index of the first character in the string to copy.--1
        //srcEnd index after the last character in the string to copy.--2
        //dst the destination array.--3
        //dstBegin the start offset in the destination array.--4
        char[] characters = new char[4];
        test.getChars(0, 4, characters, 0);//char array get chars from 0 to 3 from string testi.e it has java
        for (int i = 0; i < characters.length; i++) {
            System.out.println("characteer array is" + characters[i]);
        }
       
    //indexof(char c)-----returns  index value of given char in string
    //and returns-1 if char is not found in string
        //it will pring first occurence of index if given char is repeated in string
        System.out.println(test.indexOf("a"));//1
       
        //indexof(char c, int fromIndex)-----returns  index value of given char in string from given index
        //and returns-1 if char is not found in string
            //it will pring first occurence of index if given char is repeated in string
            System.out.println(test.indexOf("a",2));//3
           
            //indexof(String subString)-----returns  index value of given subString
            //and returns-1 if char is not found in string
                System.out.println(test.indexOf("va"));//2
               
                //indexof(String subString, int fromIndex)-----returns  index value of given subString from given index
                //and returns-1 if char is not found in string
                    System.out.println(test.indexOf("va",4));//-1
    }

}

Wednesday, 13 December 2017

Methods on String Object in Java

We have below list of methods available on String object in java.


public class StringMethodsTest {

    public static void main(String[] args) {
        String test="java";
        //charAt()
        System.out.println(test.charAt(0));//index will start with zero
        //concat()
        test.concat("program");
        System.out.println(test);//will print java becasue we just concatinated but did not assign to string
        String testcon = test.concat("program");
        System.out.println(testcon);
        //contains
        System.out.println(test.contains("j"));//return true if string contains char j any where//trur
        System.out.println(test.contains("jv"));//return true if string contains char j any where//false
        //ends with
        System.out.println(test.endsWith("a"));//return true if specified string is ends with mentioed suffix//true
        System.out.println(test.endsWith("aj"));//return true if specified string is ends with mentioed suffix//false
        //equals
        String test1 = "java";
        System.out.println(test.equals(test1));//will check only text here//true
        //compareTo
        //ifs1==s2, then 0 or if s1>s2 then +ve or if s1 <s2, then -ve values will print
        String test3 = "sql";
        String test4 = "c++";
        String test5 = "jquery";
        System.out.println(test.compareTo(test3));//-ve value-9 --diffrence between first characters
        System.out.println(test.compareTo(test4));//+ve value 2--diffrence between first characters
        System.out.println(test.compareTo(test1));//here 0
        System.out.println(test.compareTo(test5));//here -ve -16 becasue second character is different
        //equalIgnorecase
        String test6 = "JAVA";
        System.out.println(test.equalsIgnoreCase(test6));//ignore case sensitive//true
        System.out.println(test.equals(test6));//not case sensitive//false
    }

}


Will continue other methods in next post.

String comparision in Java

 We have methods like equals() to compare the string literals but it is case sensitive and it will check whether two string have same characters in order. And also we have equalsIgnorecase() method to compare the two string and it omits case sensitivity. And also we have compareTo() method amd it is generally used for sorting of collections.

We will see some important compare methods on strings in java below.


public class StringCompareTest {

    public static void main(String[] args) {

        //by Equals method
        String string1 = "equal";
        String string2 = "equal";
        String string3 = new String("equal");
        String s4 = string3.intern();
        StringBuffer stringBuffer = new StringBuffer(string1);
        StringBuilder stringBuilder = new StringBuilder(string1);
        System.out.println(string1.equals(string2));//true
        System.out.println(string1.equals(string3));//true
        System.out.println(string2.equals(string3));//true
        System.out.println(string2.equals(stringBuffer));//false
        System.out.println(string3.equals(stringBuffer));//false
        System.out.println(string2.equals(stringBuilder));//false
        System.out.println(string3.equals(stringBuilder));//false
        System.out.println(stringBuffer.equals(stringBuilder));//false
      
        System.out.println("===================================");
        //by == method
        System.out.println(string1==string2);//true
        System.out.println(string1==string3);//false
        System.out.println(string2 == string3);//false
        System.out.println(s4 == string1);//true
        System.out.println(s4 == string2);//true
        System.out.println(s4 == string3);//false
        System.out.println("===================================");
        System.out.println("compare to");
        //by compareTo method
        String string11 = "equal";
        String string21 = "notequal";
        String string31 = new String("moreequal");
        String string41 = new String("abcmoreequal");
        String string51 = "notequal";
        //s1 ==s2 then 0, s1>s2 then +ve, s1<s2 then -ve
        System.out.println(string11.compareTo(string21));//-9 because n is 9th letter after e
        System.out.println(string11.compareTo(string31));//-8 because n is 8th letter after e
        System.out.println(string21.compareTo(string31));//1 because n is 1st letter after m
        System.out.println(string21.compareTo(string41));//13 because m is 12th letter after a
        System.out.println(string21.compareTo(string51));//0 both are same
    }

}


Output:

true
true
true
false
false
false
false
false
===================================
true
false
false
true
true
false
===================================
compare to
-9
-8
1
13
0

String Reverse in Java

We can reverse string in many ways in java as shown below.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class StringRevesreTest {

    public static void main(String[] args) {
        //option1
        String test= new String("java program");
        char[] cs = test.toCharArray();
        char[] output = new char[cs.length];
        for (int i=0; i<cs.length; i++) {
            output[i]=cs[cs.length-i-1];
            //System.out.println(cs[cs.length-i-1]);
           
        }
        System.out.println(output);
        System.out.println(new String(output));
        //option 1 end here
       
        //option2
        StringBuffer stringBuffer = new StringBuffer(test);
        stringBuffer.reverse();
        System.err.println(stringBuffer);
        //option 2 end here
       
        //option 3
        ArrayList<Character> list = new ArrayList<Character>();
        char[] cs1 = test.toCharArray();
        for (char c : cs1) {
            list.add(c);
        }
        Collections.reverse(list);
        System.out.println(list);
        //using lterator
        /*Iterator<Character> iterator = list.iterator();
        for (Iterator iterator2 = list.iterator(); iterator2.hasNext();) {
            Character character = (Character) iterator2.next();
            System.out.println(character);
        }*/
        //option3 end here
       
        //option 4
        byte[] bs = test.getBytes();
        byte[] outputByte = new byte[bs.length];
        for (int i = 0; i < bs.length; i++) {
            outputByte[i]=bs[bs.length-i-1];
        }
        System.err.println(new String(outputByte));
       
        //optin4 end here
    }
   

}

Understanding of Constructors in Java

Before to this please read the constructors in java post. To Continue to this post  we have below thing need to know about the constructors in inheritance.

If we did not specify any constructors explicitly, no issues. Java will take care with Implicit constructors. But if we define explicit constructors we should know below points.

1. If we specify only one no arg default constructor in parent class explicitly, we no need to specify any explicit of constructors in sub class and if we create object of subclass, it will automatically calls the no arg explicit default constructor of parent class.

public class ConstructorTest{
    String mute1 = "java";
    //mute1 = new String("program");
   
    public ConstructorTest() {
        System.out.println("default parent const");
    }
    /*public ConstructorTest(String muteq) {
        System.out.println("default param parent const");
    }*/
    public static void main(String args[]){
        //ConstructorTest constructorTest= new ConstructorTest("rest");
        //System.out.println(constructorTest.mute1);
    }

}

public class DefaultConstructorTest extends constructorTest{
   
    /*public DefaultConstructorTest() {
        System.out.println("def const");
    }*/

    /*public DefaultConstructorTest(String muteq) {
        super(muteq);
        System.out.println("def param sub const");
    }*/

    public static void main(String[] args) {
        //DefaultConstructorTest constructorTest = new DefaultConstructorTest("test");
        DefaultConstructorTest constructorTest = new DefaultConstructorTest();
    }

}

output : default parent const

2. If we define one more parameterized constructor in parent class, then we no need to define any thing and it will work as above scenario.

public class ConstructorTest{
    String mute1 = "java";
    //mute1 = new String("program");
   
    public constructorTest() {
        System.out.println("default parent const");
    }
    public constructorTest(String muteq) {
        System.out.println("default param parent const");
    }
    public static void main(String args[]){
        //ConstructorTest constructorTest = new ConstructorTest("rest");
        //System.out.println(constructorTest.mute1);
    }

}


public class DefaultConstructorTest extends ConstructorTest{
   
    /*public DefaultConstructorTest() {
        System.out.println("def const");
    }*/

    /*public DefaultConstructorTest(String muteq) {
        super(muteq);
        System.out.println("def param sub const");
    }*/

    public static void main(String[] args) {
        //DefaultConstructorTest constructorTest = new DefaultConstructorTest("test");
        DefaultConstructorTest constructorTest = new DefaultConstructorTest();
    }

}
output : default parent const

3. if we specify only paramertized constructor in parent class, then we should define parameterized constructor in subclass and should call super class constructor as shwon below.


public class ConstructorTest{
    String mute1 = "java";
    //mute1 = new String("program");
   
    /*public ConstructorTest() {
        System.out.println("default parent const");
    }*/
    public ConstructorTest(String muteq) {
        System.out.println("default param parent const");
    }
    public static void main(String args[]){
        //ConstructorTest constructorTest= new ConstructorTest("rest");
        //System.out.println(constructorTest.mute1);
    }

}


/**
 * Implicit super constructor ConstructorTest() is undefined for default
 * constructor. Must define an explicit constructor
 *
 * @author
 *
 */
public class DefaultConstructorTest extends ConstructorTest{
   
    // will get error :Implicit super constructor ConstructorTest() is
    // undefined. Must explicitly invoke another constructor. so please comment it.
    /*public DefaultConstructorTest() {
        System.out.println("def const");
    }*/

    /**
     * We should invoke super class constructor explictly other wise it will
     * error Implicit super constructor ConstructorTest() is undefined. Must
     * explicitly invoke another constructor
     *
     * @param muteq
     */
    public DefaultConstructorTest(String muteq) {
        super(muteq);
        System.out.println("def param sub const");
    }

    public static void main(String[] args) {
        DefaultConstructorTest constructorTest = new DefaultConstructorTest("test");
        //DefaultConstructorTest constructorTest = new DefaultConstructorTest();
    }

}

4. If we have default constructor and paramterized constructor exlplicitly in parent class, then no need to define any explict constructors in sub class.


public class ConstructorTest {
    String mute1 = new String("java");
    //mute1 = new String("program");
    int j;
   
    public ConstructorTest() {
        System.out.println("default parent const");
    }
    public void modifySTring(){
        mute1 = "program";
    }
    public ConstructorTest(String muteq) {
        System.out.println("default param parent const");
    }
    public static void main(String args[]){
        ConstructorTest stringMutableTest = new ConstructorTest("rest");
        stringMutableTest.modifySTring();
        System.out.println(stringMutableTest.mute1);
    }

}
 


/**
 * Implicit super constructor StringMutableTest() is undefined for default
 * constructor. Must define an explicit constructor
 *
 * @author balakrishnab4
 *
 */
public class DefaultConstructorTest extends ConstructorTest{
   
    // will get error :Implicit super constructor StringMutableTest() is
    // undefined. Must explicitly invoke another constructor. so please comment it.
    /*public DefaultConstructorTest() {
        System.out.println("def const");
    }*/

    /**
     * We should invoke super class constructor explictly other wise it will
     * error Implicit super constructor StringMutableTest() is undefined. Must
     * explicitly invoke another constructor
     *
     * @param muteq
     */
    /*public DefaultConstructorTest(String muteq) {
    //    super(muteq);
        System.out.println("def param sub const");
    }*/

    public static void main(String[] args) {
        //DefaultConstructorTest constructorTest = new DefaultConstructorTest("test");
        DefaultConstructorTest constructorTest = new DefaultConstructorTest();
    }

}
 

Output: default parent const 

Note: We need to take care of child class, when we define only parameterized constructor in parent class.

Stack Over Flow exception

When we try to execute java program which will in infinite loop, we will get Stack Over flow exception as shown below.

package com.sample.java.testing;

public class ConstructorExample {

    /**
     * It gets stack overflow exception why because it continuously calls the
     * constructor.
     */
    private ConstructorExample() {
        ConstructorExample constructorExample = new ConstructorExample();
        System.out.println(constructorExample);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        new ConstructorExample();

    }

}

Output:
Exception in thread "main" java.lang.StackOverflowError
    at com.sample.java.testing.ConstructorExample.<init>(ConstructorExample.java:10)
    at com.sample.java.testing.ConstructorExample.<init>(ConstructorExample.java:10)