1
import java.util.Scanner;

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

    int i, j;

    String name = "kamal";
    char[] ab = name.toCharArray ();
    String actor = "hasan";
    char[] cd = actor.toCharArray ();

    int l1 = ab.length;
    int l2 = cd.length;

    System.out.println (l1);
    System.out.println (l2);


for (i =0;i <=l2;i++)
      {


        ab[l1 + i] = cd[i];

      }

   System.out.println(ab);   


  }

}

I am getting the output as 5,5 ArrayIndexOut of Bounds Not the output as kamalhasan

5
  • 1
    Arrays in Java have a fixed length. You can't write new elements at indices greater than length - 1. Read docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html. To concatenate two strings, you can just use name + actor. Commented Jan 1, 2020 at 8:16
  • There are many ways to concatenate two strings in java. Do you want to do it only by using arrays? Commented Jan 1, 2020 at 8:27
  • @abra Yes I want to concatenate only using arrays Commented Jan 1, 2020 at 8:40
  • 1
    So make a third array whose size can accommodate the two names. Using your example, you would need an array of size 10 (ten). Iterate the first array, copying the characters to the third array. Then iterate the second array and continue copying to the third. Commented Jan 1, 2020 at 8:44
  • Why aren't you doing string concatenation using string concatenation? The + operator already does it. No need for all this code. Commented Jan 1, 2020 at 8:50

2 Answers 2

1

As @dassum pointed out above, you are adding elements to "ab" array that has fixed length of 5. You can create another array of length "l1+l2", then first copy content of "ab" and then of "cd".

char[] concatenatedArray = new char[l1+l2];

for (i =0;i <l1;i++)
{
    concatenatedArray[i] = ab[i];
}

for (i =0;i <l2;i++)
{
    concatenatedArray[l1+i] = cd[i];
}
System.out.println(concatenatedArray);
Sign up to request clarification or add additional context in comments.

Comments

0

2 things are wrong in your code

  1. ab[l1 + i] = cd[i]; ab array is of size 5 and you are adding elements beyond that. Arrays in Java have fixed length.

  2. for (i =0;i <=l2;i++) : You cannot iterate the array till length. Arrays starts with position 0.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.