Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Showing posts with label Java String. Show all posts
Showing posts with label Java String. Show all posts

Tuesday

How to find the length of StringBuffer sample Program

How to find the length of StringBuffer sample program



public class Sample {

    public static void main(String args[])
    {
   StringBuffer sb = new StringBuffer("This is my first sample program");
   System.out.println("The length of the string buffer is: "+sb.length());
    }
}




Sunday

How to compare Arrays in Java

How to compare Arrays in Java

For Comparing Arrays we use equals() and deepEquals() methods.

Example:

public final class Test {
static String[] strArray = new String[10];
static String[] strArray1 = new String[10];
    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="abc";
    strArray[2]="abc";
    strArray[3]="abc";
    strArray[4]="abc";
   
    strArray1[0]="abc";
    strArray1[1]="abc";
    strArray1[2]="abc";
    strArray1[3]="abc";
    strArray1[4]="abc";
   
    if(Arrays.equals(strArray, strArray1))
    {
    System.out.println("Both are equal");
    }else
    {
    System.out.println("Both are not equal");
    }
    }
 
}

Find the longest String in an Array java with Example

Find the longest String in an Array java with Example

Example:

public final class Test {

static String[] strArray = new String[10];

public static String getLongString(String[] array)
 {
   int maxLength = 0;
   String longestString = null;
   for (String s : array)
   {
     if (s.length() > maxLength)
     {
       maxLength = s.length();
       longestString = s;
     }
   }
   return longestString;
 }

    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="ramesh";
    strArray[2]="java api";
    strArray[3]="strengh";
    strArray[4]="d";
    System.out.println("Longest String: "+getLongString(strArray));
    }
 
}

How to convert Java Object Array to List in Java

How to convert Java Object Array to List in Java

We studied how to create a Array, how to sort it etc. Now we are going to convert the Array to List .

Example:

public final class Test {

static String[] strArray = new String[10];

    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="def";
    strArray[2]="ghi";
    strArray[3]="jkl";
    strArray[4]="mno";
   
    List list = Arrays.asList(strArray);
    Iterator li = list.iterator();
    while(li.hasNext())
    {
    System.out.println(li.next());
    }
    }
 
}

Java String Array Contains with Examples

Java String Array Contains with Examples

We already studied Java String Array and Sorting a String Array. Now we check whether a String Array contains.

Example:

public final class Test {

static String[] strArray = new String[10];

    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="def";
    strArray[2]="ghi";
    strArray[3]="jkl";
    strArray[4]="mno";
   
    for(int i=0;i<strArray.length;i++)
    {
    if(strArray[2].equals("ghi"))
    System.out.println("true");
    }
    }
 
}

How to sort a Java String Array

How to sort a Java String Array

We already studied what is String array in Java. Now we will sort the previously created String Array.

Example:

public final class Test {

static String[] strArray = new String[10];

    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="def";
    strArray[2]="ghi";
    strArray[3]="jkl";
    strArray[4]="mno";
   
    Arrays.sort(strArray);
   
    for(int i=0;i<strArray.length;i++)
    {
    System.out.println(strArray[i]);
    }
    }
 
}

String Array in Java with Examples

String Array in Java with Examples

Array is a container to store some values of a single type.The length of the array is fixed at the time of creation and it can't be changed. The String array is used to store String values. In String array you can't store other types.

public final class Test {

static String[] strArray = new String[10];

    public static void main(String args[])
    {
    strArray[0]="abc";
    strArray[1]="def";
    strArray[2]="ghi";
    strArray[3]="jkl";
    strArray[4]="mno";
   
    for(int i=0;i<strArray.length;i++)
    {
    System.out.println(strArray[i]);
    }
    }
    }

Tuesday

How String Comparison works in java or Facts about String in java

How String Comparison works in java or Facts about String in java

String is the one of the mostly used feature in java. All java programmers came across this that what i am going to explain here. But they didn't care about it means they are not interested to know how java works...:).

Let me consider a simple program.

public static void main(String args[])
{
String s1 = "hai how r u";
        String s2 = "hai how r u";
        String s3 = new String(s1);
        
        if(s1==s2){
            System.out.println("s1 == s2 : TRUE");
        } else {
            System.out.println("s1 == s2 : FALSE");
        }
        if(s1.equals(s2)){
            System.out.println("s1.equals(s2) : TRUE");
        } else {
            System.out.println("s1.equals(s2) : FALSE");
        }
        
        if(s1==s3){
            System.out.println("s1 == s3 : TRUE");
        } else {
            System.out.println("s1 == s3 : FALSE");
        }
        if(s1.equals(s3)){
            System.out.println("s1.equals(s3) : TRUE");
        } else {
            System.out.println("s1.equals(s3) : FALSE");
        }


}

Frankly just answer this program without seeing the output. Did you know how the below output comes, what are the things gone innerside.

Output:-

s1 == s2 : TRUE
s1.equals(s2) : TRUE
s1 == s3 : FALSE

s1.equals(s3) : TRUE

In java If you create a String it just looks inside the String pool to verify whether any other literals are there with the same value, then its reference is given to the new one.Otherwise a new reference is given to the new literal.

