☕ Java Functions — Beginner Guide

Never coded before? No problem. Each card below explains one Java concept in plain English, shows you real code, and lets you type your own input and see what happens live. Just read, play, and learn at your own pace!

📄
Variable

A named box that holds a value. int age = 5;

📌
Method / Function

A reusable block of code you can call by name.

📄
String

Text in Java. Always in double quotes: "Hello"

🔨
boolean

Only two values: true or false. Yes or no.

🔍
Strings

String.length()

Counts how many characters are in a piece of text — like counting letters on a name tag. Spaces, punctuation, and numbers all count too! Useful for checking if a user actually typed something, or for enforcing a password length limit.

String s = "Hello!";          // declare a variable called s
int n = s.length();       // n = 6  (H-e-l-l-o-!)
Try it — each box is one character
Strings

toUpperCase() / toLowerCase()

Converts all letters to CAPITALS or all to lowercase — like holding Shift on every letter at once. Useful when you want to compare two words without caring about capitalization (e.g. "hello" and "HELLO" should both pass a search). The original string is never changed; you get a brand-new one back.

"Hello".toUpperCase() // → "HELLO"
"Hello".toLowerCase() // → "hello"
Try it
Strings

String.substring()

Cuts out a piece of text between two positions — like using scissors on a sentence. The start position IS included; the end position is NOT. So substring(0, 3) gives you positions 0, 1, and 2. The purple boxes below show exactly which characters you'll get.

"Java is fun".substring(0, 4)  // → "Java"
"Java is fun".substring(5)     // → "is fun"
Try it — purple = selected range
Strings

contains() / startsWith() / endsWith()

Asks a yes/no question about your text — does it contain this word? Does it start or end with this? The answer is always true or false. Great for things like: "does this email contain an @?" or "does the filename end in .jpg?". Green boxes show where the match was found.

"Hello Java".contains("Java")     // true
"Hello Java".startsWith("Hello") // true
Try it — green = match found
Strings

replace()

Finds every copy of a word (or character) and swaps it out — just like Find & Replace in Word. It replaces ALL matches at once, not just the first one. Great for cleaning up text, removing unwanted characters, or reformatting output. The original string is never changed; you always get a new one.

"I love cats".replace("cats", "dogs")
// → "I love dogs"
Try it — orange = will be replaced
Strings

String.split()

Chops a string into pieces every time it finds a certain character (like a comma or space). The result is an array of separate strings. Think of it like cutting a CSV row — "apple,banana,cherry" split by "," gives you three separate words. Very common when reading data files.

"a,b,c".split(",") // → ["a","b","c"]
Try it — change the delimiter
Strings

trim() & strip()

Cleans up invisible spaces at the start and end of text — the kind users accidentally leave when typing in a form. Spaces in the middle are left alone. Always trim user input before checking or saving it, or you'll get bugs that are very hard to spot! Dim boxes = stripped spaces.

"  Hello!  ".strip() // → "Hello!"
Try it — add spaces around the text
Strings

equals() vs ==

The correct way to check if two strings have the same text. Never use == for strings== checks if two variables point to the exact same place in memory, which can give a wrong false even when the words look identical. .equals() compares the actual letters.

a.equals(b)           // content equal?
a.equalsIgnoreCase(b) // case-insensitive?
a == b               // same object? (usually false)
Try it — compare two strings
Arrays

Declaring & Accessing

An array is like a row of numbered boxes — each box holds one value. The numbering always starts at 0, not 1. So the first item is at index 0, the second at index 1, and so on. ⚠️ Asking for a box that doesn't exist (e.g. index 10 in a 5-item array) causes a crash called ArrayIndexOutOfBoundsException.

//  index:    0  1  2  3   ← always starts at 0!
int[] nums = { 5, 3, 8, 1 };
nums[0];      // → 5  (first item)
nums[2];      // → 8  (third item)
nums.length; // → 4  (total boxes)
Try it — change the index
Arrays

Arrays.sort()

