Home » Java programming language

Convert a character array to the string in Java

Java | Convert character array to string: Here, we are going to learn how to convert a character array to the string in Java?
Submitted by IncludeHelp, on February 15, 2019

Given a character array and we have to convert it to the string in Java.

Java char[] to string conversion

There are two ways to convert a character array to the string in Java, which are,

  1. Using String.valueOf(char[]) method
  2. By creating a new string with character array

1) Java char[] to string example: Using String.valueOf(char[]) method

valueOf() method is a String class method, it accepts a character array and returns the string.

Example:

public class Main
{
    public static void main(String[] args) {
        char[] charArray = {'I', 'n', 'c', 'l', 'u', 'd', 'e', 'h', 'e', 'l', 'p'};
        String str ="";
        
        //converting from char[] to string
        str = String.valueOf(charArray);
        
        //printing value 
        System.out.println("str = " + str);
        
    }
}

Output

str = Includehelp

Java char[] to string example: by creating a new string with character array

We can create a new string with the character array.

Syntax:

    String str_var = new String(char[]);

Example:

public class Main
{
    public static void main(String[] args) {
        char[] charArray = {'I', 'n', 'c', 'l', 'u', 'd', 'e', 'h', 'e', 'l', 'p'};
        String str ="";
        
        //creating a new string  from char[]
        str = new String(charArray);
        
        //printing value 
        System.out.println("str = " + str);
        
    }
}

Output

str = Includehelp





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.