
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What Does the Method copyOf(int original, int newLength) Do in Java
The copyOf (int[] original, int newLength) method of the java.util.Arrays class copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid within the copy however not the original, the copy can contain zero. Such indices will exist if and only if the specified length is greater than that of the original array.
Example
import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { int[] arr1 = new int[] {45, 32, 75}; System.out.println("Printing 1st array:"); for (int i = 0; i < arr1.length; i++) { System.out.println(arr1[i]); } int[] arr2 = Arrays.copyOf(arr1, 5); arr2[3] = 11; arr2[4] = 55; System.out.println("Printing new array:"); for (int i = 0; i < arr2.length; i++) { System.out.println(arr2[i]); } } }
Output
Printing 1st array: 45 32 75 Printing new array: 45 32 75 11 55
Advertisements