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

Create user defined substring functions

 
In many interviews we may asked to substring() a string without using substring function from String class. Below are the simple code how we can write our own substring functions similar to String class functions.


public class MyStringOp {

 public static void main(String[] args) {
  
  String str = "Java Discover";
  
  MyStringOp obj = new MyStringOp();
  
  System.out.println(obj.mySubstring(str, 5));
  
  System.out.println(obj.mySubstring(str, 0,4));
 }
 
 public String mySubstring(String str, int start){
  
  if(start > str.length()) 
   throw new StringIndexOutOfBoundsException(); 
  
  String newStr = "";
  char[] ch = str.toCharArray();
  
  for(int i=start;i<str.length();i++){
   newStr = newStr + ch[i];
  }
  return newStr;
 }
 
 public String mySubstring(String str, int start, int end){
  
  if((start > end) || (start > str.length()) || (end > str.length())) 
   throw new StringIndexOutOfBoundsException(); 
  
  String newStr = "";
  char[] ch = str.toCharArray();
  
  for(int i=start;(i<str.length() && i<end);i++){
   newStr = newStr + ch[i];
  }
  return newStr;
 }
}




OUTPUT:


Discover
Java


Character Array to String in Java

 
We may seen lot of arrays like Integer, Character, Float and Double or even String array. In this tutorial we will see about converting Character array to String in Java code. We can achieve this by 2 ways like given below,
Character Array to String in Java


public class CharToString {

 public static void main(String[] args) {
  
  char[] myArray = new char[]{'j','a','v','a',' ','d','i','s','c','o','v','e','r'};
  
  //By 2 ways we can convert char[] to String and lets see both ways
  
  String type1 = String.valueOf(myArray);

String type2 = new String(myArray);
  
  
  System.out.println("TYPE 1 : "+type1);
  System.out.println("TYPE 2 : "+type2);
 }
}

OUTPUT:

TYPE 1 : java discover
TYPE 2 : java discover

Calculate String Length

 
This is one of the simple interview question that need to calculate String length without using length() function. There are lot of ways to find the find the length like converting String to Character array and by iterating it. Lets see simple java code to calculate string length.
Calculate String length




public class StringSize {

 public static void main(String[] args) {
  
                String str = "Java Discover";
  
                int length = getStringLength(str);
  
                System.out.printf("String - %s \nLength - %d ",str,length);
 }
 
 public static int getStringLength(String str){
  
                int length = 0;
  
                char[] array = str.toCharArray();
  for (char c : array) {
   length++;
  }
  
                return length;
 }
}


OUTPUT:


String - Java Discover 
Length - 13



String replace in java

string replace in java

We all know that String class is a immutable and values once stored will not be changed. So what is String replace and how its working in java? basically whenever we change are replace the value in String new String Object will be created.
And also have to know that every-time it won't create String Object, only when string change happen in string value then it will create new String Object otherwise it will return same String Object. Totally there are 4 types of replace methods are there in Java,

public String replace(char oldChar, char newChar)
- Used to replace matching character in a String and returns the new String Object. 

public String replace(CharSequence target, CharSequence replacement)
- Used to replace set of character sequence in a String and returns the new String Object.  

public String replaceAll(String regex, String replacement)
- Used to replace all matching pattern in String using regular expression or either simple string and returns the new String Object.  

public String replaceFirst(String regex, String replacement)
- This method is simplar to above method but only used to replace first matching pattern in String using regular expression or either simple string and returns the new String Object.

Important:

  • As we seen above if there is not actual replace then these all methods will return same String Object instead of new String Object.
  • All these methods are Case Sensitive and will replace only with matching case characters.

First lets see simple example for calling replace method and there's no actual replace, so we need to get same String Object.



public class StringReplaceTest {

 public static void main(String[] args) {
  
  String source = "Hello Java";
  
  String str2 = source.replace("hi", "hello");
  
  //By using == operator we can test is it same Object
  if(source == str2){
   System.out.println("First Compare - Both are same String Object");
  }else{
   System.out.println("First Compare - Both are NOT same String Object");
  }
  
  /************************************************/
  
  String str3 = source.replace("Hello", "Hello");
  
  //By using == operator we can test is it same Object
  if(source == str3){
   System.out.println("Second Compare - Both are same String Object");
  }else{
   System.out.println("Second Compare - Both are NOT same String Object");
  }
 }
}


OUTPUT:


First Compare - Both are same String Object
Second Compare - Both are NOT same String Object



