string – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Mon, 26 Dec 2022 18:27:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg string – Programmerbay https://programmerbay.com 32 32 How to Reverse a String in Java https://programmerbay.com/java-program-to-reverse-a-string/ https://programmerbay.com/java-program-to-reverse-a-string/#respond Mon, 12 Dec 2022 07:38:21 +0000 https://www.programmerbay.com/?p=4156 The Java program reverses a string using different techniques and inbuilt methods which we’ll be discussing in this article.

 

In Java, objects of a String class are immutable, as a results, one can’t alter them. Further, If there is a need to alter a string after its creation, then StringBuilder and StringBuffer are two classes come into picture. As they produce mutable strings and provide reverse() method to reverse a string.

They can be used to finish the program within 2 or 3 lines. Alternatively, a string can also be reversed with the help of an array.

These are the following approaches to reverse a string in Java :

  1. Using StringBuilder
  2. Using StringBuffer
  3. Using toCharArray method
  4. Using swapping technique
  5. Using List
  6. Using recursion technique

Example 1. Program to reverse a string in Java using StringBuilder

Program:

import java.util.Scanner;
/**
 * Reverse a string using StringBuilder
 *
 * */
public class StringReverse {

    public static void main(String[] args) {
        String word;
        System.out.print("Please enter a String = ");
        Scanner ed = new Scanner(System.in);
        word = ed.nextLine();
        StringBuilder str = new StringBuilder(word);
        System.out.println(word + " reversed to " + str.reverse() + " using in StringBuilder");
    }
}

Output:

Please enter a String = Programmerbay
Programmerbay reversed to yabremmargorP using in StringBuilder

Example 2. Program to reverse a string in Java using StringBuffer

Program:

import java.util.Scanner;
/**
 * Reverse a string using StringBuffer
 *
 * */
public class StringReverse {

    public static void main(String[] args) {
        String word;
        System.out.print("Please enter a String = ");
        Scanner ed = new Scanner(System.in);
        word = ed.nextLine();
        StringBuffer str = new StringBuffer(word);
        System.out.println(word + " reversed to " + str.reverse() + " using in StringBuffer");
    }
}

Output:

Please enter a String = angry
angry reversed to yrgna using in StringBuffer

 

Example 3. Program to reverse a string in Java using char Array

In this approach, we have converted the input string to character array and traversing it backward.

Program:

import java.util.Scanner;

/**
 * Reverse a string by converting a string to character array
 */
public class StringReverse {

    public static void main(String[] args) {
        String word, reversed = "";
        char ch[];
        int i, size;
        System.out.print("Please enter a String = ");
        Scanner ed = new Scanner(System.in);
        word = ed.nextLine();
        ch = word.toCharArray();
        size = word.length() - 1;
        for (i = size; i >= 0; i--) {
            reversed = reversed + ch[i];
        }
        System.out.println(word + " reversed to " + reversed);
    }
}

Output:

Please enter a String = programmerbay
programmerbay reversed to yabremmargorp

Example 4. Program to reverse a string in Java by Swapping

Program:

/**
 * Reverse a string by swapping technique
 */
public class StringReverse {

    public static void main(String[] args) {
        String str = "programmerbay";
        char[] chrArr = str.toCharArray();
        for (int i = 0 ; i<=str.length() - 1 ;i++){
            int backrdPos =  str.length() - (i+1);
            if(i < (backrdPos) ) {
                char temp = chrArr[i];
                chrArr[i] =  chrArr[backrdPos];
                chrArr[backrdPos] = temp;
            }
        }
        System.out.println("Reversed String :: ");
        for (char ch:
             chrArr) {
            System.out.print(ch);
        }
    }
}

Output:

Reversed String :: 
yabremmargorp

Example 5. Program to reverse a string in Java using list

Program:

/**
 * Reverse a string by converting the string to list
 */
public class StringReverse {

    public static void main(String[] args) {
        String str = "programmerbay";
        List<Character> characterList = new ArrayList<>();
        for (char ch:
             str.toCharArray()) {
            characterList.add(ch);
        }
        Collections.reverse(characterList);
        System.out.print(str+" reversed to :: ");
        for (Character ch:
             characterList) {
            System.out.print(ch);
        }
    }
}

Output:

programmerbay reversed to :: yabremmargorp

Example 6. Program to reverse a string in Java using recursion

/**
 * Reverse a string by recursion
 */
