Arrays 1.1
Arrays 1.1
Arrays 1.1
HOW?
Solution 1
Ramesh can create twelve set of
variables to store marks of twelve
students.
S1 S2 S3 … … ... S12
Solution 2
He can create one variable called mark in Mark
that mark he can store marks of twelve
Students
S1 S2 S3 S3 S12
Array
Java array is an object which contains elements of a similar data type.
Array Types
• 1D array
• 2D array
How to declare an array
dataType[] arrayName;
Example:
int[] data;
data = new int[10];
(or)
int[] data=new int[10];
Memory Allocation
• Static 1D array
• Dynamic 1D array
Java array index
int data[]=new int[5];
Last element
First element
data[0] data[1] data[2] data[3] data[4]
1 2 3 4 5
0 1 2 3 4
Syntax:
new Datatype[] {val1, val2..valn};
1
2 import java.util.*;
3 public class MyClass {
4 public static void main(String args[])
5 {
6 int s1 = sum(new int[]{1,2,3,4,5});
7 System.out.print(s1);
8 }
9 public static int sum(int a[])
10 {
11 int total = 0;
12 for(int i:a)
13 {
14 total = total+i;
15 }
16 return total;
17 }
18 }
19
20
21
22
Programming
Question 1
Write a Java code to search a given number in an array. If the element is
found then print Found, else print Not Found
B) ArrayIndexOutOfBoundsException
C) 40
D) 30
1 // Predict the output
2 import java.util.Scanner;
3 class Main
4 {
5 public static void main (String[] args)
6 {
7 int arr[] = {10, 20, 30, 40};
int a = 50;
8
call(a,arr);
9
System.out.println(a);
10
System.out.println(arr[0]);
11 System.out.println(arr[1]);
12 }
13 public static void call(int a, int arr[])
14 {
15 a = a + 2;
16 arr[0] = 100;
17 arr[1] = 200;
18 }
19 }
20
21
22
Question 2
A) 50
100
200
B) 52
100
200
C) 50
10
20
D) 52
10
20
1 // Predict the output
2 import java.util.Scanner;
3 public class Main
4 {
5 public static void main(String args[])
6 {
7 int arr[2];
8 System.out.println(arr[0]);
9 System.out.println(arr[1]);
10 }
11 }
12
13
14
15
16
17
18
19
20
21
22
Question 3
A) Garbage value
Garbage value
B) ArrayIndexOutOfBoundsException
C) Compilation error
D) 0
0
THANK YOU