Examples

Java examples

Understand object oriented programs and the JVM.

46 examples

Java Basics

Start with a class and main method.

Java

Java conditions, arrays, and loops

Count values that satisfy a boundary condition.

Java

Java methods and exception handling

Separate conversion errors from valid numeric values.

Java

Java recursion and bounded factorial

Use a base case and validate the representable range.

Java

Java variables, types, and casting

Declare typed variables and understand integer division, overflow, and conversions.

Java

Java arrays and strings

Work with fixed-size arrays, common String methods, and the difference between == and equals.

Java

Java method overloading, varargs, and pass by value

Declare several methods with the same name and see what a method can and cannot change.

Java

Java constructors and encapsulation

Initialize private fields and validate changes through methods.

Java

Java inheritance and method overriding

Use a superclass reference to call subclass behavior.

Java

Java interfaces and composition

Depend on a contract and inject a collaborating object.

Java

Java abstract classes and enums

Define a shared base with an abstract method, and a fixed set of constants with fields.

Java

Java generics and bounded types

Write one class and one method that work for many types while the compiler checks them.

Java

Java equals, hashCode, and toString

Define when two objects are equal so that they work correctly in sets and maps.

Java

Java ArrayList and generics

Use a resizable, type-checked sequence.

Java

Java binary search and interval bounds

Implement logarithmic search on an ascending array.

Java

Java stacks and balanced brackets

Use a stack to check that brackets are properly nested.

Java

Java ArrayDeque as a queue

Choose queue operations with explicit empty-queue behavior.

Java

Java maps, sets, and duplicate counting

Track counts and distinct values with separate collection roles.

Java

Java singly linked lists

Build a list of nodes by hand, insert at the front and the back, and reverse it.

Java

Java binary search trees

Insert values into a tree that keeps smaller values on the left, and traverse it in sorted order.

Java

Java sorting: insertion sort, merge sort, and comparators

Implement two sorts by hand and sort objects with a Comparator.

Java

Java priority queues and heaps

Always remove the smallest (or largest) item, and find the k largest values.

Java

Java: counting operations to see growth rates

Count loop iterations instead of timing them to compare linear, quadratic, and logarithmic growth.

Java

Java: amortized cost of a growing array

Show that doubling a backing array makes append cost O(1) on average even though some appends copy everything.

Java

Java: a hash join and why it beats a nested loop

Join two collections by building a hash table on one side and probing it with the other.

Java

Java: an ordered index with TreeMap

Use a sorted map the way a database uses an ordered index to answer range and nearest-key queries.

Java

Java: simulating round-robin CPU scheduling

Rotate jobs through a ready queue with a fixed time slice and record when each one finishes.

Java

Java: mutual exclusion with synchronized

Protect a shared counter from lost updates when two threads increment it.

Java

Java: a TCP echo server on the loopback interface

Open a server socket on an ephemeral port and connect to it with a client socket in the same program.

Java

Java: IPv4 addresses, masks, and CIDR blocks

Compute the network address, broadcast address, and host count of a subnet with bitwise operations.

Java

Java: testing a method with a tiny test runner

Check normal cases, boundaries, and error cases, and report which ones pass.

Java

Java: strategy and observer with interfaces and lambdas

Swap behavior behind an interface and notify listeners without coupling the sender to them.

Java

Java: SHA-256 hashing for integrity

Compute a SHA-256 digest with MessageDigest and see that a tiny change produces a completely different value.

Java

Java: storing passwords with a salt and PBKDF2

Derive a password hash with a random salt and many iterations, then verify a login attempt.

Java

Java: splitting work across a thread pool

Divide a sum into chunks, run them on an ExecutorService, and combine the Future results.

Java

Java: parallel streams and CompletableFuture

Count items with a parallel stream and combine two asynchronous results.

Java

Java: breadth-first search for a shortest path

Search a grid with a queue to find the fewest moves from the start to the goal around walls.

Java

Java: game-tree search with minimax (negamax)

Search every move in a take-away game to find which positions are winning for the player to move.

Java

Java: propositional entailment by model checking

Enumerate every truth assignment to decide whether a knowledge base entails a query.

Java

Java: forward chaining with if-then rules

Repeatedly apply rules whose conditions are known until no new facts can be derived.

Java

Java: linear regression with gradient descent

Fit a straight line to data by repeatedly stepping the weights against the gradient of the squared error.

Java

Java: k-nearest-neighbors classification

Classify a point by letting its k closest training points vote.

Java

Java: training a perceptron to learn AND

Update the weights of a single neuron with the perceptron rule until it classifies all four inputs correctly.

Java

Java: a two-layer network that computes XOR

Combine two hidden neurons so that a network solves the problem a single perceptron cannot.

Java

Java: filtering an image with a convolution kernel

Slide a 3×3 averaging kernel over a small grayscale image to smooth it.

Java

Java: finding edges with the Sobel operator

Estimate the horizontal intensity change at each pixel and mark strong edges.

Java