ArrayInJava

 Syntex:

Hard Code(Array Initialization):

Array of Integer:  int[] a={10,20,30};

Array of float:  float a[] = {10.0f, 20.7f, 30.4f};

Array of Double:  double[] a={10.0,20.7,30.4};

Array of String: String[] a={"Sara","Ali","Fatima"};

Array of char:  char[] a={'a','b','c'};


Soft Code(Array Decleration):

Array of Integer:   int[] a = new int[4];

Array of float:  float[] a = new float[4];

Array of Double:  double[] a = new double[4];

Array of String:  String[] a = new String[4];

Array of char:  char[] a = new char[4];


Class Array:

class abc{
int id=0;
String name="";
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}
public class hacking {

public static void main(String[] args) {

abc[] a = new abc[2];

a[0]=new abc();  //Create instances of abc and assign them to array elements
a[1]=new abc(); //Create instances of abc and assign them to array elements

a[0].setId(1);
a[0].setName("sughra");

a[1].setId(2);
a[1].setName("shahbaz");

for(int i=0;i<2;i++)
{
System.out.println("ID: "+a[i].getId());
System.out.println("Name: "+a[i].getName());
}
}

Practice Programs:

  1. Array Basics: a. Declare an array of integers and initialize it with values 10, 20, 30, 40, and 50. b. Print the third element of the array. c. Modify the second element to have a value of 25.
  2. Array Iteration: a. Declare an array of doubles and initialize it with values 2.5, 4.8, 6.2, 8.1, and 3.7. b. Use a loop to iterate through the array and print each element.
  3. Array Sum: a. Declare an array of integers and initialize it with values 5, 10, 15, 20, and 25. b. Calculate and print the sum of all elements in the array.
  4. Array Maximum: a. Declare an array of integers and initialize it with values 17, 42, 8, 59, and 23. b. Find and print the maximum value in the array.
  5. Array Search: a. Declare an array of strings and initialize it with values "apple", "banana", "orange", "grape", and "kiwi". b. Write a method that takes a string as input and returns whether it exists in the array or not.
  6. Array Sorting: a. Declare an array of integers and initialize it with values 32, 7, 15, 48, and 21. b. Sort the array in ascending order and then print the sorted elements.
  7. Array Reversal: a. Declare an array of characters and initialize it with values 'h', 'e', 'l', 'l', and 'o'. b. Reverse the elements of the array and print the reversed array.
  8. Array Copy: a. Declare an array of integers and initialize it with values 5, 10, 15, 20, and 25. b. Create a new array and copy the elements from the original array into it. c. Print the elements of the new array.
  9. Array Manipulation: a. Declare an array of integers and initialize it with values 3, 6, 9, 12, and 15. b. Multiply each element by 2 and store the results back in the array. c. Print the modified array.