Java is an object-oriented programming language, widely used for its robustness, portability, and efficiency.
It is commonly used in server applications, distributed systems, and mobile application development.
Environment Setup
JDK Installation
For JDK (Java Development Kit) installation:
Verify Java Installation
Check if Java is correctly installed.
java -version
Set the JAVA_HOME Environment Variable
Make sure to have the JAVA_HOME
variable correctly set.
export JAVA_HOME=/path/to/jdk
export PATH=$JAVA_HOME/bin:$PATH
Compilation and Execution
Compile a Java Program
The Java compiler (Javac) converts the .java
source code into .class
bytecode.
javac MyProgram.java
Run a Java Program
Use the java
command to execute the generated bytecode.
java MyProgram
Compile and Run in One Line
On UNIX systems, you can combine both commands into a single line.
javac MyProgram.java && java MyProgram
Syntax and Data Types
Basic Structure
A Java program generally consists of a public class with a main
method.
public class MyProgram {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Primitive Types
Java supports the following primitive data types:
Type | Size | Values |
---|---|---|
byte | 1 byte | -128 to 127 |
short | 2 bytes | -32,768 to 32,767 |
int | 4 bytes | -2^31 to 2^31-1 |
long | 8 bytes | -2^63 to 2^63-1 |
float | 4 bytes | Single precision 32 bits |
double | 8 bytes | Double precision 64 bits |
char | 2 bytes | A Unicode character (16 bits) |
boolean | 1 bit | true or false |
Reference Types
Include any object and are assigned null
if they do not point to an object.
Variable Declaration
To declare a variable in Java, specify the type followed by the name.
int number = 10;
double price = 25.5;
char letter = 'A';
boolean isTrue = true;
Operators
Arithmetic Operators
These are the operators for performing mathematical operations:
Operator | Description | Example |
---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulo (remainder) | a % b |
Relational Operators
Used to compare two values.
Operator | Description | Example |
---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal | a >= b |
<= | Less than or equal | a <= b |
Logical Operators
Allow logical operations on boolean variables.
Operator | Description | Example |
---|---|---|
&& | Logical AND | a && b |
` | ` | |
! | Logical NOT | !a |
Control Flow
Conditionals
If - Else
Used to make decisions based on conditions.
if (condition) {
// Block if the condition is true
} else {
// Block if the condition is false
}
Switch
Allows evaluating multiple cases for the same expression.
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Another day");
}
Loops
For Loop
The for
loop is used when you know the number of iterations.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
While Loop
This loop repeats while the condition is true.
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Do-While Loop
Unlike while
, it executes the code block at least once.
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
Methods
Method Definition
Methods are reusable blocks of code.
public int sum(int a, int b) {
return a + b;
}
Method Call
int result = sum(5, 10);
System.out.println(result);
Lambda Expressions
Allow treating code as data and enhance readability.
import java.util.Arrays;
Arrays.asList(1, 2, 3).forEach(num -> System.out.println(num * 2));
Collections
Lists
Use ArrayList
to store elements dynamically.
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("Element 1");
list.add("Element 2");
Maps
HashMap
to store key-value pairs.
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("Key1", 1);
map.put("Key2", 2);
Classes and Objects
Class Definition
A class is a blueprint for creating objects.
class Person {
String name;
int age;
void greet() {
System.out.println("Hello, my name is " + name);
}
}
Create an Object
An object is an instance of a class.
Person person1 = new Person();
person1.name = "John";
person1.age = 25;
person1.greet();
Constructors
A constructor initializes objects when they are created.
class Person {
String name;
int age;
// Constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Create an Object with Constructor
Person person2 = new Person("Ana", 30);
Access Modifiers
Access modifiers control the visibility of class members.
Modifier | Access from… | Example |
---|---|---|
public | Any class | public int age; |
private | Only within the class | private int age; |
protected | Subclasses and package | protected int age; |
Object-Oriented Programming
Definition of Inheritance
Inheritance allows a class to derive from another, inheriting its attributes and methods.
class Animal {
void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("The dog barks");
}
}
Using Inheritance
Animal myAnimal = new Animal();
myAnimal.makeSound();
Dog myDog = new Dog();
myDog.makeSound();
Using super
Used to call the constructor of the parent class.
public class Student extends Person {
public Student(String name, int age, String major) {
super(name, age);
this.major = major;
}
}
Interfaces
An interface defines methods that must be implemented by the classes that inherit it.
interface Flyer {
void fly();
}
class Bird implements Flyer {
public void fly() {
System.out.println("The bird flies");
}
}
Polymorphism
The same reference can point to different types of objects.
Flyer f = new Bird();
f.fly(); // Calls the method of the Bird class
Exceptions
Exception Handling
Exceptions allow handling errors in a controlled way.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero.");
} finally {
System.out.println("The finally block always executes.");
}
Throwing Exceptions
public void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Not old enough.");
}
}
Standard Libraries
Common Classes from java.util
ArrayList
Class
Used to store dynamic lists.
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("Element 1");
list.add("Element 2");
System.out.println(list.get(0)); // Access the first element
HashMap
Class
Used to store key-value pairs.
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
System.out.println(map.get("One")); // Prints 1
Concurrency
Threads
The Thread
class allows concurrent execution of tasks.
class MyThread extends Thread {
public void run() {
System.out.println("The thread is running");
}
}
MyThread thread = new MyThread();
thread.start();
Synchronization
Use synchronized
to prevent race conditions.
public synchronized void synchronizedMethod() {
// safe code
}
Input and Output
Read from Console
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
Read and Write Files
import java.io.*;
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
writer.write("Hello, World!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Streams
Streams
allow processing collections of data functionally.
List<String> list = Arrays.asList("a", "b", "c");
list.stream().filter(s -> s.startsWith("a")).forEach(System.out::println);