Day 9 and 10
Day 9 and 10
Arrays in Java
An array is a collection of elements of the same data type stored in contiguous memory
locations. In Java, arrays are objects, so they are created dynamically using the new keyword.
Types of Arrays:
2. One-Dimensional Array
Example:
System.out.println(arr[0]); // Output: 10
System.out.println(arr[2]); // Output: 30
Traversing an Array:
System.out.println(arr[i]);
3. Multi-Dimensional Array
Syntax of a 2D Array:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Traversing a 2D Array:
Example:
public class Main {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
4. Strings in Java
A String is a sequence of characters. In Java, strings are objects of the String class, which
provides many methods to manipulate them.
Creating a String:
String Methods:
Concatenation of Strings:
String s1 = "Hello";
String s2 = "World";
Pattern printing involves using loops to print a sequence of numbers, symbols, or characters
in a structured format.
System.out.println();
}
Output:
12
123
1234
12345
System.out.println();
System.out.println();
}
Output:
12345
1234
123
12
System.out.print("* ");
System.out.println();
Output:
**
***
****
*****
max = arr[i];
reversed += str.charAt(i);
Write a program to print the Fibonacci series up to a given number using an array.
public class Main {
fib[0] = 0;
fib[1] = 1;
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int sum = 0;
sum += matrix[i][j];
}
System.out.println("Sum of elements: " + sum);
Arrays: Use arrays to store and manipulate collections of data. Arrays can be one-
dimensional or multi-dimensional.
Strings: Strings are objects in Java and are immutable. You can use various methods
provided by the String class to manipulate strings.
Pattern Printing: You can print patterns using loops (nested for loops are commonly used).