How to fix “exception in thread main java.lang.stringindexoutofboundsexception string index out of range” errors

I'm trying to recreate the game of mastermind except a simplified version. I've been stuck on this one error and I don't know how to fix it.

I'm trying to recreate the game of mastermind except a simplified version. I've been stuck on this one error and I don't know how to fix it.

String combo = "";
int plus = 0;
String in = "";
int right = 0;
int numbers = 6;
int length = 4;
int tries = 10;
int[] guessNums = new int[numbers];
int[] comboNums = new int[numbers];

rules();
combo = guesses();

for(int i = 0; i < length; i++)

{
if(in.charAt(i) == combo.charAt(i))
{
right++;
}
guessNums[in.charAt(i)-49]++;
comboNums[combo.charAt(i)-49]++;
}

for(int i = 0; i < numbers; i++)
{
while(comboNums[i] > 0 && guessNums[i] > 0)
{
plus++;
comboNums[i]--;
guessNums[i]--;
}
}
String reset = "\u001B[0m";
System.out.print("\t");
String a = "" + right;
printRed(a);
System.out.println(" " + reset + "" + plus);
System.out.println("\n");

tries--;
return(right == length);


it says the error is in line if(in.charAt(i) == combo.charAt(i)).

How to convert an Array to String in Java?

How to convert an Array to String in Java?

In this post, you'll learn the various methods to convert an Array to String in Java

Below are the various methods to convert an Array to String in Java:

1. Arrays.toString() method:

Arrays.toString() method is used to return a string representation of the contents of the specified array. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters “, ” (a comma followed by a space). It returns “null” if the array is null.

// Java program to demonstrate 
// working of Arrays.toString() 

import java.io.*; 
import java.util.*; 

class GFG { 
	public static void main(String[] args) 
	{ 

		// Let us create different types of arrays and 
		// print their contents using Arrays.toString() 
		boolean[] boolArr 
			= new boolean[] { true, true, false, true }; 
		char[] charArr 
			= new char[] { 'g', 'e', 'e', 'k', 's' }; 
		double[] dblArr 
			= new double[] { 1, 2, 3, 4 }; 
		int[] intArr 
			= new int[] { 1, 2, 3, 4 }; 
		Object[] objArr 
			= new Object[] { 1, 2, 3, 4 }; 

		System.out.println( 
			"Boolean Array: "
			+ Arrays.toString(boolArr)); 
		System.out.println( 
			"Character Array: "
			+ Arrays.toString(charArr)); 
		System.out.println( 
			"Double Array: "
			+ Arrays.toString(dblArr)); 
		System.out.println( 
			"Integer Array: "
			+ Arrays.toString(intArr)); 
		System.out.println( 
			"Object Array: "
			+ Arrays.toString(objArr)); 
	} 
} 

Output

Boolean Array: [true, true, false, true]
Character Array: [g, e, e, k, s]
Double Array: [1.0, 2.0, 3.0, 4.0]
Integer Array: [1, 2, 3, 4]
Object Array: [1, 2, 3, 4]
2. StringBuilder append(char[]):

The java.lang.StringBuilder.append(char[]) is the inbuilt method which appends the string representation of the char array argument to this StringBuilder sequence.

// Java program to illustrate the 
// StringBuilder.append(char[]) method 

import java.lang.*; 

public class Geeks { 

	public static void main(String[] args) 
	{ 

		StringBuilder sbf 
			= new StringBuilder("We are geeks "); 
		System.out.println(sbf); 

		// Char array 
		char[] astr 
			= new char[] { 'G', 'E', 'E', 'k', 'S' }; 

		// Appends string representation of char 
		// array to this String Builder 
		sbf.append(astr); 
		System.out.println("Result after"
						+ " appending = "
						+ sbf); 

		sbf = new StringBuilder("We are -"); 
		System.out.println(sbf); 

		// Char array 
		astr = new char[] { 'a', 'b', 'c', 'd' }; 

		/* Appends string representation of char 
				array to this StringBuilder */
		sbf.append(astr); 
		System.out.println("Result after appending = " + sbf); 
	} 
} 