public class StringReverse {

    public static void main(String[] args) {
        String str = "programmerbay";
        System.out.println(str + " reversed to :: "+ getReverseString(str.toCharArray(), str.length() - 1,""));
    }

    private static String getReverseString(char[] chrArr, int len,String rvrStr) {
        if(len < 0){
            return rvrStr;
        }
        rvrStr = rvrStr + chrArr[len];
        return getReverseString(chrArr, --len, rvrStr);
    }
}

Output:

programmerbay reversed to :: yabremmargorp

 

]]>
https://programmerbay.com/java-program-to-reverse-a-string/feed/ 0
program to count a particular word occurrence in a Sequence of string without using loop https://programmerbay.com/program-to-count-a-particular-word-occurrence-in-a-string-without-using-loop/ https://programmerbay.com/program-to-count-a-particular-word-occurrence-in-a-string-without-using-loop/#respond Thu, 27 Feb 2020 07:19:02 +0000 https://programmerbay.com/?p=6131 Program:

public class Main {
   static int count = 0;
    String search;
    int len;
    String[] str;
    Main(String[] s,String srch){
str = s;
search = srch;
len = s.length;
    }

    int call_me(int len) {

        if (len < 1) // base case
        {
            return count;
        } else if (str[len].equals(search)) {
            ++count;
        }
        return call_me(len - 1);
    }

    public static void main(String[] args) {
        Main obj;
        String[] str = {"this","is","a","string","and","a","sequence","of","a","string","arr"};
        obj = new Main(str,"a");
        System.out.println(obj.search+" occurred "+obj.call_me(obj.len-1)+" times");

    }
}

Output:

a occurred 3 times

]]>
https://programmerbay.com/program-to-count-a-particular-word-occurrence-in-a-string-without-using-loop/feed/ 0
Java Program to replace a substring without using replace method https://programmerbay.com/java-program-to-replace-a-substring-without-using-replace-method/ https://programmerbay.com/java-program-to-replace-a-substring-without-using-replace-method/#respond Thu, 27 Feb 2020 04:53:26 +0000 https://programmerbay.com/?p=6125 Given a string str that may consist a sequence of characters and we need to replace a sub-string with a specific character sequence without using replace method.

Program:

class Main {
    public static void main(String[] args) {
            String str = "newBay", replace="new";
            String replaceTo = "programmer";

        int position =str.indexOf(replace);
        int len = replace.length();
        String new_string = str.substring(0, position) + replaceTo +
                str.substring(position+len);
        System.out.println(new_string);
    }
}

Output:

ProgrammerBay

Explanation

  • Have a string str containing ‘newBay’
  • In the above code, we need to replace  substring ‘new’ present in ‘newBay’ with ‘programmer’
  • Storing the occurring position of ‘replace’ string and its length too
  • Since, the position of ‘new’, we got is 0 , therefore, str.substring(0,position) would extract nothing
  • replaceTo concatenated with ‘ ‘ subtring extracted by  str.substring(0,position)
  • str.substring(position+len) extracted ‘Bay’ from ‘newBay’. Now after concatenating, we got ‘ProgrammerBay’

]]>
https://programmerbay.com/java-program-to-replace-a-substring-without-using-replace-method/feed/ 0
Difference between String, StringBuilder and StringBuffer in Tabular form https://programmerbay.com/difference-between-string-stringbuilder-and-stringbuffer/ https://programmerbay.com/difference-between-string-stringbuilder-and-stringbuffer/#respond Tue, 25 Feb 2020 18:34:42 +0000 https://programmerbay.com/?p=6089 Java supports three classes to operate on strings, String, StringBuffer and StringBuilder. The main difference between them is, String is immuatable, whereas StringBuffer & StringBuilder provides mutable object.

Difference between String, StringBuilder and StringBuffer in Tabular form

Basis
String
StringBuilder
StringBuffer
String Type
A String class always create an immutable string
It produces a mutable string
It provides another way of creating mutable string
Thread Safe
It doesn’t ensure thread safety as it’s not synchronized
It is not thread safe
It is synchronized which assures thread safe enviroment
Performance
It serves slower performance as it creates a separate object on each manipulation It is not thread safe and this is why, it provides faster performance than StringBuffer
It is synchronized that is the reason it provides slower performance than StringBuilder
Memory Wastage
Each time when manipulations are made to a string, a new object with applied changes created, despite the instance which always reference to original string
Operations are always performed on the original string object. It reflects the changes on that respective string.
Simmilar to StringBuilder, operations performed on a string alters the orginal version of the existing string.
Memory allocation It gets memory on String Constant Pool, even though it generated from String constructor as it first gets space on Heap but afterwards ends up with String pool
It uses Heap to store a string
It takes up space in Heap
PurposedJava 1.0Java 1.5Java 1.2

