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.