Learn how to write Java code effectively with 10 best Java code examples, equally perfect for newbies and seasoned developers.
Whether you are starting your web development journey and wondering “how do I code with Java?” or an experienced developer looking for some practical Java code examples, this blog delivers all that you need. We are explaining 10 essential code examples that you can follow for your successful projects in 2025.
1. Hello World & Basic Syntax
We are starting with the classic beginner Java code example, ‘Hello World’. It may seem simple, but it helps in understanding all the key elements of language structure. In Java, the main method serves as the program’s entry point. In order to print output to the console, System.out.printIn function is used. With this step, developers will be able to understand the strict Syntax of Java.
Here’s the example:
java
public class HelloWorld {
public static void main ( String [ ] args ) {
System . out . println ( “ Hello , Java 2025!” );
}
} 2. Loops and Conditional Logic
With control flow, your program is enabled to make decisions and perform actions repeatedly. Through this example, we discover if/else statements to determine outcomes and assess conditions, no matter whether a number is even or odd. After that, you can introduce ‘for’ and ‘while’ loops to show repetition. The ‘for’ loop is important for scenarios where the number of iterations is known, and the ‘while’ loop is ideal for situations where repetition relies on dynamic conditions.
Moreover, for smooth programming, you can hire Java developers.
Here are some examples of Java code:
java
public class FlowExamples {
public static void main ( String [ ] args ) {
int x = 10;
if ( x % 2 == 0 ) {
System . out. println ( x + “is even” );
} else {
System . out . println ( x + “is odd” );
}
// Loop examples
for ( int i = 0 ; i < 5 ; i ++ ) {
System . out . println ( “ For loop iteration ” + i );
}
int j = 0;
while ( j < 5 ) {
System . out . println ( “ While loop iteration ” + j );
j++;
}
}
} 3. Object Oriented Programming
Object-oriented programming is the foundation of Java. That’s why it’s essential to understand inheritance, classes, and polymorphism. In this basic Java code example, we start by defining an Animal class and extending it to a Dog class. This example exhibits inheritance, where Dog inherits methods and properties from Animal:
java
class Animal {
String name;
Animal ( String name ) { this . name = name; }
void speak ( ) { System . out . println ( “ Some sound” ); }
}
class Dog extends Animal {
Dog ( String name ) { super ( name ); }
@ Override
void speak ( ) { System . out . println ( name + “ says : Woof!” ); }
}
public class OOPExample {
public static void main ( String [ ] args ) {
Animal a = new Dog ( “ Buddy ” );
a . speak ( ) ; // Outputs : Buddy says : Woof!
}
} 4. Generics and Collections
With the help of collections, developers can efficiently work with groups of data. In this type of Java code example, an ‘ArrayList’ is used to store strings and for mapping these strings to integers, ‘HashMap’ is utilized. By preventing runtime type errors, the use of generics enables type safety.
Collections and generics example is given here:
java
import java . Util.*;
public class CollectionsExample {
public static void main ( String [ ] args ) {
List < String > fruits = new ArrayList < > ( );
fruits . add ( “ Apple ” );
fruits . Add ( “ Banana ” );
fruits . add ( “ Cherry ” );
for ( String fruit : fruits ) {
System . out . println ( fruit );
}
Map < String, Integer > counts = new HashMap < > ( );
counts . put ( “ Apple ” ,3 );
counts .put ( “ Banana ”, 5 );
counts . forEach (( k , v ) -> System . out . println ( k + “ : “ + v ));
}
} 5. File I\O
It is a must-have skill for Java developers to know how to read from and write to files. ‘BufferedWriter’ is used in this example for writing a string to a text file and a ‘BufferedReader’ for reading the content back:
java
import java . io. *;
public class FileIOExample {
public static void main ( String [ ] args ) {
String filePath = “ example . txt ”;
try ( BufferedWriter writer = new BufferedWriter ( new FileWriter ( filePath ))) {
writer . write ( “ Hello , file world! ” );
} catch ( IOException e ) {
e . printStackTrace ( );
}
try ( BufferedReader reader = new BufferedReader ( new FileReader ( filePath ))){
String line;
while (( line = reader . readLine ( )) ! = null ) {
System . out . println ( “ Read : “ + line );
}
} catch ( IOException e ) {
e . PrintStackTrace ( );
}
}
} 6. Streams API
Streams API was first introduced in Java 8, and since then, it has been processing collections in a declarative style in a powerful way. In the given example, we are going to filter odd numbers, sort them, square them, and collect the results:
java
import java . util. *;
import java . util . stream. *;
public class StreamExample {
public static void main ( String [ ] args ) {
List < Integer > numbers = Arrays . Aslist ( 5, 3, 8, 1, 9, 2 );
List < Integer > result = numbers . stream ( )
.filter ( n - > n % 2 == 1 )
.sorted ( )
.map ( n - > n * n )
.collect ( Collectors . toList ( ));
System . out . println ( result ); // [ 1, 9, 25, 81 ]
}
} 7. Threads and Synchronization
To build responsive and performant applications, multithreading is crucial, specifically while managing background tasks or parallel workloads. In this example, two threads will work concurrently to increment a shared counter:
java
public class ThreadExample {
private int count = 0;
public synchronized void increment ( ) {
Count ++;
}
public static void main ( String [ ] args ) throws InterruptedException {
ThreadExample example = new ThreadExample ( );
Runnable task = ( ) - > {
for int i = 0; i < 1000; i++) {
example . increment ( );
}
};
Thread t1 = new Thread ( task );
Thread t2 = new Thread ( task );
t1 . start ( );
t2 . start ( );
t1 .join ( );
t2 . join ( );
System . out .println ( “ Final count :” + example . count ); // Should be 2000
}
} 8. Error Management
Certain errors may occur even if you carefully manage your code. These include null pointer exceptions, divide by zero, or file not found. Here’s how you can throw and catch an ‘Arithmetic Exception’ when dividing by zero:
java
public class ExceptionExample {
public static int divide ( int a , int b ) throws ArithmeticException {
If ( b == 0 ) {
throw new ArithmeticException ( “ Cannot divide by zero.” );
}
return a / b;
}
public static void main ( String [ ] args ) {
Try {
System . out . println ( divide ( 10 , 0));
} catch ( ArithmeticException e ){
System . err .println ( “ Caught error:” + e . GetMessage ( ));
} finally {
System . out . println ( “ Finished division attempt.” );
}
}
} 9. Integration with JSP
Through Java Server Pages (JSP), developers can embed Java code into HTML, designing dynamic web content. In this Java code example, with the help of an array of colors, we use Java to show the current data and loop:
java
< % @page import = “ java . util. *” %>
< !DOCTYPE html >
< html >
< head > < title> JSP & Java Demo < /title > < /head >
< body >
< h2 > Current Date & Time < /h2 >
< %
date now = new Date ( );
out. println ( “ Now:” + now . toString ( ));
%>
< h3 > JSP Loop Example < \h3 >
< %
String [ ] colors = { “ Red ” , “ Green” , “ Blue" };
for ( String color : colors ) {
out . println ( color + “ < br/ >” );
}
% >
< / body >
< / html > 10. Access to Database
Java programs can easily connect to databases (like MySQL) with Java Database Connectivity (JDBC). Here, we will establish a connection, execute an SQL query, and process the outcome. To ensure statements and connections are closed properly, we are using the ‘try-with-resources’ command:
java
< %@ page import = “ java . Util. *” %>
< !DOCTYPE html>
< html >
< head > < title > JSP & Java Demo < / title > < / head >
< body >
< h2 > Current Date & Time < /h2 >
<%
Date now = new Date ( );
out . println ( “ Now :” + now . ToString ( ));
%>
< h3 > JSP Loop Example < /h3 >
<%
String [ ] colors = { “ Red” , “ Green ” , “ Blue ” };
for ( String color : colors ) {
out . println ( color + “ < br />” );
}
%>
< / body >
< / html > Java Vs JavaScript: Code
Java is a statically typed and compiled language designed specifically for backend systems, enterprise software, and Android applications. JavaScript is a dynamically typed, interpreted language, developed to power interactive frontends.
Certain syntax elements are shared between Java, JavaScript, and other popular JavaScript frameworks, like method names and curly braces. That you can see in the given Java vs JavaScript code examples:
java
public class Sum {
public static int add ( int a , int b ) {
return a + b;
}
public static void main ( String [ ] args ) {
System . out . println ( add ( 5 , 7)) ; // 12
}
}
javascript
function add ( a , b) {
return a + b;
}
console . log ( add ( 5 , 7 )) ; // 12 Conclusion
You have learnt 10 essential Java code examples in this blog, starting from the basic ‘Hello World, to using JSP and JDBC. Every example illustrates Java concepts like syntax, OOP, streams, data structures, concurrency, database integration, and error handling. Practice them well to gain real-world Java skills in 2025.
Happy Coding!
FAQs
1. What are the Java code examples?
Java examples include basic syntax, loops, conditional statements, classes, file I/O, error handling, streams, JSP integrations, and others as well.
2. How can I start coding with Java?
To code with Java, you can start by installing the Java Development Kit (JDK), configuring environment variables, learning syntax through a simple program, using an IDE, and then by regular practice.
3. Where can I look for more Java code examples?
For more Java code examples, check out GitHub projects, Oracle’s Java tutorials, StackOverflow, and Java-centric blogs.