Output:

We are geeks 
Result after appending = We are geeks GEEkS
We are -
Result after appending = We are -abcd

Java String – String Functions In Java With Examples

Java String – String Functions In Java With Examples

In this post, we will be discussing about a new concept, Java String. String is a sequence of characters. But in Java, a string is an object that represents a sequence of characters. The java.lang.String class is used to create string object.

Originally published by Aayushi Johari at https://www.edureka.co
There are two ways to create a String object:
By string literal : Java String literal is created by using double quotes. For Example: String s=“Welcome”; By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”); It creates two objects (in String pool and in heap) and one reference variable where the variable ‘s’ will refer to the object in the heap.
Now, let us understand the concept of Java String pool.

**Java String Pool: **Java String pool refers to collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned. Refer to the diagrammatic representation for better understanding:

In the above image, two Strings are created using literal i.e “Apple” and “Mango”. Now, when third String is created with the value “Apple”, instead of creating a new object, the already present object reference is returned. That’s the reason Java String pool came into the picture.

Before we go ahead, One key point I would like to add that unlike other data types in Java, Strings are immutable. By immutable, we mean that Strings are constant, their values cannot be changed after they are created. Because String objects are immutable, they can be shared. For example:

   String str =”abc”;

is equivalent to:

char data[] = {‘a’, ‘b’, ‘c’};
     String str = new String(data);

Let us now look at some of the inbuilt methods in String class.

Java String Methods

Java String length(): The Java String length() method tells the length of the string. It returns count of total number of characters present in the String. For example:

public class Example{
public static void main(String args[]{
String s1="hello";
String s2="whatsup";
System.out.println("string length is: "+s1.length()); 
System.out.println("string length is: "+s2.length());
}}

Here, String length() function will return the length 5 for s1 and 7 for s2 respectively.
Java String compareTo(): The Java String compareTo() method compares the given string with current string. It is a method of* ‘Comparable’* interface which is implemented by String class. Don’t worry, we will be learning about String interfaces later. It either returns positive number, negative number or 0. For example:

public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="hemlo";
String s4="flag";
System.out.println(s1.compareTo(s2)); // 0 because both are equal
System.out.println(s1.compareTo(s3)); //-1 because "l" is only one time lower than "m"
System.out.println(s1.compareTo(s4)); // 2 because "h" is 2 times greater than "f"
}} 

This program shows the comparison between the various string. It is noticed that

if s1 > s2, it returns a positive number

if s1 < s2, it returns a negative number

if s1 == s2, it returns 0
**Java String concat() : **The Java String concat() method combines a specific string at the end of another string and ultimately returns a combined string. It is like appending another string. For example:

public class ConcatExample{
public static void main(String args[]){
String s1="hello";
s1=s1.concat("how are you");
System.out.println(s1);
}}

The above code returns “hellohow are you”.
Java String IsEmpty() : This method checks whether the String contains anything or not. If the java String is Empty, it returns true else false. For example:

public class IsEmptyExample{
public static void main(String args[]){
String s1="";
String s2="hello";
System.out.println(s1.isEmpty());      // true
System.out.println(s2.isEmpty());      // false
}}

  • Java String Trim() : The java string trim() method removes the leading and trailing spaces. It checks the unicode value of space character (‘u0020’) before and after the string. If it exists, then removes the spaces and return the omitted string. For example:
public class StringTrimExample{ 
public static void main(String args[]){ 
String s1="  hello   "; 
System.out.println(s1+"how are you");        // without trim() 
System.out.println(s1.trim()+"how are you"); // with trim() 
}}  

In the above code, the first print statement will print “hello how are you” while the second statement will print “hellohow are you” using the trim() function.

  • Java String toLowerCase() : The java string toLowerCase() method converts all the characters of the String to lower case. For example:
public class StringLowerExample{
public static void main(String args[]){
String s1="HELLO HOW Are You?”;
String s1lower=s1.toLowerCase();
System.out.println(s1lower);}
}

The above code will return “hello how are you”.

  • Java String toUpper() : The Java String toUpperCase() method converts all the characters of the String to upper case. For example:
