Welcome to this easy-to-follow Java tutorial designed for beginners! Whether you’re new to programming or looking to refresh your skills, this guide will help you learn Java step by step with clear explanations and practical examples.
Java is a powerful, versatile, and widely used programming language known for its “Write Once, Run Anywhere” (WORA) capability. This means Java code can run on any device with a Java Virtual Machine (JVM), making it perfect for:
✅ Easy to learn (clean syntax, similar to English)
✅ High demand in the job market
✅ Strong community support
✅ Platform-independent (works on Windows, Mac, Linux)
Before coding, you need to install Java and set up your development environment.
Download the latest JDK from Oracle’s official website.
Popular IDEs for Java:
Let’s create a simple “Hello World” program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
How to Run the Program?
HelloWorld.java
javac HelloWorld.java
java HelloWorld
Output:
Hello, World!
🎉 Congratulations! You’ve just written your first Java program.
A Java program follows a structured format:
// Class Declaration (Filename must match class name)
public class MyClass {
// Main Method (Entry point of the program)
public static void main(String[] args) {
// Your code goes here
System.out.println("Java is fun!");
}
}
Variables are containers that store data in a program.
How to Declare a Variable?
datatype variableName = value;
✔ Must start with a letter, _
, or $
✔ Cannot use Java keywords (e.g., int
, class
)
✔ Case-sensitive (age
≠ Age
)
Example:
int age = 25;
String name = "Alice";
double salary = 50000.50;
Understanding data types is crucial in Java because they define what kind of data a variable can hold. Java has two main categories of data types:
Think of data types like different container types:
true
/false
).Let’s explore each in detail with simple explanations and examples.
Primitive data types are predefined by Java and hold single values with no additional methods.
Data Type | Size | Default Value | Range | Example |
---|---|---|---|---|
byte | 1 byte | 0 | -128 to 127 | byte age = 25; |
short | 2 bytes | 0 | -32,768 to 32,767 | short salary = 15000; |
int | 4 bytes | 0 | -2³¹ to 2³¹-1 | int population = 2000000; |
long | 8 bytes | 0L | -2⁶³ to 2⁶³-1 | long distance = 15000000000L; |
float | 4 bytes | 0.0f | ~±3.4e38 | float pi = 3.14f; |
double | 8 bytes | 0.0d | ~±1.7e308 | double price = 19.99; |
char | 2 bytes | ‘\u0000’ | 0 to 65,535 (Unicode) | char grade = 'A'; |
boolean | 1 bit | false | true or false | boolean isJavaFun = true; |
✔ byte
, short
, int
, long
→ Used for whole numbers (different sizes).
✔ float
& double
→ Used for decimal numbers (double
is more precise).
✔ char
→ Stores single characters (e.g., 'A'
, '$'
, '3'
).
✔ boolean
→ Only true
or false
(used in conditions).
int age = 30;
double height = 5.9;
char initial = 'J';
boolean isEmployed = true;
These are objects and do not store the actual value but a reference (memory address) to the data.
Data Type | Description | Example |
---|---|---|
String | Stores text (sequence of characters) | String name = "Alice"; |
Array | Stores multiple values of the same type | int[] numbers = {1, 2, 3}; |
Class | User-defined blueprint for objects | class Car { ... } |
Interface | Defines methods without implementation | interface Drawable { ... } |
❌ Not predefined (created by the programmer).
❌ Start with uppercase (e.g., String
, Array
).
❌ Can be null
(primitives cannot).
String greeting = "Hello, Java!";
int[] scores = {90, 85, 77};
Sometimes, you need to convert one data type to another.
→ Smaller type → Larger type (No data loss)
→ Done automatically by Java.
Example:
int num = 100;
long bigNum = num; // Automatic conversion (int → long)
→ Larger type → Smaller type (May lose data)
→ Requires explicit casting.
Example:
double decimal = 9.78;
int wholeNum = (int) decimal; // Manual casting (double → int)
// Output: 9 (loses decimal part)
🚫 Using float
without f
suffix → float pi = 3.14;
❌ (Error)
✅ Fix: float pi = 3.14f;
🚫 Storing large numbers in int
→ int bigNum = 3000000000;
❌ (Too big)
✅ Fix: long bigNum = 3000000000L;
🚫 Comparing String
with ==
→ if (name == "Alice")
❌ (Use .equals()
)
✅ Fix: if (name.equals("Alice"))
Category | Data Types | Usage |
---|---|---|
Primitive | byte , short , int , long | Whole numbers |
float , double | Decimal numbers | |
char | Single characters | |
boolean | true /false | |
Non-Primitive | String | Text |
Array | Multiple values | |
Class , Interface | Custom objects |
Now you know:
✔ Primitive types (like int
, double
) store simple values.
✔ Non-primitive types (like String
, Array
) store complex data.
✔ Type conversion helps switch between data types.
✔ Common mistakes to avoid when working with data types.
Operators in Java are symbols that perform operations on variables and values.
Think of them as tools that let you:
Used for basic calculations like addition, subtraction, etc.
Operator | Name | Example | Result |
---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 10 - 4 |
6 |
* |
Multiplication | 2 * 6 |
12 |
/ |
Division | 20 / 5 |
4 |
% |
Modulus (Remainder) | 10 % 3 |
1 *(since 10 ÷ 3 = 3 with remainder 1)* |
public class HelloWorld {
int a = 15, b = 4;
System.out.println(a + b); // 19
System.out.println(a % b); // 3 (remainder of 15 ÷ 4)
}
Return true
or false
by comparing values.
Operator | Meaning | Example | Result |
---|---|---|---|
== |
Equal to | 5 == 5 |
true |
!= |
Not equal | 5 != 3 |
true |
> |
Greater than | 10 > 5 |
true |
< |
Less than | 3 < 2 |
false |
>= |
Greater than or equal | 7 >= 7 |
true |
<= |
Less than or equal | 5 <= 3 |
false |
Example:
public class HelloWorld {
int age = 20;
System.out.println(age >= 18); // true (checks if age is 18 or older)
}
Used to test multiple conditions at once.
Operator | Name | Description | Example | Result |
---|---|---|---|---|
&& |
Logical AND | Returns true only if both conditions are true |
(5 > 3) && (2 < 4) |
true |
|| |
Logical OR | Returns true if at least one condition is true |
(5 > 3) || (2 > 4) |
true |
! |
Logical NOT | Reverses the result (true → false , false → true ) |
!(5 == 3) |
true |
&&
(AND)
if (isStudent && hasID)
→ Only true if both are true
.\|\|
(OR)if (hasCoupon \|\| isMember)
→ True if either is true
.!
(NOT)
if (!isRaining)
→ True if isRaining
is false
.boolean isSunny = true;
boolean isWeekend = false;
System.out.println(isSunny && isWeekend); // false (AND)
System.out.println(isSunny || isWeekend); // true (OR)
System.out.println(!isWeekend); // true (NOT)
Why This Order?
Assign values to variables (with optional math).
Operator | Example | Equivalent To |
---|---|---|
= |
x = 5 |
x = 5 |
+= |
x += 3 |
x = x + 3 |
-= |
x -= 2 |
x = x - 2 |
*= |
x *= 4 |
x = x * 4 |
/= |
x /= 2 |
x = x / 2 |
Example:
int score = 10;
score += 5; // score = 10 + 5 → 15
System.out.println(score); // 15
Shortcuts to increase or decrease a value by 1.
Operator | Example | Meaning |
---|---|---|
++ |
x++ |
x = x + 1 |
-- |
x-- |
x = x - 1 |
int count = 5;
count++; // count becomes 6
System.out.println(count); // 6
=
vs ==
=
assigns a value (x = 5
).==
checks equality (if (x == 5)
).Control statements let you control the flow of your Java program by making decisions, repeating actions, or branching code execution.
if-else
StatementsExecute code only if a condition is true.
if (condition) {
// Code runs if condition is true
} else {
// Code runs if condition is false
}
Examples:
int age = 18;
if (age >= 18) {
System.out.println("You can vote!");
} else {
System.out.println("Too young to vote.");
}
Statement | Usage |
---|---|
if | Single condition check |
if-else | Choose between two options |
else-if | Multiple conditions (like a ladder) |
int marks = 85;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 80) {
System.out.println("Grade B"); // This runs
} else {
System.out.println("Grade C");
}
switch-case
StatementsBest for multiple fixed choices (like menus).
switch (variable) { case value1: // Code for value1 break; case value2: // Code for value2 break; default: // Code if no case matches }
int day = 3; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); // This runs break; default: System.out.println("Invalid day"); }
✔ break
→ Stops further checks (without it, execution “falls through”).
✔ default
→ Runs if no case matches (like else
).
for
LoopBest when you know how many times to repeat.
for (initialization; condition; update) { // Code to repeat }
for (int i = 1; i <= 5; i++) { System.out.println("Count: " + i); }
Output:
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
while
LoopRepeats while a condition is true (checks first).
while (condition) { // Code to repeat }
int i = 1; while (i <= 5) { System.out.println("Count: " + i); i++; }
(Same output as for
loop above.)
do-while
LoopRuns at least once before checking the condition.
do { // Code to repeat } while (condition);
int i = 1; do { System.out.println("Count: " + i); i++; } while (i <= 5);
(Works like a while
loop, but always runs at least once.)
break
switch
immediately.for (int i = 1; i <= 10; i++) { if (i == 5) break; // Stops at 5 System.out.println(i); }
continue
for (int i = 1; i <= 5; i++) { if (i == 3) continue; // Skips 3 System.out.println(i); }
Output: 1 2 4 5
return
boolean isAdult(int age) { return (age >= 18); // Returns true/false }
Category | Key Statements | When to Use |
---|---|---|
Decision | if , else-if , switch | Choose between paths |
Loop | for , while , do-while | Repeat code |
Jump | break , continue , return | Control flow within loops/methods |
if-else
→ Simple true/false decisions.switch
→ Many fixed choices (e.g., menus).for
→ Known number of repetitions.while
→ Unknown repetitions (check first).do-while
→ Must run at least once.🚀 Try It Yourself!
Print even numbers from 1 to 10 using a loop.
for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { System.out.println(i); } }
Output: 2 4 6 8 10
A method in Java is a block of code that performs a specific task and runs only when called. Think of it like a recipe: you write the steps once, and you can use that recipe whenever you need to make the dish. Methods help organize your code, make it reusable, and keep it clean.
returnType methodName(parameters) {
// Code to perform the task
}
returnType: The type of data the method returns (e.g., int, String, or void if it returns nothing).
methodName: A meaningful name for the method (e.g., calculateSum).
parameters: Optional inputs the method needs to work (e.g., int a, int b).
Java supports several types of methods, each serving a unique purpose:
Example: Printing a message to the console.
Example: Calculating and returning the sum of two numbers.
Example: Utility methods like Math.sqrt().
Example: A method that calculates the square of a given number.
Example: A method that always prints a fixed message.
Let’s create a method that calculates the square of a number and returns the result.
public class SquareCalculator {
// Method to calculate the square of a number
public static int calculateSquare(int number) {
return number * number;
}
public static void main(String[] args) {
// Calling the method
int result = calculateSquare(5);
System.out.println("Square of 5 is: " + result); // Output: Square of 5 is: 25
}
}
Explanation:
Using methods makes your code more efficient and easier to manage. For example, instead of writing the same code to calculate squares multiple times, you can call calculateSquare whenever needed. This is a core concept in Java programming for beginners and aligns with best practices for clean code.
Aspect | Static Method | Non-Static Method |
---|---|---|
Definition | Belongs to the class, defined with the static keyword. | Belongs to an instance of the class, no static keyword. |
How to Call | Called using the class name (e.g., ClassName.methodName()). No object needed. | Called using an object of the class (e.g., objectName.methodName()). |
Access to Instance Variables | Cannot directly access instance variables or methods unless an object is created. | Can directly access instance variables and other non-static methods of the class. |
Memory Allocation | Allocated when the class is loaded into memory (once for the class). | Allocated when an object is created (each object has its own copy). |
Use Case | Used for operations that don’t depend on object state (e.g., utility functions). | Used for operations tied to a specific object’s data (e.g., getting/setting object properties). |
Example Keyword | static (e.g., public static void utilityMethod()). | No static (e.g., public void instanceMethod()). |
An array in Java is a container that holds multiple values of the same data type in a single variable. Imagine an array as a row of lockers, where each locker stores one value, and you can access them using their position (index).
dataType[] arrayName = new dataType[size];
dataType: The type of data the array will hold (e.g., int, String).
arrayName: A name for the array.
size: The number of elements the array can hold.
Index: Each element in an array is accessed using an index (starting from 0).
Example: Storing a list of student marks.
Example: A 2D array for a chessboard (rows and columns).
Example: A list of student grades where each student has a different number of scores.
Let’s create an array to store and print student marks.
public class StudentMarks {
public static void main(String[] args) {
// Declaring and initializing an array
int[] marks = new int[5]; // Array to store 5 marks
marks[0] = 85;
marks[1] = 90;
marks[2] = 78;
marks[3] = 92;
marks[4] = 88;
// Printing the array using a for loop
System.out.println("Student Marks:");
for (int i = 0; i < marks.length; i++) {
System.out.println("Mark " + (i + 1) + ": " + marks[i]);
}
// Using a for-each loop
System.out.println("\nUsing for-each loop:");
for (int mark : marks) {
System.out.println("Mark: " + mark);
}
}
}
Output:
Student Marks:
Mark 1: 85
Mark 2: 90
Mark 3: 78
Mark 4: 92
Mark 5: 88
Using for-each loop:
Mark: 85
Mark: 90
Mark: 78
Mark: 92
Mark: 88
Explanation:
Let’s create a 2D array to represent a 2×3 matrix.
public class MatrixExample {
public static void main(String[] args) {
// Declaring and initializing a 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
// Printing the 2D array
System.out.println("2D Array (Matrix):");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // New line after each row
}
}
}
Output:
2D Array (Matrix):
1 2 3
4 5 6
Explanation:
Arrays are perfect for storing and managing lists of data, like scores, names, or coordinates. They’re a fundamental concept in Java programming and are widely used in real-world applications, such as data analysis, game development, and more.
The java.util.Arrays class provides static methods to perform common operations on arrays, such as sorting, searching, copying, and comparing. To use these methods, you need to import the Arrays class:
import java.util.Arrays;
Here’s a list of key Arrays class methods, their definitions, and practical uses, along with examples.
Arrays.sort(array); // Sorts the entire array
Arrays.sort(array, fromIndex, toIndex); // Sorts a specific range
import java.util.Arrays;
public class SortExample {
public static void main(String[] args) {
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers); // Sort in ascending order
System.out.println("Sorted Array: " + Arrays.toString(numbers));
// Output: Sorted Array: [1, 2, 5, 8, 9]
}
}
String result = Arrays.toString(array);
import java.util.Arrays;
public class ToStringExample {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie"};
System.out.println(Arrays.toString(names));
// Output: [Alice, Bob, Charlie]
}
}
Arrays.fill(array, value); // Fills entire array
Arrays.fill(array, fromIndex, toIndex, value); // Fills specific range
import java.util.Arrays;
public class FillExample {
public static void main(String[] args) {
int[] array = new int[5];
Arrays.fill(array, 10); // Fill array with 10
System.out.println("Filled Array: " + Arrays.toString(array));
// Output: Filled Array: [10, 10, 10, 10, 10]
}
}
dataType[] newArray = Arrays.copyOf(originalArray, newLength);
import java.util.Arrays;
public class CopyOfExample {
public static void main(String[] args) {
int[] original = {1, 2, 3};
int[] copied = Arrays.copyOf(original, 5); // New array with length 5
System.out.println("Copied Array: " + Arrays.toString(copied));
// Output: Copied Array: [1, 2, 3, 0, 0]
}
}
dataType[] newArray = Arrays.copyOfRange(originalArray, from, to);
import java.util.Arrays;
public class CopyOfRangeExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int[] range = Arrays.copyOfRange(numbers, 1, 4); // Copy indices 1 to 3
System.out.println("Range Array: " + Arrays.toString(range));
// Output: Range Array: [2, 3, 4]
}
}
int index = Arrays.binarySearch(array, key);
import java.util.Arrays;
public class BinarySearchExample {
public static void main(String[] args) {
int[] numbers = {1, 3, 5, 7, 9};
Arrays.sort(numbers); // Ensure array is sorted
int index = Arrays.binarySearch(numbers, 5);
System.out.println("Index of 5: " + index);
// Output: Index of 5: 2
}
}
boolean isEqual = Arrays.equals(array1, array2);
import java.util.Arrays;
public class EqualsExample {
public static void main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3};
int[] array3 = {3, 2, 1};
System.out.println("array1 equals array2: " + Arrays.equals(array1, array2));
System.out.println("array1 equals array3: " + Arrays.equals(array1, array3));
// Output:
// array1 equals array2: true
// array1 equals array3: false
}
}
boolean isEqual = Arrays.deepEquals(array1, dualDepthArray);
import java.util.Arrays;public class DeepEqualsExample {
public static void main(String[] args) {
int[][] array1 = {{1, 2}, {3, 4}};
int[][] array2 = {{1, 2}, {3, 4}};
System.out.println("2D Arrays Equal: " + Arrays.deepEquals(array1, array2));
// Output: 2D Arrays Equal: true
}
}
List<T> list = Arrays.asList(array);
import java.util.Arrays;
import java.util.List;public class AsListExample {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie"};
List<String> nameList = Arrays.asList(names);
System.out.println("List: " + nameList);
// Output: List: [Alice, Bob, Charlie]
}
}
The Arrays class methods make working with arrays in Java easier and more efficient:
The Arrays class is a must-know tool for Java programming. These methods simplify common tasks, saving time and reducing errors when working with Java arrays. Whether you’re sorting data, copying arrays, or converting them to lists, these methods are essential for efficient coding.
We use cookies to improve your experience on our site. By using our site, you consent to cookies.
Manage your cookie preferences below:
Essential cookies enable basic functions and are necessary for the proper function of the website.
These cookies are needed for adding comments on this website.
These cookies are used for managing login functionality on this website.
Statistics cookies collect information anonymously. This information helps us understand how visitors use our website.
Google Analytics is a powerful tool that tracks and analyzes website traffic for informed marketing decisions.
Service URL: policies.google.com
Marketing cookies are used to follow visitors to websites. The intention is to show ads that are relevant and engaging to the individual user.
Sign in to your account