Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
public class Test {
	public static void main(String[] args)
	{
		int[] a={10,20,80,40,50};
		int[] b={10,20,80,40,50};
		int[] c=new int[a.length+b.length];
		int x=0;
		for(int i=0;i<=a.length-1;i++)
		{
			c[x++]=a[i];
		}
		
		for(int j=0;j<=b.length;j++)
		{
			c[x++]=b[j];
		}
		
		for(int k=0;k<=c.length-1; k++)
		{
			System.out.println(c[k]);
		}
	}

}


What I have tried:

I am trying to merge 2 arrays and store in different array, but I am getting array index out of bound exception though I have intialized the array with proper size
Posted
Updated 11-Aug-19 5:20am

It must be:
for(int j=0;j<=b.length-1;j++)
 
Share this answer
 
Java
for(int i=0;i<=a.length-1;i++)

Rather than adding a '-1' to the end condition of a loop, common usage is to use strictly lower operator.
Java
for(int i=0; i<a.length; i++)

Quote:
I am getting array index out of bound exception though I have initialized the array with proper size

When you don't understand why your code fail, the debugger will show you the exact condition of fail.

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900