Thus the "==" operator compares the reference(memory location) and values and return true.The equals also compares the value and returns true.

But the s3 is created by new keyword hence it occupies a new location in java heap. thus the "==" operator fails but the equals operator succeeds.

Why we should avoid "==" operator for comparing Integer objects in java

Why we should avoid "==" operator for comparing objects in java

The autoboxing is the technology introduced since java 5. Autoboxing in the sense converting  primitive types to its wrapper classes.
eg:- int to Integer. for more see  autoboxing and unboxing in java.

During comparison the Integer is converted into its primitive types. Even if the two have the same value it should return false because "==" also compares the reference, and it may be two objects in the java heap.

public static void main(String args[])
{
Integer i1 =260;
Integer i2 = 260;
if (i1 == i2) { System.out.println("i1 and i2 is equal"); }
else { System.out.println("i1 and i2 is not equal "); }


}

here it will print false because i1 and i2 are two objects in the heap and reference are different, so better to avoid "==" operator for comparing Integer Objects.

Overriding equals() and hashCode() methods in java

Overriding equals() and hashCode() methods in java

equals() and hashCode() are two methods of java.lang.Object. The main use of equals() method is to compare the two objects. If the value and the two reference variables are pointing to the same memory location it returns true.

Normally the equals of method is used in HashMap. Also used in HashSet to avoid duplicates.

1) Reflexive : Object must be equal to itself.
2) Symmetric : if z.equals(x) is true then x.equals(z) must be true.
3) Transitive : if z.equals(x) is true and z.equals(y) is true then y.equals(x) must be true.
4) Consistent : multiple invocation of equals() method must result same value until any of properties are modified. So if two objects are equals in Java they will remain equals until any of there property is modified.
5) Null comparison : comparing any object to null must be false and should not result in NullPointerException.

hashCode() and equals();-

  1. If two objects are equal then their hashcode are equal.
  2. If two objects are not equal then their hashcode is also different.
Code Example:-

/**
 * 
 */
package in.jobberindia;

/**
 * @author user
 *
 */
public class EqualsOverRide {
private int id; 
private String fName;
private String lName;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the fName
*/
public String getfName() {
return fName;
}
/**
* @param fName the fName to set
*/
public void setfName(String fName) {
this.fName = fName;
}
/**
* @return the lName
*/
public String getlName() {
return lName;
}
/**
* @param lName the lName to set
*/
public void setlName(String lName) {
this.lName = lName;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((fName == null) ? 0 : fName.hashCode());
result = prime * result + id;
result = prime * result + ((lName == null) ? 0 : lName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof EqualsOverRide)) {
return false;
}
EqualsOverRide other = (EqualsOverRide) obj;
if (fName == null) {
if (other.fName != null) {
return false;
}
} else if (!fName.equals(other.fName)) {
return false;
}
if (id != other.id) {
return false;
}
if (lName == null) {
if (other.lName != null) {
return false;
}
} else if (!lName.equals(other.lName)) {
return false;
}
return true;
}

}


Monday

How to find the first non repeated characters from a string in java program

How to find the non repeated characters from a string in java program

This is also one of the normally asked interview question for fresher and experienced java developer. Jobberindia provides the easy solution to solve this.

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class Programming {
    
   
    public static char getFNRChar(String str) {
        Map<Character,Integer> c = new LinkedHashMap<>(str.length());
        
        for (char c : str.toCharArray()) {
            c.put(c, c.containsKey(c) ? c.get(c) + 1 : 1);
        }
        
        for (Entry<Character,Integer> ent : c.entSet()) {
            if (ent.getValue() == 1) {
                return ent.getKey();
            }
        }
        throw new RuntimeException("no matches found");
    }


    public static char getRepeatedChar(String word) {
        Set<Character> rep = new HashSet<>();
        List<Character> nonRep = new ArrayList<>();
        for (int i = 0; i < word.length(); i++) {
            char letter = word.charAt(i);
            if (rep.contains(letter)) {
                continue;
            }
            if (nonRep.contains(letter)) {
                nonRep.remove((Character) letter);
                rep.add(letter);
            } else {
                nonRep.add(letter);
            }
        }
        return nonRep.get(0);
    }



    public static char getNonRepeatedCharacter(String word) {
        HashMap<Character,Integer> sc = new HashMap<>();
        // build table [char -> count]
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (sc.containsKey(c)) {
                sc.put(c, sc.get(c) + 1);
            } else {
                sc.put(c, 1);
            }
        }
        
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (sc.get(c) == 1) {
                return c;
            }
        }
        throw new RuntimeException("exceptionnnnnnnn");
    }

}

How to find out the duplicate characters in String java program