In above example we are trying to replace string "hi" with string"hello" where "hi" is not present in source string. So replace method will return same String Object instead of new String in first compare. 
In second replace we trying to replace "Hello" with same same string "Hello" where "Hello" present in source string. So replace method will return new String Object. 


Now lets see simple examples for all 4 replace methods in java 


public class StringReplaceTest {

 public static void main(String[] args) {
  
  String source = "Hello Java Hello";
  
  // Replace character with new character
  String str1 = source.replace('H', 'S');
  System.out.println("\nMethod 1 : "+str1);
  
  // Replace character sequence with new character sequence
  CharSequence old = "Java";
  CharSequence _new = "String";
  
  String str2 = source.replace(old, _new);
  System.out.println("\nMethod 2 : "+str2);
  
  // Replace all matching pattern
  String str3 = source.replaceAll("el", "al");
  System.out.println("\nMethod 3 : "+str3);
  
  // Replace any matching pattern at beginning of the line
  String str4 = source.replaceAll("^H", "S");
  System.out.println("Method 3 : "+str4);
  
  // Replace only first matching pattern
  String str5 = source.replaceFirst("Hello", "Hi");
  System.out.println("\nMethod 4 : "+str5);
 }
}

OUTPUT:


Method 1 : Sello Java Sello

Method 2 : Hello String Hello

Method 3 : Hallo Java Hallo
Method 3 : Sello Java Hello

Method 4 : Hi Java Hello



Character Frequency in String

 
Character Frequency in String

This is one of the easy interview programming question under 3 years experience. Lets assume given a lengthy string and asked you to find each character frequency. For example the given string is "hello java discover". In this string 'h'=1 , 'o'=2 etc., need to find each character occurred counts need to printed. 
We can achieve this by many ways like converting to character array and then manipulating each character or in looping count each character occurrence and store in any Collection object etc., In our below example we will use HashMap to store characters as key and their counts in value part.


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

public class CharFreq {

 public static void main(String[] args) {

  String str = "hello javadiscover";

  Map<Character, Integer> map = new HashMap<Character, Integer>();

  for (int i = 0; i < str.length(); i++) {
   char ch = str.charAt(i);
   if (map.get(ch) != null) {
    map.put(ch, (map.get(ch) + 1));
   } else {
    map.put(ch, 1);
   }
  }

  Set<Character> set = map.keySet();
  for (Character character : set) {
   System.out.println(character + " : " + map.get(character));
  }
 }
}


OUTPUT:


  : 1 // space character 
d : 1
e : 2
c : 1
a : 2
o : 2
l : 2
j : 1
h : 1
i : 1
v : 2
s : 1
r : 1



Java String

 
Java String

We all know String class in Java is immutable and the value once stored in String Object can't be modified. Also we have discussed about this in our earlier tutorials like difference between String, StringBuffer and StringBuilder and how to create user defined immutable class in Java. We will see how "==" equals operator works on String Object. 

We know that when we apply "==" equals operator on Object it will check only the Object reference rather than values stored in the Object. So using "==" on string Object will result incorrect output and advised to use equals() method which internally overrides hashcode() which will check the values in the Objects using hashing algorithm and gives the correct output.

In this tutorial we will see about how "==" equals operator works internally on string Object with different scenarios. 

Program : 1


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "javadiscover";
  System.out.println(str1 == str2);
 }
}

OUTPUT:


true



We can see in above disassembled code from Java class file, both String references are same. So when we compare these string Objects with "==" operator we will get true. 


Program : 2


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "java" + "discover";
  System.out.println(str1 == str2);
 }
}

OUTPUT:


true



We can see both the string Objects are referred by same reference. So we are getting true when we compare by "==" operator. 


Program : 3


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "java";
  String str3 = "discover";
  String str4 = str2 + str3;
  System.out.println(str1 == str4);
 }
}

OUTPUT:


false



From above code we can clearly see first 3 string objects are having different references. But 4th "Str4" String in java file contains same value of 1st String "str1" but JDK has created StringBuilder class instead of String with different reference. Hence we are getting false when we compare "str1" and "str4" with "==" operator. 



Split() in Java

 
Split in Java

In our earlier tutorial we have seen about String Tokenizer class in Java. And we have given Split method from String class which will be an alternate since String Tokenizer is legacy class. So its recommended to use split method from String class instead of StringTokenizer. So lets see whats the use if split method and how we can use in Java by using simple example. 

Split method used to search for the match as specified in the argument and splits the string and stores into an String array. There are 2 types of split methods in String class,

String str = "Hello how are you";
String arr[] = str.split(" ");

