×

Java String getBytes() method

getBytes() method returns sequence of bytes.

Syntax:

There are three variants of getBytes() method:
public byte[] getBytes()       
public byte[] getBytes(String charsetName)
public byte[] getBytes(Charset charset)

Returns:

It returns sequence of bytes.

Java String getBytes() Example 1

public class JavaStringGetBytesEx1
{ 
                     public static void main(String args[])
{ 
            String s1="ghijklm"; 
            byte[] barr=s1.getBytes(); 
            for(int i=0;i<barr.length;i++){ 
             System.out.println(barr[i]); 
     } 
   }
}

Output:

103
104
105
106
107
108
109

Java String getBytes() Example 2

public class JavaStringGetBytesEx2
{
    public static void main(String[] args)
    {
        String str = "tutorialandexample";
        // Copy the contents of the String to a byte array.
byte[] byte_arr = str.getBytes();
        // Create a new String using the contents of the byte array.
        String new_str = new String(byte_arr);
        String str1 = new_str.concat(".com");
        // Display the contents of the byte array.
System.out.println("\nBest online Tutorial site : " +
str1 + "\n");
    }
}

Output:

Best online Tutorial site : tutorialandexample.com

Java String getBytes() Example 3

import java.nio.charset.Charset;
public class JavaStringGetBytesEx3 {
  public static void main(String[] args) {
    try {
      String str = "tutorialandexample.com";
      System.out.println();
      System.out.println("\n Given String = " + str);
      // copy the contents of the String to a byte array
      byte[] arr = str.getBytes(Charset.forName("ASCII"));
      String s1 = new String(arr);
      System.out.println(" New string = " + s1);
            System.out.println();
    } catch (Exception e) {
      System.out.print(e.toString());
      System.out.println();
    }
  }
}

Output:

Given String = tutorialandexample.com
New string = tutorialandexample.com

Java String getBytes() Example 4

import java.nio.charset.Charset;
public class JavaStringGetBytesEx4 {
  public static void main(String[] args) {
    try {
      String str = "tutorialandexample.com";
      System.out.println();
      System.out.println("\n Given String = " + str);
      // copy the contents of the String to a byte array
      byte[] arr = str.getBytes(Charset.forName("ASCII"));
       for(int i=0;i<arr.length;i++){ 
            System.out.println(arr[i]); 
        }
      String s1 = new String(arr);
      System.out.println(" New string = " + s1);
            System.out.println();
    } catch (Exception e) {
      System.out.print(e.toString());
      System.out.println();
    }
  }
}

Output:

Given String = tutorialandexample.com
116
117
116
111
114
105
97
108
97
110
100
101
120
97
109
112
108
101
46
99
111
109
New string = tutorialandexample.com

Related Topics

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Java Regular Expressions

Java Regular Expressions The Java Regex or Regular Expression is an API that defines a pattern for searching or manipulating strings. A regular expression is a pattern that can be as simple as...

8 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.