0% found this document useful (0 votes)
2 views9 pages

Java Basics Part3 Arrays Methods

This document covers Java basics focusing on arrays and methods, including declaration, initialization, operations, and common methods for arrays. It also explains method declaration, overloading, parameters, return values, and best practices for writing methods. Additionally, it provides a quick reference for array and method summaries.

Uploaded by

Aniket Deshpande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views9 pages

Java Basics Part3 Arrays Methods

This document covers Java basics focusing on arrays and methods, including declaration, initialization, operations, and common methods for arrays. It also explains method declaration, overloading, parameters, return values, and best practices for writing methods. Additionally, it provides a quick reference for array and method summaries.

Uploaded by

Aniket Deshpande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Java Basics - Part 3: Arrays & Methods

Arrays
Array Declaration and Initialization
// Declaration
int[] numbers;
String[] names;

// Initialization with size


int[] numbers = new int[5];
String[] names = new String[3];

// Initialization with values


int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
double[] prices = {10.99, 20.50, 15.75};

// Multi-dimensional arrays
int[][] matrix = new int[3][3];
int[][] matrix2 = {{1,2,3}, {4,5,6}, {7,8,9}};

// Jagged arrays (irregular)


int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[1];

Array Operations
int[] numbers = {1, 2, 3, 4, 5};

// Length
int length = numbers.length;

// Accessing elements
int first = numbers[0];
int last = numbers[numbers.length - 1];

// Modifying elements
numbers[0] = 10;
numbers[numbers.length - 1] = 100;

// Copying arrays
int[] copy = Arrays.copyOf(numbers, numbers.length);
int[] copyRange = Arrays.copyOfRange(numbers, 1, 4);

1
// Manual copying
int[] manualCopy = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
manualCopy[i] = numbers[i];
}

Common Array Methods


int[] numbers = {3, 1, 4, 1, 5};

// Sorting
Arrays.sort(numbers); // [1, 1, 3, 4, 5]

// Searching (array must be sorted)


int index = Arrays.binarySearch(numbers, 4);

// Filling
Arrays.fill(numbers, 0); // [0, 0, 0, 0, 0]
Arrays.fill(numbers, 1, 3, 10); // Fill positions 1-2 with 10

// Comparing
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
boolean equal = Arrays.equals(arr1, arr2);

// Converting to string
String arrayString = Arrays.toString(numbers);

// Deep comparison for multi-dimensional arrays


int[][] matrix1 = {{1,2}, {3,4}};
int[][] matrix2 = {{1,2}, {3,4}};
boolean deepEqual = Arrays.deepEquals(matrix1, matrix2);

Multi-dimensional Array Operations


int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}};

// Accessing elements
int element = matrix[1][2]; // 6

// Getting dimensions
int rows = matrix.length;
int cols = matrix[0].length;

// Iterating through 2D array

2
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

// Enhanced for loop


for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}

Array Utilities
// Creating arrays with Stream
int[] numbers = IntStream.range(0, 10).toArray();
int[] evenNumbers = IntStream.range(0, 10).filter(n -> n % 2 == 0).toArray();

// Converting between array types


Integer[] boxed = Arrays.stream(numbers).boxed().toArray(Integer[]::new);
int[] unboxed = Arrays.stream(boxed).mapToInt(Integer::intValue).toArray();

// Array to List
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Integer[] array = list.toArray(new Integer[0]);

Methods
Method Declaration
// Basic method
public void greet() {
System.out.println("Hello!");
}

// Method with parameters


public void greet(String name) {
System.out.println("Hello, " + name + "!");
}

// Method with return value


public int add(int a, int b) {

3
return a + b;
}

// Method with multiple return types


public String getGrade(int score) {
if (score >= 90) return "A";
else if (score >= 80) return "B";
else if (score >= 70) return "C";
else return "F";
}

// Method with array parameter


public int sumArray(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}

// Method returning array


public int[] createArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = i + 1;
}
return array;
}

Method Overloading
public class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}