will give output as below, since we are splitting by space " "
Hello
how
are
you



String str = "Hello how are you";
String arr[] = str.split(" ", 2);

will give output as below, here we are requesting to split the string with the array size as 2. so remaining complete string will be stored in last array as below
Hello
how are you


Lets see simple java example with their output.


public class SplitTest {
 
 public static void main(String[] args) {
  String str = "Hello how are you";
  
  String arr[] = str.split(" ");
  for (String string : arr) {
   System.out.println(string);
  }
  
  System.out.println("-------------------------------");
  
  String arr1[] = str.split(" ",3);
  for (String string : arr1) {
   System.out.println(string);
  }
 }
}


OUTPUT:


Hello
how
are
you
-------------------------------
Hello
how
are you






String Tokenizer in Java


String Tokenizer in Java

In most of the older application we will be seen String Tokenizer class used for operations like splitting words or text from a given String or line. The String Tokenizer class allows user to break a String into tokens based on the input parameters. By default String Tokenizer will split the String and gives the token based on space character else we can provide our delimit as parameter. Lets see few String Tokenizer constructor parameters with their output.

StringTokenizer tok = new StringTokenizer("Hello how are you");
will give output as below, since space (" ") is a default delimiter
Hello
how
are
you

StringTokenizer tok = new StringTokenizer("Hello|how|are|you", "|");
will give output as below, since we have delimit as "|"
Hello
how
are
you

StringTokenizer tok = new StringTokenizer("Hello|how|are|you", "|", true);
will give output as below, true gives the delimiter along with tokens 
Hello
|
how
|
are
|
you

Lets see simple example of using String Tokenizer class in Java.


import java.util.StringTokenizer;

public class StringTokenizerTest {
 
 public static void main(String[] args) {
  
  StringTokenizer tok = new StringTokenizer("Hello how are you");
  while(tok.hasMoreTokens()){
   System.out.println(tok.nextElement());
  }
  
  System.out.println("-------------------------------");
  
  tok = new StringTokenizer("Hello|how|are|you", "|");
  while(tok.hasMoreTokens()){
   System.out.println(tok.nextElement());
  }
  
  System.out.println("-------------------------------");

  tok = new StringTokenizer("Hello|how|are|you", "|", true);
  while(tok.hasMoreTokens()){
   System.out.println(tok.nextElement());
  }
 }
}


OUTPUT:


Hello
how
are
you
-------------------------------
Hello
how
are
you
-------------------------------
Hello
|
how
|
are
|
you




Alternate:

String Tokenizer is from legacy class and because of compatibility reasons recommended to use "split" method from String class. Lets see this "split" method in our next tutorial



Difference between String, StringBuffer and StringBuilder


In this tutorial we will see about difference between String, StringBuffer and StringBuilder. The most important difference that String Object is immutable but whereas StringBuffer/ StringBuilder are mutable. 

So what is immutable and mutable?
Once a value assigned to the String Object then the values can't be modified or changed is called as immutable class. On the other end the values can be changed and modified is called as mutable class.

How String works in Java?
Since String is immutable class we can't change the values once we placed in String Object. But we are able to modify the String value in Java and how its possible? Yes, whenever we modify a String Object new Object will be created. Below example will explain more details on how String works in Java.

String val = "My";
val = val + " Friend";
System.out.println(val);

Output of above code will be "My Friend". We assume that value of "val" gets concatenated. But internally Java creates Object for every String operation which we does. In Java we can create String Object by 2 ways like 

Using "new" operator:
String val = new String("My");

Using String Literal:
String val = "Friend";

Since String creates Objects at each time, we need to switch to StringBuffer or StringBuilder whenever we does String concatenations to avoid multiple String Objects creation and to increase our application performance.

Internally StringBuilder and StringBuffer or mutable, then what is the difference?
If we go back to JDK versions StringBuffer introduced in JDK 1.4 and StringBuilder introduced in JDK 1.5 version. 
Other main difference between StringBuffer and StringBuilder are synchronization. Internally StringBuffer is synchronized and StringBuilder is non-synchronized. Synchronized means it is thread safe and we can use when we implement any multi-threading operations, only one thread can modify StringBuffer at a time. Whereas StringBuilder is not thread safe.

Lets see how to create StringBuffer and StringBuilder

StringBuffer:
StringBuffer str = new StringBuffer();
str.append("My");
str.append(" Friend");
System.out.println(str);

StringBuilder:
StringBuilder str = new StringBuilder();
str.append("My");
str.append(" Friend");
System.out.println(str);