﻿ Java exercises: Merge two given sorted array of integers and create a new sorted array - w3resource # Java Exercises: Merge two given sorted array of integers and create a new sorted array

## Java Basic: Exercise-113 with Solution

Write a Java program to merge two given sorted array of integers and create a new sorted array.

Example
array1 = [1,2,3,4]
array2 = [2,5,7, 8]
result = [1,2,2,3,4,5,7,8]

Pictorial Presentation: Sample Solution:

Java Code:

``````import java.util.*;
public class Example113 {
public static void main(String[] arg)
{

// Sorted integer array array1 which has m elements,
// but size of array1 is m+n, sorted integer array array2 which has n elements

//declaration and instantiation.
int array1[]=new int;
//initialization.
array1=1;
array1=2;
array1=3;
array1=4;
int[] array2 = {2,5,7,8};
System.out.println("\nArray1: "+Arrays.toString(array1));
System.out.println("\nArray2: "+Arrays.toString(array2));
int m =4, n=4;
int i = m-1, j = n-1, index = m + n - 1;
while (i >= 0 && j >= 0) {
if (array1[i] > array2[j]) {
array1[index--] = array1[i--];
} else {
array1[index--] = array2[j--];
}
}
while (i >= 0) {
array1[index--] = array1[i--];
}
while (j >= 0) {
array1[index--] = array2[j--];
}

System.out.println("\nMerged array: "+Arrays.toString(array1));
}
}
```
```

Sample Output:

```Array1: [1, 2, 3, 4, 0, 0, 0, 0]

Array2: [2, 5, 7, 8]

Merged array: [1, 2, 2, 3, 4, 5, 7, 8]
```

Flowchart: Java Code Editor:

What is the difficulty level of this exercise?

﻿

## Java: Tips of the Day

Try and catch:

Java is excellent at catching errors, but it can only recover gracefully if you tell it what to do. The cascading hierarchy of attempting to perform an action in Java starts with try, falls back to catch, and ends with finally. Should the try clause fail, then catch is invoked, and in the end, there's always finally to perform some sensible action regardless of the results. Here's an example:

```try {
cmd = parser.parse(opt, args);

if(cmd.hasOption("help")) {
HelpFormatter helper = new HelpFormatter();
helper.printHelp("Hello ", opt);
System.exit(0);
}
else {
if(cmd.hasOption("shell") || cmd.hasOption("s")) {
String target = cmd.getOptionValue("tgt");
} // else
} // fi
} catch (ParseException err) {
System.out.println(err);
System.exit(1);
} //catch
finally {
new Hello().helloWorld(opt);
} //finally
} //try
```

It's a robust system that attempts to avoid irrecoverable errors or, at least, to provide you with the option to give useful feedback to the user. Use it often, and your users will thank you!

Ref: https://red.ht/3EZc9OC