public int add(int a, int b, int c) {


return a + b + c;
}

public String add(String a, String b) {


return a + b;

4
}

// Varargs method
public int add(int... numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
}

// Usage
Calculator calc = new Calculator();
int result1 = calc.add(5, 3); // 8
double result2 = calc.add(5.5, 3.2); // 8.7
int result3 = calc.add(1, 2, 3); // 6
String result4 = calc.add("Hello", "World"); // "HelloWorld"
int result5 = calc.add(1, 2, 3, 4, 5); // 15

Variable Arguments (Varargs)


public int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}

// Usage
int result1 = sum(1, 2, 3);
int result2 = sum(1, 2, 3, 4, 5);
int result3 = sum(); // 0

// Varargs with other parameters


public void printInfo(String prefix, int... numbers) {
System.out.print(prefix + ": ");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
}

// Usage
printInfo("Numbers", 1, 2, 3, 4, 5);

5
Method Parameters and Return Values
// Pass by value (primitives)
public void modifyPrimitive(int x) {
x = 100; // Original value unchanged
}

// Pass by reference (objects)


public void modifyArray(int[] arr) {
arr[0] = 100; // Original array modified
}

// Return multiple values using array


public int[] getMinMax(int[] numbers) {
int min = numbers[0];
int max = numbers[0];

for (int num : numbers) {


if (num < min) min = num;
if (num > max) max = num;
}

return new int[]{min, max};


}

// Return multiple values using object


public class MinMaxResult {
public int min;
public int max;

public MinMaxResult(int min, int max) {


this.min = min;
this.max = max;
}
}

public MinMaxResult getMinMaxObject(int[] numbers) {


int min = numbers[0];
int max = numbers[0];

for (int num : numbers) {


if (num < min) min = num;
if (num > max) max = num;
}

return new MinMaxResult(min, max);

6
}

Recursive Methods
// Factorial
public int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}

// Fibonacci
public int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}

// Binary search
public int binarySearch(int[] arr, int target, int left, int right) {
if (left > right) {
return -1;
}

int mid = left + (right - left) / 2;

if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
return binarySearch(arr, target, left, mid - 1);
} else {
return binarySearch(arr, target, mid + 1, right);
}
}

Method Best Practices


// Single responsibility principle
public class StringUtils {
// Good: Each method has a single purpose
public static String reverse(String str) {
return new StringBuilder(str).reverse().toString();
}

7
public static boolean isPalindrome(String str) {
return str.equals(reverse(str));
}

public static int countVowels(String str) {


int count = 0;
String vowels = "aeiouAEIOU";
for (char c : str.toCharArray()) {
if (vowels.indexOf(c) != -1) {
count++;
}
}
return count;
}
}

// Method naming conventions


public class Examples {
// Use verb-noun format
public void calculateTotal() { }
public String getUserName() { }
public boolean isValid() { }

// Avoid abbreviations
public void processData() { } // Good
public void procData() { } // Bad

// Be descriptive
public int getAge() { } // Good
public int getA() { } // Bad
}

Quick Reference
Array Summary
• Declaration: Type[] name;
• Initialization: new Type[size] or {val1, val2, ...}
• Length: array.length
• Access: array[index]
• Copy: Arrays.copyOf(), Arrays.copyOfRange()
• Sort: Arrays.sort()
• Search: Arrays.binarySearch() (sorted arrays)
• Compare: Arrays.equals(), Arrays.deepEquals()

8
Method Summary
• Declaration: accessModifier returnType methodName(parameters)
• Overloading: Same name, different parameters
• Varargs: Type... parameterName
• Return: return value; or implicit return for void
• Recursion: Method calling itself

Best Practices
1. Use meaningful method names
2. Keep methods small and focused
3. Use appropriate access modifiers
4. Document complex methods
5. Use method overloading for similar operations
6. Prefer varargs over array parameters when appropriate
7. Handle edge cases in methods
8. Use recursion carefully (consider stack overflow)
9. Return early to reduce nesting
10. Use consistent naming conventions

You might also like