Lab 5 - ARRAYS
Lab 5 - ARRAYS
ORIENTED PROGRAMMING
Lab 5
Arrays and Strings
Array Declaration
DataType [ ] ArrayName
Array Initialization
DataType [ ] ArrayName = {val1, val2, val3}
Array Initialization
int [ ] num = {2,6,3,9,7,0}
Access the values of array
In Java there are two ways to access the element of an array, lets look at examples below:
num[2] = 4;
System.out.println(num[2])
Multi Dimensional array
A multidimensional array is an array of arrays. Multidimensional arrays are useful when you want to store data
as a tabular form like a table with rows and columns.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
for (int i = 0; i < nums.length; i++) {
result += nums[i];
}
System.out.println("Average is " + result / nums.length);
}
}
Array Example 2
Initialize 2D Array with Random Numbers
Write a program to initialize and print a 5x5 2D array with random numbers.
class RandomArray2D {
public static void main(String[] args) {
double[][] array2d = new double[5][5];
for (int row = 0; row < array2d.length; row++) {
for (int col = 0; col < array2d[row].length; col++) {
array2d[row][col] = Math.round(Math.random());
}}
for (int row = 0; row < array2d.length; row++) {
for (int col = 0; col < array2d[row].length; col++) {
System.out.print(array2d[row][col] + " ");}
System.out.println();
}}}
What are the strings in Java
Strings are used for storing text. A String variable contains a collection of characters
surrounded by double quotes
Length of a String
System.out.println("The length of the txt string is: " + text.length());
Uppercase Strings
System.out.println(“String to Upper Case: " + text.toUpperCase());
Lowercase Strings
System.out.println(" String to Lower Case : " + text.toLowerCase());