-
-
Notifications
You must be signed in to change notification settings - Fork 2
Java Beginner Part3
- Introduction
- Methods - Introduction
- Method Parameters and Return Values
- Method Overloading
- Arrays - Introduction
- Working with Arrays
- Array Methods and Utilities
- Two-Dimensional Arrays
- Common Array Operations
- Practice Exercises
In this guide, you'll learn two essential concepts:
- Methods - Reusable blocks of code that perform specific tasks
- Arrays - Collections that store multiple values in a single variable
These are fundamental building blocks that every Java programmer needs to master!
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.
- Reusability - Write once, use many times
- Organization - Break code into logical chunks
- Easier Testing - Test each method separately
- Readability - Cleaner, easier to understand code
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
}
}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 |
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());
}
}Parameters are inputs that methods can accept:
// 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);
}Use return to send a value back:
// 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};
}-
returnexits the method immediately - Methods with
voiddon't return anything - Methods with a return type MUST return a value
public static String checkAge(int age) {
if (age >= 18) {
return "Adult";
} else {
return "Minor";
}
// No need for else after return
}In Java, primitives are passed by value (a copy is made):
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 allows multiple methods with the same name but different parameters.
Different ways to do similar things:
// 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
}// 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); // booleanArrays store multiple values in a single variable. Instead of having 10 separate variables, you can have one array with 10 elements!
- Store related data together
- Easy to process with loops
- Efficient way to manage collections
// 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};// 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};Arrays start at index 0:
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]); // Bananaint[] 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]); // 100int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers.length); // 5int[] 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);
}Java provides built-in ways to work with arrays:
Convert an array to a readable string:
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
System.out.println(Arrays.toString(numbers));
// [5, 2, 8, 1, 9]Sort array elements:
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]Fill an array with a value:
import java.util.Arrays;
int[] numbers = new int[5];
Arrays.fill(numbers, 100);
System.out.println(Arrays.toString(numbers));
// [100, 100, 100, 100, 100]Copy an array:
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]Arrays can have multiple dimensions! A 2D array is like a table or grid.
// Create a 3x3 grid
int[][] grid = new int[3][3];
// Or with values
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};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)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 9int[] 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); // 99int[] 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); // 1int[] 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.0String[] 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); // trueint[] 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]Create a method that prints "Hello, World!"
public class Exercise1 {
public static void sayHello() {
System.out.println("Hello, World!");
}
public static void main(String[] args) {
sayHello();
}
}Create a method that takes a name and prints a greeting.
public class Exercise2 {
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
greet("Alice");
greet("Bob");
}
}Create a method that returns the square of a number.
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
}
}Create an array of your favorite fruits and print each one.
public class Exercise4 {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}Calculate the average of numbers in an array.
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
}
}Find the largest number in an array.
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
}
}Create overloaded methods for adding numbers.
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
}
}Create and print a 3x3 multiplication table.
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();
}
}
}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 to learn about Object-Oriented Programming and more advanced concepts!
Excellent work! You're now ready for intermediate Java! 🚀