public class StringUpperExample{ 
public static void main(String args[]){ 
String s1="hello how are you"; 
String s1upper=s1.toUpperCase(); 
System.out.println(s1upper); 
}}

The above code will return “HELLO HOW ARE YOU”.
Java String ValueOf(): This method converts different types of values into string.Using this method, you can convert int to string, long to string, Boolean to string, character to string, float to string, double to string, object to string and char array to string. The signature or syntax of string valueOf() method is given below: public static String valueOf(boolean b) public static String valueOf(char c) public static String valueOf(char[] c) public static String valueOf(int i) public static String valueOf(long l) public static String valueOf(float f) public static String valueOf(double d) public static String valueOf(Object o)
Let’s understand this with a programmatic example:

public class StringValueOfExample{
public static void main(String args[]){
int value=20;
String s1=String.valueOf(value);
System.out.println(s1+17);       //concatenating string with 10
}}

In the above code, it concatenates the Java String and gives the output – 2017.
Java String replace(): The Java String replace() method returns a string, replacing all the old characters or CharSequence to new characters. There are 2 ways to replace methods in a Java String.

public class ReplaceExample1{
public static void main(String args[]){
String s1="hello how are you";
String replaceString=s1.replace('h','t');
System.out.println(replaceString); }}

In the above code, it will replace all the occurrences of ‘h’ to ‘t’. Output to the above code will be “tello tow are you”. Let’s see the another type of using replace method in java string:

**Java String replace(CharSequence target, CharSequence replacement) method **:

public class ReplaceExample2{
public static void main(String args[]){
String s1="Hey, welcome to Edureka";
String replaceString=s1.replace("Edureka","Brainforce");
System.out.println(replaceString);
}}

In the above code, it will replace all occurrences of “Edureka” to “Brainforce”. Therefore, the output would be “ Hey, welcome to Brainforce”.
Java String contains() :The java string contains() method searches the sequence of characters in the string. If the sequences of characters are found, then it returns true otherwise returns false. For example:

class ContainsExample{
public static void main(String args[]){
String name=" hello how are you doing";
System.out.println(name.contains("how are you"));  // returns true
System.out.println(name.contains("hello"));        // returns true 
System.out.println(name.contains("fine"));         // returns false 
}}

In the above code, the first two statements will return true as it matches the String whereas the second print statement will return false because the characters are not present in the string.
Java String equals() : The Java String equals() method compares the two given strings on the basis of content of the string i.e Java String representation. If all the characters are matched, it returns true else it will return false. For example:

public class EqualsExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="hi";
System.out.println(s1.equalsIgnoreCase(s2));   // returns true
System.out.println(s1.equalsIgnoreCase(s3));   // returns false
}
}

  • **JavaString equalsIgnoreCase(): **This method compares two string on the basis of content but it does not check the case like equals() method. In this method, if the characters match, it returns true else false. For example:
public class EqualsIgnoreCaseExample{
public static void main(String args[]){
String s1="hello";
String s2="HELLO";
String s3="hi";
System.out.println(s1.equalsIgnoreCase(s2));   // returns true
System.out.println(s1.equalsIgnoreCase(s3));   // returns false
}}

In the above code, the first statement will return true because the content is same irrespective of the case. Then, in the second print statement will return false as the content doesn’t match in the respective strings.
**Java String toCharArray(): **This method converts the string into a character array i.e first it will calculate the length of the given Java String including spaces and then create an array of char type with the same content. For example:

StringToCharArrayExample{
public static void main(String args[]){
String s1="Welcome to Edureka";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.print(ch[i]);
}}}

The above code will return “Welcome to Edureka”.
Java StringGetBytes() : The Java string getBytes() method returns the sequence of bytes or you can say the byte array of the string. For example:

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

In the above code, it will return the value 65,66,67.
Java String IsEmpty() : This method checks whether the String is empty or not. If the length of the String is 0, it returns true else false. For example:

public class IsEmptyExample{
public static void main(String args[]) {
String s1="";
String s2="hello";
System.out.prinltn(s1.isEmpty());     // returns true
System.out.prinltn(s2.isEmpty());     // returns false
}}

