Method Overloading
With method overloading, multiple methods can have the same name with different
parameters:
Example
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Consider the following example, which has two methods that add numbers of different
type:
Example
static int plusMethodInt(int x, int y) {
return x + y;
}
static double plusMethodDouble(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
[Link]("int: " + myNum1);
[Link]("double: " + myNum2);
}
Instead of defining two methods that should do the same thing, it is better to overload
one.
In the example below, we overload the plusMethod method to work for both int and
double:
Example
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
[Link]("int: " + myNum1);
[Link]("double: " + myNum2);
}
Note: Multiple methods can have the same name as long as the number and/or type of
parameters are different.
Java Recursion
Recursion is the technique of making a function call itself. This technique provides a
way to break complicated problems down into simpler problems which are easier to
solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is
to experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers
together by breaking it down into the simple task of adding two numbers:
Example
Use recursion to add all numbers from 1 to 10.
public class Main {
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
public static void main(String[] args) {
int result = sum(10);
[Link](result);
}
}
Example Explained
When the sum() method is called, it adds parameter k to the sum of all numbers
smaller than k and returns the result. When k becomes 0, the method just returns 0.
When running, the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the method does not call itself when k is 0, the program stops there and returns
the result.
Halting Condition
Just as loops can run into the problem of infinite looping, recursive methods can run into
the problem of infinite recursion. Infinite recursion is when the method never stops
calling itself. Every recursive method should have a halting condition, which is the
condition where the method stops calling itself. In the previous example, the halting
condition is when the parameter k becomes 0.
It is helpful to see a variety of different examples to better understand the concept. In
this example, the method adds a range of numbers between a start and an end. The
halting condition for this recursive method is when end is not greater than start:
Example
Use recursion to add all numbers from 5 to 10 (5+6+7+8+9+10):
public class Main {
public static int sum(int start, int end) {
if (end > start) {
return end + sum(start, end - 1);
} else {
return end;
}
}
public static void main(String[] args) {
int result = sum(5, 10);
[Link](result);
}
}
Be careful with recursion: it's easy to accidentally write a method that never stops or uses too
much memory. But when written correctly, recursion can be both efficient and elegant.
Countdown with Recursion
This example demonstrates how to use recursion to create a countdown function:
Example
public class Main {
static void countdown(int n) {
if (n > 0) {
[Link](n + " ");
countdown(n - 1);
}
}
public static void main(String[] args) {
countdown(5);
}
}
The method calls itself with n - 1 until n becomes 0.
Calculate Factorial with Recursion
This example uses a recursive method to calculate the factorial of 5:
public class Main {
static int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
public static void main(String[] args) {
[Link]("Factorial of 5 is " + factorial(5));
}
}
Factorial means multiplying a number by every number below it, down to 1. For example, the
factorial of 5 is: 5 * 4 * 3 * 2 * 1 = 120. By definition, 0! is also 1.
Java Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as
functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method,
followed by parentheses (). Java provides some pre-defined methods, such as
[Link](), but you can also create your own methods to perform
certain actions:
Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}
Example Explained
● myMethod() is the name of the method
● static means that the method belongs to the Main class and not an object of
the Main class. You will learn more about objects and how to access methods
through objects later in this tutorial.
● void means that this method does not have a return value. You will learn more
about return values later in this chapter
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;
In the following example, myMethod() is used to print a text (the action), when it is
called:
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
// Outputs "I just got executed!"
A method can also be called multiple times:
Example
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}
}
// I just got executed!
// I just got executed!
// I just got executed!
In the next chapter, Method Parameters, you will learn how to pass data (parameters) into a
method.
Parameters and Arguments
Information can be passed to methods as a parameter. Parameters act as variables
inside the method.
Parameters are specified after the method name, inside the parentheses. You can add
as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as parameter.
When the method is called, we pass along a first name, which is used inside the method
to print the full name:
Example
public class Main {
static void myMethod(String fname) {
[Link](fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
When a parameter is passed to the method, it is called an argument. So, from the example
above: fname is a parameter, while Liam, Jenny and Anja are arguments.
Multiple Parameters
You can have as many parameters as you like:
Example
public class Main {
static void myMethod(String fname, int age) {
[Link](fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
// Liam is 5
// Jenny is 8
// Anja is 31
Note that when you are working with multiple parameters, the method call must have the same
number of arguments as there are parameters, and the arguments must be passed in the same
order.
A Method with If...Else
It is common to use if...else statements inside methods:
Example
public class Main {
// Create a checkAge() method with an integer variable called
age
static void checkAge(int age) {
// If age is less than 18, print "access denied"
if (age < 18) {
[Link]("Access denied - You are not old
enough!");
// If age is greater than, or equal to, 18, print "access
granted"
} else {
[Link]("Access granted - You are old
enough!");
}
public static void main(String[] args) {
checkAge(20); // Call the checkAge method and pass along an
age of 20
}
}
// Outputs "Access granted - You are old enough!"
Return Values
In the previous page, we used the void keyword in all examples (like static void
myMethod(int x)), which indicates that the method should not return a value.
If you want the method to return a value, you can use a primitive data type (such as
int, char, etc.) instead of void, and use the return keyword inside the method:
Example
public class Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
[Link](myMethod(3));
}
}
// Outputs 8 (5 + 3)
This example returns the sum of a method's two parameters:
Example
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
[Link](myMethod(5, 3));
}
}
// Outputs 8 (5 + 3)
You can also store the result in a variable (recommended, as it is easier to read and
maintain):
Example
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
int z = myMethod(5, 3);
[Link](z);
}
}
// Outputs 8 (5 + 3)
Practical Example
Here is a simple and fun "game example" using a method that returns a value, to show
the double of the numbers 1 through 5 (using a for loop):
Example
public class Main {
// Method that doubles the number
static int doubleGame(int x) {
return x * 2;
}
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
[Link]("Double of " + i + " is " +
doubleGame(i));
}
}
}
Java Errors
Even experienced Java developers make mistakes. The key is learning how to spot and
fix them!
These pages cover common errors and helpful debugging tips to help you understand
what's going wrong and how to fix it.
Types of Errors in Java
Error Type Description
Compile-Time Error Detected by the compiler. Prevents code from running.
Runtime Error Occurs while the program is running. Often causes crashes.
Logical Error Code runs but gives incorrect results. Hardest to find.
Common Compile-Time Errors
Compile-time errors occur when the program cannot compile due to syntax or type
issues.
Here are some examples:
1) Missing Semicolon
Example
int x = 5
[Link](x);
Result:
error: ';' expected
Tip: Java requires a semicolon at the end of every statement (int x = 5;).
2) Undeclared Variables
Example
[Link](myVar);
Result:
cannot find symbol
symbol: variable myVar
Tip: You must declare a variable before using it (int myVar = 50;).
3) Mismatched Types
Example
int x = "Hello";
Result:
incompatible types: String cannot be converted to int
Tip: Make sure the value matches the variable type (String x = "Hello";).
Common Runtime Errors
Runtime errors occur when the program compiles but crashes or behaves unexpectedly.
Here are some examples:
1) Division by Zero
Example
int x = 10;
int y = 0;
int result = x / y;
[Link](result);
Result:
Exception in thread "main" [Link]: / by zero
2) Array Index Out of Bounds
Example
int[] numbers = {1, 2, 3};
[Link](numbers[8]);
Result:
Exception in thread "main" [Link]:
Index 8 out of bounds for length 3
Logical Errors
Logical errors happen when the code runs, but the result is not what you thought:
Example:
int x = 10;
int y = 2;
int sum = x - y;
[Link]("x + y = " + sum);
Result:
x + y = 8
Expected Result: 12
Logical Error: The code mistakenly subtracts instead of adds.
Tip: Test your program with different inputs to catch logic flaws (try using x + y instead). This is
part of debugging, which you will learn more about in the next chapter.
Good Habits to Avoid Errors
● Use meaningful variable names
● Read the error message carefully. What line does it mention?
● Check for missing semicolons or braces
● Look for typos in variable or method names
Java Debugging
After learning about common errors, the next step is understanding how to debug your
Java code - that is, how to find and fix those errors effectively.
This page introduces simple debugging techniques that are useful for beginners and
helpful even for experienced developers.
What is Debugging?
Debugging is the process of identifying and fixing errors or bugs in your code.
It often involves:
● Reading error messages
● Tracing variable values step by step
● Testing small pieces of code independently
Tip: Debugging is a skill that improves with practice. The more you debug, the better you get at
spotting problems quickly.
Print Statements for Debugging
The most basic (and often most effective) way to debug Java code is to use
[Link]() to print values and check the flow of the program.
In this example, the first line "Before division" will print, but the second line is
never reached because the program crashes due to division by zero:
Example
int x = 10;
int y = 0;
[Link]("Before division"); // Debug output
int result = x / y; // Crashes
[Link]("Result: " + result); // Never runs
Result:
Before division
Exception in thread "main" [Link]: / by zero
Tip: Add print statements before and after key lines of code to find out where things go wrong.
Check Variable Values
If something unexpected happens, print out the values of your variables:
Example
int age = 17;
[Link]("Age: " + age);
if (age >= 18) {
[Link]("Access granted");
} else {
[Link]("Access denied");
}
Tip: This is a good way to test whether a condition is working correctly - try changing age to 18
or 19 and observe the output!
Debugging with IDEs
Modern IDEs like IntelliJ IDEA, Eclipse, and NetBeans come with built-in debugging
tools.
● Set breakpoints to pause the program at specific lines
● Step through code line by line
● Inspect variable values in real time
Tip: Use your IDE's debugger to find errors faster - it's more powerful than print statements
alone!
Debugging Checklist
● Read the full error message, it often tells you exactly what's wrong
● Check if all variables are initialized before use
● Print variable values to trace the problem
● Watch for off-by-one errors in loops and arrays
● Comment out sections of code to find bugs
In the next chapter, you will learn about how to handle errors gracefully in your
programs with Java Exceptions.
Java Exceptions
As mentioned in the Errors chapter, different types of errors can occur while running a
program - such as coding mistakes, invalid input, or unexpected situations.
When an error occurs, Java will normally stop and generate an error message. The
technical term for this is: Java will throw an exception (throw an error).
Exception Handling (try and catch)
Exception handling lets you catch and handle errors during runtime - so your program
doesn't crash.
It uses different keywords:
The try statement allows you to define a block of code to be tested for errors while it is
being executed.
The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
The try and catch keywords come in pairs:
Syntax
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Consider the following example:
This will generate an error, because myNumbers[10] does not exist.
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]); // error!
}
}
The output will be something like this:
Exception in thread "main" [Link]:
10
at [Link]([Link])
Note: ArrayIndexOutOfBoundsException occurs when you try to access an index
number that does not exist.
If an error occurs, we can use try...catch to catch the error and execute some code
to handle it:
Example
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
}
}
}
The output will be:
Something went wrong.
Finally
The finally statement lets you execute code, after try...catch, regardless of the
result:
Example
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
} finally {
[Link]("The 'try catch' is finished.");
}
}
}
The output will be:
Something went wrong.
The 'try catch' is finished.
The throw keyword
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many
exception types available in Java: ArithmeticException,
FileNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc:
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be
at least 18 years old.");
}
else {
[Link]("Access granted - You are old
enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
The output will be:
Exception in thread "main" [Link]: Access
denied - You must be at least 18 years old.
at [Link]([Link])
at [Link]([Link])
If age was 20, you would not get an exception:
Example
checkAge(20);
The output will be:
Access granted - You are old enough!
Errors and Exception Types
The table below shows some of the most common errors and exceptions in Java, with a
short description of each:
Error/Exception Description
ArithmeticError Occurs when a numeric calculation goes wrong
ArrayIndexOutOfBoundsExc Occurs when trying to access an index number that
eption does not exist in an array
ClassNotFoundException Occurs when trying to access a class that does not
exist
FileNotFoundException Occurs when a file cannot be accessed
InputMismatchException Occurs when entering wrong input (e.g. text in a
numerical input)
IOException Occurs when an input or output operation fails
NullPointerException Occurs when trying to access an object referece that
is null
NumberFormatException Occurs when it is not possible to convert a specified
string to a numeric type
StringIndexOutOfBoundsExc Occurs when trying to access a character in a String
eption that does not exist
Tip: For a list of all errors and exception types, go to our Java Errors and Exception
Types Reference.
Multiple Exceptions
Sometimes, different errors (exceptions) can happen in the same try block. You can
handle them with multiple catch blocks.
One try, Many catch
You can add more than one catch block, and Java will run the first one that matches
the thrown exception type:
Example
public class Main {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
[Link](numbers[10]); //
ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index does not exist.");
}
catch (ArithmeticException e) {
[Link]("Cannot divide by zero.");
}
catch (Exception e) {
[Link]("Something else went wrong.");
}
}
}
Result:
Array index does not exist.
Explanation: Only the first exception (ArrayIndexOutOfBoundsException) is
thrown, so only the first matching catch runs.
Order Matters
You should always put more specific exceptions first, and general ones later. Otherwise,
the general catch will grab the error and the specific ones will never run:
Example (bad order)
try {
int result = 10 / 0;
}
catch (Exception e) {
[Link]("General error.");
}
catch (ArithmeticException e) {
// This will never be reached
[Link]("Divide by zero.");
}
Tip: Always put Exception (the general one) at the end.
Multi-Catch
Since Java 7, you can catch multiple exceptions in one catch block using the | symbol.
This is useful when different exceptions should be handled in the same way, so you
don't have to repeat code:
Example
try {
int result = 10 / 0;
int[] numbers = {1, 2, 3};
[Link](numbers[10]);
}
catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
[Link]("Math error or array error occurred.");
}
Java Arrays Class
The Java Arrays class (found in [Link]), has methods that allow you to
manipulate arrays.
Arrays Methods
A list of popular methods of the Arrays Class can be found in the table below:
Method Description
compare() Compares two arrays
copyOf() Creates a copy of an array with a new length
deepEquals() Compares two multidimensional arrays to check whether
they are deeply equal to each other
equals() Checks if two arrays are equal
fill() Fills an array with a specified value
mismatch() Returns the index position of the first mismatch/conflict
between two arrays
sort() Sorts an array in ascending order
Properties
Property Description
length Returns the length of an array
The length property is a built-in Java property, and does not belong to the Arrays
class.
Java [Link]() Method
Example
Compare two arrays:
String[] cars = {"Volvo", "BMW", "Tesla"};
String[] cars2 = {"Volvo", "BMW", "Tesla"};
[Link]([Link](cars, cars2));
Definition and Usage
The compare() method compares two arrays lexicographically.
Syntax
[Link](array1, array2)
Parameter Values
Parameter Description
array1 Required. The array to compare with array2
array2 Required. The array to be compared with array1
Technical Details
Returns: Returns 0 if the arrays are equal.
Returns a negative integer if the array1 is less than array2
lexicographically
Returns a positive integer if array1 is greater than array2
lexicographically.
Java [Link]() Method
Example
Find out if two arrays are equal:
String[] cars = {"Volvo", "BMW", "Tesla"};
String[] cars2 = {"Volvo", "BMW", "Tesla"};
[Link]([Link](cars, cars2));
Definition and Usage
The equals() method checks whether two arrays are equal.
Note: Two arrays are consided equal if they share the same elements in the same
order.
Syntax
[Link](array1, array2)
Parameter Values
Parameter Description
array1 Required. The array to compare with array2
array2 Required. The array to be compared with array1
Technical Details
Returns: Returns true if the arrays are equal.
Returns false if the arrays are not equal.
Java [Link]() Method
Example
Sort an array of strings alphabetically:
String[] cars = {"Volvo", "BMW", "Tesla", "Ford", "Fiat",
"Mazda", "Audi"};
[Link](cars);
Definition and Usage
The sort() method sorts an array in ascending order.
This method sorts arrays of strings alphabetically, and arrays of integers numerically.
Syntax
[Link](array)
[Link](array, start, end)
Parameter Values
Parameter Description
array Required. The array to be sorted
start Optional. The index position of the first element (inclusive) to be
sorted
end Optional. The index position of the last element (exclusive) to be
sorted
Technical Details
Returns: No return value
Java version: 1.2 ([Link])
Example
Sort an integer array numerically:
int[] myNum = {50, 10, 25, 1, 17, 99, 33};
[Link](myNum);
Example
Sort an integer array numerically, but only sort from index 1 to 3:
int[] myNum = {50, 10, 25, 1, 17, 99, 33};
// This will only sort the integers 10, 25, 1 and 17 from the
myNum array
[Link](myNum, 1, 4);
Java [Link]() Method
Example
Fill all the elements in an array with a "Kiwi" value:
String[] fruits = {"Banana", "Orange", "Apple", "Mango"};
[Link](fruits, "Kiwi");
Definition and Usage
The fill() method fills an array with a specified value.
Note: The value must be of the same data type as the array.
Tip: Start and end position can be specified. If not, all elements will be filled.
Syntax
[Link](array, value)
[Link](array, start, end, value)
Parameter Values
Parameter Description
array Required. The array to be filled
start Optional. The index position of the first element (inclusive) to be
filled
end Optional. The index position of the last element (exclusive) to be
filled
value Required. The value to fill in the array
Technical Details
Returns: No return value
Java version: 1.2 ([Link])
More Examples
Example
Fill the last two elements:
String[] fruits = {"Banana", "Orange", "Apple", "Mango"};
[Link](fruits, 2, 4, "Kiwi");
Java Array length Property
Example
Find out how many elements an array has:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
[Link]([Link]);
Definition and Usage
The length property returns the length of an array.
This is a built-in Java property, and does not belong to the Java Arrays Class.
Note: The length property must not be mistaken with the length() method that is
used for Strings.
Syntax
[Link]