×

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

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond,...

4 minutes read.

Java Heap Space Out of Memory Error

This error is called an "out of memory" error, which indicates that the JVM cannot allocate an object in memory from the heap. Hence the java.lang.out of memory error, describing...

2 minutes read.