# Java Beginner Guide - Part 3: Methods and Arrays ## Table of Contents - [Introduction](#introduction) - [Methods - Introduction](#methods---introduction) - [Method Parameters and Return Values](#method-parameters-and-return-values) - [Method Overloading](#method-overloading) - [Arrays - Introduction](#arrays---introduction) - [Working with Arrays](#working-with-arrays) - [Array Methods and Utilities](#array-methods-and-utilities) - [Two-Dimensional Arrays](#two-dimensional-arrays) - [Common Array Operations](#common-array-operations) - [Practice Exercises](#practice-exercises) --- ## Introduction In this guide, you'll learn two essential concepts: 1. **Methods** - Reusable blocks of code that perform specific tasks 2. **Arrays** - Collections that store multiple values in a single variable These are fundamental building blocks that every Java programmer needs to master! --- ## Methods - Introduction Methods (also called functions in other languages) are reusable blocks of code. Instead of writing the same code multiple times, you write it once in a method and "call" it when needed. ### Why Use Methods? - **Reusability** - Write once, use many times - **Organization** - Break code into logical chunks - **Easier Testing** - Test each method separately - **Readability** - Cleaner, easier to understand code ### Basic Method Structure ```java public class Main { // This is a method public static void sayHello() { System.out.println("Hello!"); } // Main method - where the program starts public static void main(String[] args) { sayHello(); // Call the method sayHello(); // Call it again sayHello(); // One more time } } ``` ### Method Parts Explained ```java public static void myMethod(String parameter) { // method body } ``` | Part | What It Means | |------|---------------| | `public` | Accessible from anywhere | | `static` | Can be called without creating an object | | `void` | Returns nothing | | `myMethod` | The name you use to call it | | `String parameter` | Input the method receives | ### Types of Methods ```java public class MethodTypes { // 1. No parameters, no return public static void greet() { System.out.println("Hello!"); } // 2. With parameters, no return public static void greetPerson(String name) { System.out.println("Hello, " + name + "!"); } // 3. With parameters, with return public static int add(int a, int b) { return a + b; } // 4. No parameters, with return public static String getMessage() { return "Welcome to Java!"; } public static void main(String[] args) { greet(); greetPerson("Alice"); int sum = add(5, 3); System.out.println(sum); // 8 System.out.println(getMessage()); } } ``` --- ## Method Parameters and Return Values ### Parameters Parameters are inputs that methods can accept: ```java // Single parameter public static void printTwice(String text) { System.out.println(text); System.out.println(text); } // Multiple parameters public static void introduce(String name, int age) { System.out.println("I am " + name + ", " + age + " years old."); } // Different types of parameters public static void processData(String message, int count, double price) { System.out.println(message + " - Count: " + count + ", Price: " + price); } ``` ### Return Values Use `return` to send a value back: ```java // Return an int public static int doubleNumber(int num) { return num * 2; } // Return a String public static String getFullName(String first, String last) { return first + " " + last; } // Return a boolean public static boolean isEven(int num) { return num % 2 == 0; } // Return an array public static int[] getNumbers() { return new int[]{1, 2, 3, 4, 5}; } ``` ### The return Statement - `return` exits the method immediately - Methods with `void` don't return anything - Methods with a return type MUST return a value ```java public static String checkAge(int age) { if (age >= 18) { return "Adult"; } else { return "Minor"; } // No need for else after return } ``` ### Passing by Value In Java, primitives are passed by value (a copy is made): ```java public static void changeValue(int num) { num = 100; // This only changes the local copy } public static void main(String[] args) { int num = 5; changeValue(num); System.out.println(num); // Still 5! } ``` --- ## Method Overloading Method overloading allows multiple methods with the same name but different parameters. ### Why Use It? Different ways to do similar things: ```java // Same method name, different parameters public static int add(int a, int b) { return a + b; } public static double add(double a, double b) { return a + b; } public static int add(int a, int b, int c) { return a + b + c; } public static void main(String[] args) { System.out.println(add(5, 3)); // Calls int version: 8 System.out.println(add(5.5, 3.2)); // Calls double version: 8.7 System.out.println(add(1, 2, 3)); // Calls three-param version: 6 } ``` ### Common Overloaded Methods ```java // Print can take any type! System.out.println(42); // int System.out.println("Hello"); // String System.out.println(3.14); // double System.out.println(true); // boolean ``` --- ## Arrays - Introduction Arrays store multiple values in a single variable. Instead of having 10 separate variables, you can have one array with 10 elements! ### Why Use Arrays? - Store related data together - Easy to process with loops - Efficient way to manage collections ### Declaring Arrays ```java // Method 1: Declare and create int[] numbers = new int[5]; // Method 2: Declare with values int[] numbers = {1, 2, 3, 4, 5}; // Method 3: Different syntax int numbers[] = {1, 2, 3, 4, 5}; ``` ### Array Types ```java // Integer array int[] ages = {20, 25, 30, 35}; // String array String[] names = {"Alice", "Bob", "Charlie"}; // Double array double[] prices = {19.99, 29.99, 9.99}; // Boolean array boolean[] flags = {true, false, true}; ``` ### Array Indexing Arrays start at index 0: ```java String[] fruits = {"Apple", "Banana", "Cherry"}; System.out.println(fruits[0]); // Apple (first element) System.out.println(fruits[1]); // Banana (second element) System.out.println(fruits[2]); // Cherry (third element) // Access with a variable int index = 1; System.out.println(fruits[index]); // Banana ``` --- ## Working with Arrays ### Accessing Elements ```java int[] numbers = {10, 20, 30, 40, 50}; // Get values System.out.println(numbers[0]); // 10 System.out.println(numbers[4]); // 50 // Set values numbers[0] = 100; System.out.println(numbers[0]); // 100 ``` ### Array Length ```java int[] numbers = {1, 2, 3, 4, 5}; System.out.println(numbers.length); // 5 ``` ### Looping Through Arrays ```java int[] scores = {95, 87, 92, 78, 88}; // Regular for loop for (int i = 0; i < scores.length; i++) { System.out.println("Score " + i + ": " + scores[i]); } // For-each loop (easier!) for (int score : scores) { System.out.println("Score: " + score); } ``` --- ## Array Methods and Utilities Java provides built-in ways to work with arrays: ### Arrays.toString() Convert an array to a readable string: ```java import java.util.Arrays; int[] numbers = {5, 2, 8, 1, 9}; System.out.println(Arrays.toString(numbers)); // [5, 2, 8, 1, 9] ``` ### Arrays.sort() Sort array elements: ```java import java.util.Arrays; int[] numbers = {5, 2, 8, 1, 9}; Arrays.sort(numbers); System.out.println(Arrays.toString(numbers)); // [1, 2, 5, 8, 9] ``` ### Arrays.fill() Fill an array with a value: ```java import java.util.Arrays; int[] numbers = new int[5]; Arrays.fill(numbers, 100); System.out.println(Arrays.toString(numbers)); // [100, 100, 100, 100, 100] ``` ### Arrays.copyOf() Copy an array: ```java import java.util.Arrays; int[] original = {1, 2, 3, 4, 5}; int[] copy = Arrays.copyOf(original, original.length); System.out.println(Arrays.toString(copy)); // [1, 2, 3, 4, 5] ``` --- ## Two-Dimensional Arrays Arrays can have multiple dimensions! A 2D array is like a table or grid. ### Declaring 2D Arrays ```java // Create a 3x3 grid int[][] grid = new int[3][3]; // Or with values int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; ``` ### Accessing 2D Array Elements ```java int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println(matrix[0][0]); // 1 (row 0, col 0) System.out.println(matrix[1][2]); // 6 (row 1, col 2) System.out.println(matrix[2][1]); // 8 (row 2, col 1) ``` ### Looping Through 2D Arrays ```java int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Nested for loop for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[row].length; col++) { System.out.print(matrix[row][col] + " "); } System.out.println(); } // Output: // 1 2 3 // 4 5 6 // 7 8 9 ``` --- ## Common Array Operations ### Find Maximum Value ```java int[] numbers = {5, 12, 3, 8, 99, 1}; int max = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } } System.out.println("Max: " + max); // 99 ``` ### Find Minimum Value ```java int[] numbers = {5, 12, 3, 8, 99, 1}; int min = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] < min) { min = numbers[i]; } } System.out.println("Min: " + min); // 1 ``` ### Calculate Sum and Average ```java int[] numbers = {5, 10, 15, 20, 25}; int sum = 0; for (int num : numbers) { sum += num; } double average = (double) sum / numbers.length; System.out.println("Sum: " + sum); // 75 System.out.println("Average: " + average); // 15.0 ``` ### Search for an Element ```java String[] names = {"Alice", "Bob", "Charlie", "Diana"}; String searchName = "Charlie"; boolean found = false; for (String name : names) { if (name.equals(searchName)) { found = true; break; } } System.out.println("Found: " + found); // true ``` ### Reverse an Array ```java int[] original = {1, 2, 3, 4, 5}; int[] reversed = new int[original.length]; for (int i = 0; i < original.length; i++) { reversed[i] = original[original.length - 1 - i]; } System.out.println(Arrays.toString(reversed)); // [5, 4, 3, 2, 1] ``` --- ## Practice Exercises ### Exercise 1: Simple Method Create a method that prints "Hello, World!" ```java public class Exercise1 { public static void sayHello() { System.out.println("Hello, World!"); } public static void main(String[] args) { sayHello(); } } ``` ### Exercise 2: Method with Parameters Create a method that takes a name and prints a greeting. ```java public class Exercise2 { public static void greet(String name) { System.out.println("Hello, " + name + "!"); } public static void main(String[] args) { greet("Alice"); greet("Bob"); } } ``` ### Exercise 3: Method with Return Create a method that returns the square of a number. ```java public class Exercise3 { public static int square(int num) { return num * num; } public static void main(String[] args) { System.out.println(square(5)); // 25 System.out.println(square(10)); // 100 } } ``` ### Exercise 4: Array Basics Create an array of your favorite fruits and print each one. ```java public class Exercise4 { public static void main(String[] args) { String[] fruits = {"Apple", "Banana", "Cherry", "Date"}; for (String fruit : fruits) { System.out.println(fruit); } } } ``` ### Exercise 5: Array Average Calculate the average of numbers in an array. ```java public class Exercise5 { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; int sum = 0; for (int num : numbers) { sum += num; } double average = (double) sum / numbers.length; System.out.println("Average: " + average); // 30.0 } } ``` ### Exercise 6: Find Maximum Find the largest number in an array. ```java public class Exercise6 { public static void main(String[] args) { int[] numbers = {5, 12, 3, 8, 99, 1}; int max = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } } System.out.println("Maximum: " + max); // 99 } } ``` ### Exercise 7: Method Overloading Create overloaded methods for adding numbers. ```java public class Exercise7 { public static int add(int a, int b) { return a + b; } public static double add(double a, double b) { return a + b; } public static int add(int a, int b, int c) { return a + b + c; } public static void main(String[] args) { System.out.println(add(5, 3)); // 8 System.out.println(add(5.5, 3.2)); // 8.7 System.out.println(add(1, 2, 3)); // 6 } } ``` ### Exercise 8: 2D Array Create and print a 3x3 multiplication table. ```java public class Exercise8 { public static void main(String[] args) { int[][] table = new int[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { table[i][j] = (i + 1) * (j + 1); System.out.printf("%2d ", table[i][j]); } System.out.println(); } } } ``` --- ## Summary In this guide, you learned: - ✅ What methods are and why to use them - ✅ How to create methods with parameters - ✅ How to return values from methods - ✅ What method overloading is - ✅ What arrays are and how to use them - ✅ How to work with array elements - ✅ Common array operations (sort, search, etc.) - ✅ How to use two-dimensional arrays **Congratulations!** You've completed the Java Beginner series! **Next Steps:** Move on to [Java Intermediate Guide](./Java-Intermediate-Guide.md) to learn about Object-Oriented Programming and more advanced concepts! --- *Excellent work! You're now ready for intermediate Java! 🚀*