1. Why sometimes we need to pass an array to a method? Use an JAVA code to show
ID: 3827646 • Letter: 1
Question
1. Why sometimes we need to pass an array to a method? Use an JAVA code to show how to pass an array to a method.
2. What are the differences between array and arraylist in JAVA. What are the advantages of using arraylist?
3. If we want to copy an array, why can't we use the code below? How to correct it?
import java.util.Arrays;
public class CopyAnArray {
public static void main(String[] args){
int[] x = {1, 2, 3, 4, 5};
int[] y = x;
}}
4. Is the code below correct? Why or why not?
class Vehicle {
public void move(){
System.out.println(“Vehicles can move!!”);
}}
class MotorBike extends Vehicle {
public void repair(){}}
class Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move();
vh.repair();
}}
Explanation / Answer
1)1. Why sometimes we need to pass an array to a method? Use an JAVA code to show how to pass an array to a method.
Ans)
int arr[]={1,2,3,4,5}; //creating an array
function(arr); //passing the array as argument to the function
______________
2)What are the differences between array and arraylist in JAVA. What are the advantages of using arraylist?
Ans)
An array is used to store a group of elements of same type.we cannot store different type of elements into an array.We cant extend the side of an array
An ArrayList can hold a group of elements of different types.The size of an ArrayList increases dynamically while we storing elements into it.
_________________
3)
If we want to copy an array, why can't we use the code below? How to correct it?
import java.util.Arrays;
public class CopyAnArray {
public static void main(String[] args){
int[] x = {1, 2, 3, 4, 5};
int[] y = x;
}}
Ans) If we want to copy one array elements into another array elements.The size of an array must be same.and type must be same.So that we can iterate over the array which we want to copy the elements and populate each element into the destination array by using a loop .
But here we didnt specified the size of the array 'y'.By simply assigning the array 'x' to 'y' we cant copy the elements of array 'x' into array 'y'
_________________
4) The code is not correct,because we are creating an obejct to the super class or base class(Vehicle) in the main method.We are calling the method .repair(); on the Vehicle clas object.which is not available.So whiich gives compilation error.
To resolve this we have to create the Sub-class object.So that we can access both sub class method and super class method.
______________Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.