stringbuffer – 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 stringbuffer – 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
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