How to find out the duplicate characters in String java program

 This is one of the normal java interview questions asked for fresher and experienced java developers. To solve this jobberindia has come along with a solution. Below is the program to find the duplicate characters in a string.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class checkRepeatingCharacters{

    public static void main(String args[]) {
        getDupCharacters("blogger");
    }

    
    public static void getDupCharacters(String w) {
        char[] char = w.toCharArray();

       
        Map<Character, Integer> m = new HashMap<Character, Integer>();
        for (Character c : char) {
            if (m.containsKey(ch)) {
                m.put(c, m.get(c) + 1);
            } else {
                m.put(c, 1);
            }
        }

        
        Set<Map.Entry<Character, Integer>> eS = charMap.entrySet();
        System.out.println("duplicate characters is"+word);
        for (Map.Entry<Character, Integer> e : eS) {
            if (e.getValue() > 1) {
                System.out.println("key:"+e.getKey()+"value:"e.getValue());
            }
        }
    }

}

duplicate characters is
g : 2

Thursday

How to convert String to Date in Java

How to convert String to Date in Java

Java provides java.text.DateFormat and java.text.SimpleDateFormat for converting String to date and vice versa.

Steps to convert String to Date:


  1. Declare a SimpleDateFormat object. with argument as the format of date eg:- dd/mm/yyyy
  2. Use the parse() method to  covert the string object into its date type.
eg:- 

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

public class dateParsing{
 
    
public static void main(String args[]) throws ParseException{
     
        DateFormat f = 
null;
        Date cD = 
null;

        String d = "14-09-2011";
        f = 
new SimpleDateFormat("dd-MM-yyyy");
        cD = 
(Date) f.parse(d);
        System.
out.println("Coverted String to Date" + cD);
}
}

The main things to remember are

  1. the input string should not be null or any invalid data.
  2. It throws ParseException, try to handle it.

Wednesday

How to split string in java

How to split string in java

String is the most and commonly used function in java.String has lot of inbuilt functions and the most common one is split() function. You all java developers know how to use split function in java.
String str = "hai:how:are:the:one";
String str1 = str.split(":");
for(String s:str1)
{
System.out.println(s);
}

For String Tokenizer StringTokenizer the program is much like this.


StringTokenizer str2 = new StringTokenizer(str, ":");
while (str2.hasMoreElements()) {
System.out.println(str2.nextToken());
}


OutPut:

hai
how
are
the
one

By giving the limit:


String str = "hai:how:are:the:one";
String str1 = str.split(":",2);
for(String s:str1)
{
System.out.println(s);
}

OutPut:

hai
how:are:the:one

Monday

Difference between equals method and == operator in java

In java Programming both are used for comparing. The == is used to compare primitive and objects while the later is used to compare objects. Use of both can vary based on the business needs.

What is "==" operator in java.

comparing primitives like boolean, int, float "==" works fine, but for objects comparison it uses the memory location. Return True only if both the memory reference are same otherwise return false.

What is "equals" method in java.

It also returns true if both the memory reference are same. It checks the values inside the object.

Difference between Java equals and == :

Main difference between == and equals in Java is that "==" is used to compare primitives while equals() method is recommended to check equality of objects. Another difference between them is that, If both "==" and equals() is used to compare objects than == returns true only if both references points to same object while equals() can return true or false based on its overridden implementation.

String a = new String("hai i am here");
String b = new String("hai i am here");
     
boolean c = a == b;
System.out.println(" == operator: " + c);
     
result = a.equals(b);
System.out.println("equals method: " + c);
     
homeLoan = personalLoan;

result = (a == b);
System.out.println("reference pointing same String with == operator: " + c);

Output:
Comparing two strings with == operator: false
Comparing two Strings with same content using equals method: true
Comparing two reference pointing to same String with == operator: true


Conclusion:


  • For comparing primitive types use "==".
  • For comparing objects of the same refernce use "equals".
  • For String comparison use "equals" rather than "==".

Ways to concatenate String in java

String Concatenation in java is a real topic for every programmer. Many of the programmers are not yet aware of what are the ways to concatenate string in java. What are the ways...


  • String.concat().
  • Normal Concatenation using (+) operator.
  • String Buffer
  • StringBuilder
1. Using Concatenation Operator(+):-

 
                           It's the easy way to do the job. Ex:- String s = "hai how what when"+"where why"+"think or not" ; But just think if you are using this in a for loop. Each time String will create a new object inside the string pool. It will create performance leakage.

2.Using StringBuffer and StringBuilder append():-

                                   Using the String Buffer or String Builder. StringBuilder str = new StringBuilder().append("hai when where").append("why how what").toString();


Program for Concatenation in java:

String firstname = "Sachin"String lastname = "Tendulkar"Use + operator to concatenate String String name = firstname + " " + lastname; System.out.println(name);// first way
StringBuilder StringBuilder sb = new StringBuilder(14); 
sb.append(firstname).append(" ").append(lastname); System.out.println(sb.toString()); //second way
StringBuffer StringBuffer sBuffer = newStringBuffer(15);
 sBuffer.append(firstname).append(" ").append(lastname); System.out.println(sBuffer.toString());//third way

Out Put:

Sachin Tendulkar
Sachin Tendulkar
Sachin Tendulkar


  • String.concat().------- 1358 ms
  • Normal Concatenation using (+) operator. --------6568 ms
  • String Buffer ------------- 2.8 ms
  • StringBuilder -------------- 2.4 ms
So better to use StringBulder for larger Concatenations and inside for loops.