In the above code, the first print statement will return true as it does not contain anything while the second print statement will return false.
Java String endsWith() : The Java String endsWith() method checks if this string ends with the given suffix. If it returns with the given suffix, it will return true else returns false. For example:

public class EndsWithExample{
public static void main(String args[]) {
String s1="hello how are you”;
System.out.println(s1.endsWith("u"));       // returns true
System.out.println(s1.endsWith("you"));     // returns true  
System.out.println(s1.endsWith("how"));     // returns false
}}

This is not the end. There are more Java String methods that will help you make your code simpler.

Moving on, Java String class implements three interfaces, namely – Serializable, Comparable and CharSequence.

Since, Java String is immutable and final, so a new String is created whenever we do String manipulation. As String manipulations are resource consuming, Java provides two utility classes: StringBuffer and StringBuilder.

Let us understand the difference between these two utility classes:
StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized whereas StringBuilder operations are not thread-safe.StringBuffer is to be used when multiple threads are working on same String and StringBuilder in the single threaded environment.StringBuilder performance is faster when compared to StringBuffer because of no overhead of synchronized.
I hope you guys are clear with Java String, how they are created, their different methods and interfaces. I would recommend you to try all the Java String examples. Do read my next blog on Java Interview Questions which will help you set apart in the interview process.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Top 4 Spring Annotations for Java Developer in 2019

Java Tutorial for Absolute Beginners

100+ Java Interview Questions and Answers In 2019

Python vs Java: Understand Object Oriented Programming

Understanding Arrays in Java

Understanding Arrays in Java

An array is a group of like-typed variables that are referred to by a common name.Arrays in Java work differently than they do in C/C++. Following are some important point about Java arrays.

Originally published at https://www.geeksforgeeks.org

Following are some important point about Java arrays.

  • In Java all arrays are dynamically allocated.(discussed below)
  • Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find length using sizeof.
  • A Java array variable can also be declared like other variables with [] after the data type.
  • The variables in the array are ordered and each have an index beginning from 0.
  • Java array can be also be used as a static field, a local variable or a method parameter.
  • The size of an array must be specified by an int value and not long or short.
  • The direct superclass of an array type is Object.
  • Every array type implements the interfaces Cloneable and java.io.Serializable.

Array can contains primitives data types as well as objects of a class depending on the definition of array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in heap segment. 

Creating, Initializing, and Accessing an Array

One-Dimensional Arrays :

The general form of a one-dimensional array declaration is

type var-name[];
OR
type[] var-name;

An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array. Like array of int type, we can also create an array of other primitive data types like char, float, double..etc or user defined data type(objects of a class).Thus, the element type for the array determines what type of data the array will hold.

Example:

// both are valid declarations
int intArray[]; 
or int[] intArray; 

byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];

// an array of references to objects of
// the class MyClass (a class created by
// user)
MyClass myClassArray[];

Object[] ao, // array of Object
Collection[] ca; // array of Collection
// of unknown type

Although the above first declaration establishes the fact that intArray is an array variable, no array actually exists. It simply tells to the compiler that this(intArray) variable will hold an array of the integer type. To link intArray with an actual, physical array of integers, you must allocate one using new and assign it to intArray.

Instantiating an Array in Java

When an array is declared, only a reference of array is created. To actually create or give memory to array, you create an array like this:The general form of new as it applies to one-dimensional arrays appears as follows:

var-name = new type [size];

Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and var-name is the name of array variable that is linked to the array. That is, to use new to allocate an array, you must specify the type and number of elements to allocate.

Example:

int intArray[];    //declaring array
intArray = new int[20]; // allocating memory to array

OR

int[] intArray = new int[20]; // combining both statements in one

Note :

  1. The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types).
  2. Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java all arrays are dynamically allocated.

Array Literal

In a situation, where the size of the array and variables of array are already known, array literals can be used.

 int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
  • The length of this array determines the length of the created array.
  • There is no need to write the new int[] part in the latest versions of Java

Accessing Java Array Elements using for Loop

Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop.


// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);

Implementation:

// Java program to illustrate creating an array 
// of integers, puts some values in the array, 
// and prints each value to standard output. 

class GFG 

public static void main (String[] args) 
{  
// declares an Array of integers. 
int[] arr; 

// allocating memory for 5 integers.&nbsp;
arr = new int[5];&nbsp;
	
// initialize the first elements of the array&nbsp;
arr[0] = 10;&nbsp;
	
// initialize the second elements of the array&nbsp;
arr[1] = 20;&nbsp;
	
//so on...&nbsp;
arr[2] = 30;&nbsp;
arr[3] = 40;&nbsp;
arr[4] = 50;&nbsp;
	
// accessing the elements of the specified array&nbsp;
for (int i = 0; i &lt; arr.length; i++)&nbsp;
	System.out.println("Element at index " + i +&nbsp;
								" : "+ arr[i]);		&nbsp;
}&nbsp;


Output:

Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

You can also access java arrays using foreach loops

Arrays of Objects

An array of objects is created just like an array of primitive type data items in the following way.

 Student[] arr = new Student[7]; //student is a user-defined class

The studentArray contains seven memory spaces each of size of student class in which the address of seven Student objects can be stored.The Student objects have to be instantiated using the constructor of the Student class and their references should be assigned to the array elements in the following way.

Student[] arr = new Student[5];


// Java program to illustrate creating an array of 
// objects 

class Student 

public int roll_no; 
public String name; 
Student(int roll_no, String name) 

this.roll_no = roll_no; 
this.name = name; 

// Elements of array are objects of a class Student. 
public class GFG 

public static void main (String[] args) 

// declares an Array of integers. 
Student[] arr; 

	// allocating memory for 5 objects of type Student.&nbsp;
	arr = new Student[5];&nbsp;


	// initialize the first elements of the array&nbsp;
	arr[0] = new Student(1,"aman");&nbsp;


	// initialize the second elements of the array&nbsp;
	arr[1] = new Student(2,"vaibhav");&nbsp;


	// so on...&nbsp;
	arr[2] = new Student(3,"shikar");&nbsp;
	arr[3] = new Student(4,"dharmesh");&nbsp;
	arr[4] = new Student(5,"mohit");&nbsp;


	// accessing the elements of the specified array&nbsp;
	for (int i = 0; i &lt; arr.length; i++)&nbsp;
		System.out.println("Element at " + i + " : " +&nbsp;
					arr[i].roll_no +" "+ arr[i].name);&nbsp;
}&nbsp;


Output:

Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit

What happens if we try to access element outside the array size?

JVM throws ArrayIndexOutOfBoundsException to indicate that array has been accessed with an illegal index. The index is either negative or greater than or equal to size of array.

class GFG 

public static void main (String[] args) 

int[] arr = new int[2]; 
arr[0] = 10; 
arr[1] = 20; 

	for (int i = 0; i &lt;= arr.length; i++)&nbsp;
		System.out.println(arr[i]);&nbsp;
}&nbsp;


Runtime error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at GFG.main(File.java:12)

Output:

10
20

Multidimensional Arrays

Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other array. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square brackets ([]) per dimension. Examples:

int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array


class multiDimensional 

public static void main(String args[]) 

// declaring and initializing 2D array 
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} }; 

	// printing 2D array&nbsp;
	for (int i=0; i&lt; 3 ; i++)&nbsp;
	{&nbsp;
		for (int j=0; j &lt; 3 ; j++)&nbsp;
			System.out.print(arr[i][j] + " ");&nbsp;


		System.out.println();&nbsp;
	}&nbsp;
}&nbsp;


Output:

2 7 9
3 6 1
7 4 2

Passing Arrays to Methods

Like variables, we can also pass arrays to methods.For example, below program pass array to method sum for calculating sum of array’s values.

// Java program to demonstrate 
// passing of array to method 

class Test 
{  
// Driver method 
public static void main(String args[]) 

int arr[] = {3, 1, 2, 5, 4}; 

	// passing array to method m1&nbsp;
	sum(arr);&nbsp;

}&nbsp;


