Java is one of the most popular programming languages in the world. It is used to develop mobile apps, web apps, desktop apps, games, and much more.
Key Concepts
Java was developed by Sun Microsystems (now owned by Oracle) in 1995.
Java is an object-oriented, class-based, concurrent programming language.
Java's motto: "Write Once, Run Anywhere" (WORA).
More than 3 billion devices run Java worldwide.
Java Example
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Live Editor
Java Introduction
Java is a general-purpose programming language that is class-based and object-oriented. It is designed to have as few implementation dependencies as possible.
Why Use Java?
Platform Independent: Java code is compiled to bytecode that runs on the Java Virtual Machine (JVM), making it platform independent.
Object-Oriented: Everything in Java is an object. OOP makes the full program simpler by breaking it into objects.
Secure: Java has built-in security features like no explicit pointer usage and bytecode verification.
Robust: Java has strong memory management, exception handling, and type checking.
Multithreaded: Java supports multithreading at the language level.
Java applications are compiled to bytecode that can run on any JVM regardless of the underlying hardware or OS. This makes Java extremely portable. The JVM acts as an intermediary between the Java code and the machine, translating bytecode into machine-specific instructions at runtime.
Java is widely used in enterprise-level applications, Android mobile development, big data technologies (like Hadoop and Spark), and server-side web development using frameworks like Spring Boot.
Common Mistakes and Pitfalls
Confusing Java with JavaScript — they are completely different languages.
Not understanding that Java is compiled to bytecode, NOT directly to machine code.
Java Get Started
To start writing Java programs, you need to install the Java Development Kit (JDK) and set up your environment.
Verify: Run java -version and javac -version in terminal.
Use an IDE like IntelliJ IDEA, Eclipse, or VS Code.
After installing the JDK, you write your code in a .java file. The Java compiler (javac) compiles it into a .class file (bytecode). You then run the bytecode using the java command.
Compile and Run
# Save code as Main.java
javac Main.java # Compile
java Main # Run
Best Practices
Always name the file with the same name as the public class inside it.
Use an IDE for autocompletion, debugging, and project management.
Java Syntax
Every Java application must contain a main method. The main method is the entry point of any Java program.
Key Concepts
Every line of code in Java must be inside a class.
The class name should always start with an uppercase letter and match the filename.
Java is case-sensitive.
Every statement ends with a semicolon;.
Syntax Example
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Live Editor
Common Mistakes
Forgetting the semicolon at the end of a statement.
Not matching the filename to the public class name.
Using system instead of System (case sensitivity).
Java Output
You can use println() to output values or print text in Java.
Key Concepts
System.out.println() — prints and adds a new line.
System.out.print() — prints without adding a new line.
You can print numbers, text, and expressions.
Output Example
System.out.println("Hello World!");
System.out.println(3 + 3);
System.out.print("I am learning ");
System.out.print("Java!");
Java Comments
Comments can be used to explain Java code and to make it more readable. They can also be used to prevent execution when testing alternative code.
Key Concepts
Single-line comments start with //.
Multi-line comments start with /* and end with */.
Javadoc comments start with /** and are used for documentation.
Comment Example
// This is a single-line comment
/* This is a
multi-line comment */
/** This is a Javadoc comment
* @param args command line arguments
*/
Java Variables
Variables are containers for storing data values. In Java, there are different types of variables.
Key Concepts
String — stores text like "Hello".
int — stores integers like 123.
float — stores floating point numbers like 19.99f.
char — stores single characters like 'a'.
boolean — stores values with two states: true or false.
Use final keyword to declare a constant.
In Java, you must declare the variable type before using it. Java is a statically typed language, meaning the type of a variable is known at compile time. This is different from Python where types are inferred at runtime.
Variable Example
String name = "John";
int myNum = 15;
float myFloat = 5.99f;
char myLetter = 'D';
boolean myBool = true;
final int CONSTANT = 100;
Live Editor
Common Mistakes
Using a variable before declaring it.
Trying to reassign a final constant variable.
Forgetting to add f suffix to float literals.
Java Data Types
Data types specify the different sizes and values that can be stored in a variable.
Primitive Data Types
byte — 1 byte, stores whole numbers from -128 to 127.
short — 2 bytes, stores whole numbers from -32,768 to 32,767.
int — 4 bytes, stores whole numbers up to ~2.1 billion.
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
Live Editor
Java Switch
Use the switch statement to select one of many code blocks to be executed.
Switch Example
int day = 4;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
default: System.out.println("Other day");
}
Warning: Don't forget the break keyword! Without it, the code will "fall through" and execute the next case as well.
Java While Loop
The while loop loops through a block of code as long as a specified condition is true.
While Loop Example
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Live Editor
Java For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop.
Loop Types
for — traditional counter-based loop.
for-each — iterates over elements of arrays and collections.
For Loop Example
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// For-each loop
String[] cars = {"Volvo", "BMW", "Ford"};
for (String car : cars) {
System.out.println(car);
}
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
Key Concepts
Arrays are declared with square brackets: String[] cars;
Array elements are accessed by their index (starting from 0).
A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method.
Key Concepts
Methods are defined with an access modifier, return type, name, and parameters.
void means the method does not return a value.
Methods can have parameters and return values.
Method Overloading: Multiple methods can have the same name but different parameters.
Method Example
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
}
Live Editor
Java Classes & Objects
Java is an object-oriented programming language. Everything in Java is associated with classes and objects, along with its attributes and methods.
Key Concepts
A class is a blueprint for creating objects.
An object is an instance of a class.
Attributes are variables within a class.
Methods define behaviors of the class.
Use new keyword to create an object.
Class Example
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Java Inheritance
In Java, it is possible to inherit attributes and methods from one class to another using the extends keyword.
Key Concepts
Subclass (child): The class that inherits from another class.
Superclass (parent): The class being inherited from.
Use extends to inherit from a class.
Java does not support multiple inheritance (use interfaces instead).
Inheritance Example
class Vehicle {
protected String brand = "Ford";
public void honk() {
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang";
public static void main(String[] args) {
Car myCar = new Car();
myCar.honk();
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. It lets us perform a single action in different ways.
Key Concepts
Method Overriding: A subclass provides a specific implementation of a method already provided by its parent class.
Method Overloading: Multiple methods with the same name but different parameters.
Polymorphism Example
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
Java Abstraction
Data abstraction is the process of hiding certain details and showing only essential information to the user. It can be achieved with either abstract classes or interfaces.
Key Concepts
Abstract Class: Cannot be used to create objects. Must be inherited from another class.
Abstract Method: Can only be used in an abstract class, and has no body.
Interface: A completely "abstract class" that groups related methods with empty bodies.
Java Encapsulation
Encapsulation means making sure that "sensitive" data is hidden from users. To achieve this, declare class variables as private and provide get and set methods.
Encapsulation Example
public class Person {
private String name;
// Getter
public String getName() { return name; }
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Best Practices
Always use private for class attributes.
Provide public getter and setter methods to access and update the value.
Add validation logic inside setters to protect data integrity.
Java Exceptions
When executing Java code, different errors can occur. Java provides a powerful mechanism to handle runtime errors using try...catch.
Key Concepts
try — defines a block of code to be tested for errors.
catch — defines a block of code to handle the error.
finally — executes code after try/catch, regardless of the result.