Puts the elements in order from smallest to largest — directly inside the same array (no copy made). Works on numbers and on text (alphabetical order). ⚠️ The original order is gone after sorting — if you need to keep it, copy the array first. Click Sort below to watch the boxes rearrange!

import java.util.Arrays;
int[] a = { 5, 1, 4, 2 };
Arrays.sort(a); // a is now [1, 2, 4, 5]
// ⚠️ a's original order is gone forever!
Try it — watch the boxes reorder
Arrays

Arrays.copyOfRange()

Makes a brand-new array that contains just a piece of an existing one — the original array is NOT changed. Think of it like photocopying only a specific page range. Blue boxes show which part of the original is selected; green boxes show the fresh copy you get.

int[] orig = { 1,2,3,4,5 };
Arrays.copyOfRange(orig, 1, 4);
// → [2, 3, 4]
Try it — blue = source range, green = copy
Arrays

Arrays.fill()

Fills every slot (or just a section) of an array with the same value — like painting a row of boxes one color. Great for quickly resetting an array or pre-loading it with a default value like 0 or -1 before you fill it with real data. Orange boxes show which slots get filled.

int[] a = new int[6];
Arrays.fill(a, 7); // [7,7,7,7,7,7]
Try it — orange = filled
Loops

for loop

The most common loop — runs a block of code a set number of times. You pick the start number, the end number, and how much to count by each step. Think of i as a counter that keeps going until it hits the limit. Hit ▶ Next below to step through it one round at a time!

// i starts at 0, counts up by 1 while i < 5
for (int i = 0; i < 5; i++) {
    System.out.println(i); // prints 0, 1, 2, 3, 4
}
Step through it
i = 
Press Next to start
Loops

Enhanced for-each

A simpler loop for visiting every item in a list or array — one by one. You don't need an index counter; Java handles that automatically. Use this when you want to do something with each item and don't need to know its position number. The blue box is the item being visited right now.

String[] fruits = {"apple", "banana", "cherry"};

// "for each fruit in the fruits array"
for (String fruit : fruits) {
    System.out.println(fruit); // prints each one
}
Step through it
item = 
Loops

break & continue

break is an emergency exit — the moment Java hits it, the loop ends immediately. continue is a skip — it jumps straight to the next round without running the rest of the loop body for that step. Watch some numbers get skipped (struck through) and one stop the whole loop dead.

for (int i = 0; i < 10; i++) {
    if (i == 3) continue; // skip 3, jump to i=4
    if (i == 7) break;    // stop everything at 7
    System.out.println(i);  // prints 0,1,2,4,5,6
}
Try it — change skip/stop values
Loops

while loop

A loop that keeps going as long as a condition is true — like saying "keep playing rounds while lives > 0". Great when you don't know in advance how many times to loop. ⚠️ If the condition is always true, the loop runs forever (infinite loop)! Step through below to see the condition checked each round.

int lives = 3;

// keep going as long as this is true
while (lives > 0) {
    lives--;  // remember to change the variable!
}             // infinite loop if you forget this
Step through it
n = 
Math

Math.abs() / max() / min()

Three everyday helpers: abs() removes the sign (makes any negative number positive — think absolute value). max() picks whichever of two numbers is bigger. min() picks the smaller one. These show up constantly in score calculations and range checks.

Math.abs(-42)       // 42
Math.max(10, 25)    // 25
Math.min(10, 25)    // 10
Try it — change a and b
Math

Math.pow() & Math.sqrt()

pow(base, exp) raises a number to a power — like squaring it or cubing it. sqrt(n) finds the square root. Both always give back a decimal (double) even if the result is a whole number. Fun fact: pow(2, 10) = 1024 — that's how many bytes are in a kilobyte!

Math.pow(2, 10)   // 1024.0
Math.sqrt(144)   // 12.0
Try it
Math

Math.random() — dice