public static void sum(int[] arr)&nbsp;
{&nbsp;
	// getting sum of array values&nbsp;
	int sum = 0;&nbsp;
	
	for (int i = 0; i &lt; arr.length; i++)&nbsp;
		sum+=arr[i];&nbsp;
	
	System.out.println("sum of array values : " + sum);&nbsp;
}&nbsp;


Output :

sum of array values : 15

Returning Arrays from Methods

As usual, a method can also return an array. For example, below program returns an array from method m1.

// Java program to demonstrate 
// return of array from method 

class Test 
{  
// Driver method 
public static void main(String args[]) 

int arr[] = m1(); 

	for (int i = 0; i &lt; arr.length; i++)&nbsp;
		System.out.print(arr[i]+" ");&nbsp;

}&nbsp;


public static int[] m1()&nbsp;
{&nbsp;
	// returning array&nbsp;
	return new int[]{1,2,3};&nbsp;
}&nbsp;


Output:

1 2 3

Class Objects for Arrays

Every array has an associated Class object, shared with all other arrays with the same component type.

// Java program to demonstrate 
// Class Objects for Arrays 

class Test 

public static void main(String args[]) 

int intArray[] = new int[3]; 
byte byteArray[] = new byte[3]; 
short shortsArray[] = new short[3]; 

	// array of Strings&nbsp;
	String[] strArray = new String[3];&nbsp;
	
	System.out.println(intArray.getClass());&nbsp;
	System.out.println(intArray.getClass().getSuperclass());&nbsp;
	System.out.println(byteArray.getClass());&nbsp;
	System.out.println(shortsArray.getClass());&nbsp;
	System.out.println(strArray.getClass());&nbsp;
}&nbsp;


Output:

class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;

Explanantion :

  1. The string “[I” is the run-time type signature for the class object “array with component type int“.
  2. The only direct superclass of any array type is java.lang.Object.
  3. The string “[B” is the run-time type signature for the class object “array with component type byte“.
  4. The string “[S” is the run-time type signature for the class object “array with component type short“.
  5. The string “[L” is the run-time type signature for the class object “array with component type of a Class”. The Class name is then followed.

Array Members

Now as you know that arrays are object of a class and direct superclass of arrays is class Object.The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
  • The public method clone(), which overrides clone method in class Object and throws no checked exceptions.

Cloning of arrays

  • When you clone a single dimensional array, such as Object[], a “deep copy” is performed with the new array containing copies of the original array’s elements as opposed to references. 
// Java program to demonstrate 
// cloning of one-dimensional arrays 

class Test 
{  
public static void main(String args[]) 

int intArray[] = {1,2,3}; 

	int cloneArray[] = intArray.clone();&nbsp;
	
	// will print false as deep copy is created&nbsp;
	// for one-dimensional array&nbsp;
	System.out.println(intArray == cloneArray);&nbsp;
	
	for (int i = 0; i &lt; cloneArray.length; i++) {&nbsp;
		System.out.print(cloneArray[i]+" ");&nbsp;
	}&nbsp;
}&nbsp;


Output:

false
1 2 3

  • A clone of a multidimensional array (like Object[][]) is a “shallow copy” however, which is to say that it creates only a single new array with each element array a reference to an original element array but subarrays are shared.
// Java program to demonstrate 
// cloning of multi-dimensional arrays 

class Test 
{  
public static void main(String args[]) 

int intArray[][] = {{1,2,3},{4,5}}; 

	int cloneArray[][] = intArray.clone();&nbsp;
	
	// will print false&nbsp;
	System.out.println(intArray == cloneArray);&nbsp;
	
	// will print true as shallow copy is created&nbsp;
	// i.e. sub-arrays are shared&nbsp;
	System.out.println(intArray[0] == cloneArray[0]);&nbsp;
	System.out.println(intArray[1] == cloneArray[1]);&nbsp;
	
}&nbsp;


Output:

false
true
true

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

How to Manipulate Arrays in JavaScript

Learn NumPy Arrays With Examples

All about JavaScript Arrays Methods

The Complete Guide to Arrays in Go