Home » Java programming language

Java String copyValueOf() Method with Example

Java String copyValueOf() Method: Here, we are going to learn about the copyValueOf() method with example in Java.
Submitted by IncludeHelp, on February 20, 2019

String copyValueOf() Method

copyValueOf() is a String method in Java and it is used to create a string with given character array i.e. it accepts a character array and returns a string. In other words, we can say copyValueOf() method is used to copy the value of character array to the string.

Syntax:

    String str_object.concat(char[] chr, [int offset], [int len]);

Here,

  • chr is a character array, we have to convert into a string.
  • str_object is the main string in which we have to copy the copy the value of the character array.
  • offset is an optional parameter, it is used to set the starting offset (position), from where we want to copy the character array as a string.
  • length is also an optional parameter, it is used to define the number of characters to be copied as a string.

Method accepts a character array and returns string.

Example:

    Input: 
    char char_arr[] = {'I','n','c','l','u','d','e','h','e','l','p'};

    Function call                       Output
    str.copyValueOf(char_arr)           Includehelp
    str.copyValueOf(char_arr, 7, 4)     help

Java code to demonstrate the example of String.copyValueOf() method

public class Main
{
    public static void main(String[] args) {
        char char_arr[] = {'I','n','c','l','u','d','e','h','e','l','p'};
        String str ="";
        
        //copying char[] and creating string 
        str = str.copyValueOf(char_arr);
        System.out.println("str = " + str);
        
        //using offset and length
        str = str.copyValueOf(char_arr, 7, 4);
        System.out.println("str = " + str);

    }
}

Output

str = Includehelp
str = help


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.