Gives you a random decimal between 0.0 and 1.0 (never reaches 1.0 exactly) every time you call it. To get a random whole number — like rolling a dice — multiply by how many sides and round down. Roll the dice below to see the formula in action each time!

int dice = (int)(Math.random() * 6) + 1;
Roll it!
Math

floor() / ceil() / round()

floor() always rounds down to the nearest whole number (even for negatives). ceil() always rounds up. round() rounds to whichever whole number is closest (standard rounding). Drag the slider to move the dot on the number line and watch all three results change at once!

Math.floor(3.7) // 3.0 ← rounds down
Math.ceil(3.2)  // 4.0 ← rounds up
Math.round(3.5) // 4   ← standard
Try it — drag the slider
OOP

Classes & Objects

A class is like a cookie cutter — it defines the shape and contents. An object is an actual cookie made from that cutter. You create objects with new ClassName(). Each object gets its own copy of the data (fields), and you can tell it to do things (methods). Fill in the fields below and click bark()!

// 1. Define the class (the blueprint)
class Dog {
    String name;           // field: each Dog has a name
    int    age;            // field: and an age
    void bark() {          // method: something the Dog can DO
        System.out.println("Woof!");
    }
}

// 2. Create an object from the blueprint
Dog myDog = new Dog();
myDog.name = "Rex";
myDog.bark();              // calls the method → Woof!
Try it — instantiate a Dog object
OOP

Inheritance

Inheritance lets one class borrow all the code from another class, then customize parts of it. A Dog can inherit from Animal and override speak() to say "Woof!" instead of a generic sound. The same method name does completely different things depending on which class you're calling it on — click each animal to see this in action!

class Animal {
    void speak() { System.out.println("..."); }
}

// Dog inherits from Animal, then overrides speak()
class Dog extends Animal {
    @Override              // this replaces the parent version
    void speak() { System.out.println("Woof!"); }
}
Try it — click an animal to call speak()
Animal
▼ extends
OOP

Interfaces

An interface is a promise — it says "any class that signs up MUST provide these methods". Think of it like a job description: the interface lists the duties; the class is the employee who actually does them. A class can "sign up" for multiple interfaces at once (unlike inheritance, which allows only one parent).

interface Drawable  { void draw(); }
interface Resizable { void resize(double f); }
class Circle implements Drawable, Resizable {…}
Try it
«interface» Drawable
«interface» Resizable
▼ implements both
Circle
Collections

ArrayList

ArrayList is like a regular array but it can grow and shrink automatically — you never need to decide the size upfront. Add items with add(), remove with remove(), and check how many items there are with size(). It's the most commonly used collection in Java by far!

// <String> means this list holds Strings
ArrayList<String> names = new ArrayList<>();
names.add("Alice");    // add to the end
names.add("Bob");
names.size();          // → 2
names.remove("Alice"); // now size() → 1
Try it — add items, click × to remove
Collections

HashMap

HashMap stores pairs of keys and values — like a phone book where the name is the key and the number is the value. You look up values by their key (not by position). ⚠️ If you add the same key twice, the new value replaces the old one. Looking up a key that doesn't exist returns null.

HashMap<String,Integer> map = new HashMap<>();
map.put("Alice", 95);
map.get("Alice"); // 95
Try it — put & get
Collections

HashSet — unique only

HashSet is a collection that refuses duplicates — every item must be unique. If you try to add something that's already there, it's silently ignored (no crash, no error). Perfect for tracking things like "which users have already voted" or "which words appear in this document". Try adding a duplicate below!

HashSet<String> set = new HashSet<>();
set.add("red");
set.add("red"); // ignored!
Try it — add a duplicate to see rejection
Collections

Collections.sort() & reverse()

The Collections class has ready-made tools that work on any list — you don't have to write these yourself! sort() puts items in order, reverse() flips the whole list around, shuffle() puts them in a random order. Hit Shuffle first, then Sort to watch the boxes snap back into place!

Collections.sort(list);
Collections.reverse(list);
Try it — Shuffle then Sort
No functions match your search.