Java String

A string is a sequence of characters of object type that provides a way to work efficiently with this character array or string.

A string object is immutable which means that making any changes would not affect the respective string, instead a new string object comes into existence carrying those changes.

No matter how many operations are performed, the string reference variable always point towards original string.

In short ,

  • String is a character sequence
  •  It is immutable
  • It is an object backed by String Class
  •  It supports several methods that assures efficient string handling.
  • Each time when an operation is performed on these strings, a new string object would be created and original one remain unchanged

string

public class Main{ 
public static void main(String[] args) 
{ 
String str ="Programmer"; 
str.concat("Bay"); 
System.out.println(" After Concatenation "+str); 
} 
}

Output:

Programmer

Explanation:

Since, the instance “str” would never change its reference therefore the output was Programmer.

str.concat(“Bay”) was creating “ProgrammerBay” which lead to a new object.

Java StringBuilder

StringBuilder is used to create mutable strings and is growable in nature. It is not thread safe, that is why it provides faster performance than StringBuffer. However, when it comes to multithreading where multiple threads try to access an object, in such case, one should go with StringBuffer.

It has two primary methods, append and insert. Append adds a character sequence at the end each time whereas insert put a specific set of characters at specified location. It automatically grows larger as and when internal buffer overflows.

In other words,

  • StringBuilder is a class that allows mutable strings
  • It is not thread safe, which means it’s not synchronized
  • It provides faster performance
  • It supports several methods which involves append(),insert(),charAt() and more

Picture2

public class Main{ 
public static void main(String[] args) 
{ 
String str ="Programmer"; 
str.append("Bay"); 
System.out.println(" After Concatenation "+str); 
} 
}

Output:

ProgrammerBay

Explanation:

str.append(“Bay”) was creating “ProgrammerBay” and update the object to which str was referencing.

Java StringBuffer

A way of having synchronized string object along with its operational methods . It is thread safe as each and every thread would sequentially access and perform the operations on the object using predefined methods. The only difference between String Buffer and String Builder is the thread safety.

In other words,

  • StringBuffer is a class that creates mutable strings
  • It is thread safe, which means it’s synchronized
  • It provides slower performance
  • It supports several methods append(),insert(),charAt() and more

Lets see Which one executes faster

String using String Class Program:

package com.company;

class Example implements  Runnable {
    String str = new String("Programmer");

    @Override
    public void run() {
        for(int i =0;i<10000000;i++) {
            str.concat(" ");
        }
    }
}
public class Main {

    public static void main(String[] args) {
Example obj = new Example();
 Thread thread1 = new Thread(obj);
        long start = System.currentTimeMillis();

        thread1.start();

        try {
            thread1.join();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();

        System.out.printf((end-start) + "ms");

    }
}

Output:

161ms

String using StringBuilder Program :

package com.company;

class Example implements  Runnable {
    StringBuilder str = new StringBuilder("Programmer");

    @Override
    public void run() {
        for(int i =0;i<10000000;i++) {
            str.append(" ");
        }
    }
}
public class Main {

    public static void main(String[] args) {
Example obj = new Example();
 Thread thread1 = new Thread(obj);
        long start = System.currentTimeMillis();

        thread1.start();

        try {
            thread1.join();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();

        System.out.printf((end-start) + "ms");

    }
}

Output:

48ms

String using StringBuffer Program :

class Example implements  Runnable {
    StringBuffer str = new StringBuffer("Programmer");

    @Override
    public void run() {
        for(int i =0;i<10000000;i++) {
            str.append(" ");
        }
    }
}
public class Main {

    public static void main(String[] args) {
Example obj = new Example();
 Thread thread1 = new Thread(obj);
        long start = System.currentTimeMillis();

        thread1.start();

        try {
            thread1.join();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();

        System.out.printf((end-start) + "ms");

    }
}

Output:

255ms

]]>
https://programmerbay.com/difference-between-string-stringbuilder-and-stringbuffer/feed/ 0