Java Tutorial for Beginners
1. Introduction to Java:
Java is a widely used programming language known for its platform independence. It uses a "write once, run anywhere" approach, allowing programs to be executed on any platform that has a Java Virtual Machine (JVM).
2. Installing Java:
To get started, you need to install the Java Development Kit (JDK) on your system. You can download the latest JDK from the official Oracle website.
3. Writing Your First Java Program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation: This program demonstrates the basic structure of a Java program. It defines a class named `HelloWorld` with a `main` method, where the program execution begins. The `System.out.println` statement prints the message to the console.
4. Variables and Data Types:
int age = 25;
double salary = 50000.50;
char grade = 'A';
String name = "John";
boolean isStudent = true;
Explanation: Java supports various data types like `int`, `double`, `char`, `String`, and `boolean` for storing different types of values.
5. Operators:
int a = 10, b = 5;
int sum = a + b;
int product = a * b;
int quotient = a / b;
Explanation: Java provides arithmetic (`+`, `-`, `*`, `/`), comparison (`<`, `>`, `==`, `!=`), and logical (`&&`, `||`, `!`) operators for performing operations.
6. Control Structures:
- if-else:
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is not greater than 5");
}
- for loop:
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
- while loop:
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
7. Arrays:
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Carol";
Explanation: Arrays allow you to store multiple values of the same data type in a single variable.
8. Methods:
public int add(int a, int b) {
return a + b;
}
int result = add(3, 5);
System.out.println("Sum: " + result);
Explanation: Methods are reusable blocks of code. They can take parameters, perform tasks, and return values.
9. Classes and Objects:
class Car {
String brand;
int year;
void startEngine() {
System.out.println("Engine started");
}
}
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.year = 2023;
myCar.startEngine();
Explanation: Classes define the blueprint for creating objects. Objects are instances of classes, and they encapsulate data and behavior.
10. Constructors:
class Student {
String name;
Student(String n) {
name = n;
}
}
Student student1 = new Student("Alice");
Student student2 = new Student("Bob");
Explanation: Constructors are special methods used to initialize objects when they are created.
11. Encapsulation:
Encapsulation is the concept of bundling data (attributes) and methods (behavior) that operate on the data into a single unit, known as a class.
12. Inheritance:
class Animal {
void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof woof!");
}
}
Dog myDog = new Dog();
myDog.makeSound();
Explanation: Inheritance allows one class (subclass) to inherit the attributes and methods of another class (superclass).
13. Polymorphism:
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}
Shape shape1 = new Circle();
shape1.draw();
Explanation: Polymorphism allows objects of different classes to be treated as objects of a common superclass.
14. Method Overloading:
class MathUtils {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Explanation: Method overloading allows defining multiple methods with the same name but different parameter lists.
15. Method Overriding:
class Parent {
void show() {
System.out.println("Parent class");
}
}
class Child extends Parent {
void show() {
System.out.println("Child class");
}
}
Explanation: Method overriding allows a subclass to provide a specific implementation for a method defined in its superclass.
16. Abstract Classes:
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}
Explanation: Abstract classes cannot be instantiated and can contain abstract methods, which must be implemented by concrete subclasses.
17. Interfaces:
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() {
System.out.println("Drawing a circle");
}
}
Explanation: Interfaces define a contract that classes must adhere to by implementing the methods defined in the interface.
18. Packages:
Java packages are used to organize classes into meaningful namespaces to avoid naming conflicts.
19. Access Modifiers:
Java has four access modifiers: `public`, `protected`, `default` (no modifier), and `private`, which control the visibility and accessibility of classes, fields, methods, and constructors.
20. Exception Handling:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
Explanation: Exception handling allows you to gracefully handle runtime errors to prevent program crashes.
21. File I/O:
import java.io.*;
public class FileExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("myfile.txt");
writer.write("Hello, Java!");
writer.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Explanation: File Input/Output operations allow you to read from and write to files
.
22. Static Members:
Static members (fields and methods) belong to the class rather than instances of the class. They are accessed using the class name.
23. Final Keyword:
The `final` keyword can be used to make a class not extendable, a method not overrideable, or a variable a constant.
24. Enums:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day today = Day.WEDNESDAY;
System.out.println("Today is " + today);
Explanation: Enums define a set of named values, often used to represent categories or options.
25. Generics:
class Box<T> {
private T item;
void setItem(T item) {
this.item = item;
}
T getItem() {
return item;
}
}
Explanation: Generics allow you to create classes, interfaces, and methods that operate on types specified at compile time.
26. Collections Framework:
Java's Collections Framework provides a set of interfaces and classes to work with collections (lists, sets, maps, etc.) of objects.
27. List and ArrayList:
import java.util.ArrayList;
import java.util.List;
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Carol");
System.out.println(names.get(1)); // Output: Bob
Explanation: ArrayList is a dynamic array implementation of the List interface.
28. Set and HashSet:
import java.util.HashSet;
import java.util.Set;
Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Bob"); // Duplicates are not allowed
System.out.println(uniqueNames.size()); // Output: 2
Explanation: HashSet is an implementation of the Set interface that does not allow duplicates.
29. Map and HashMap:
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
System.out.println(ages.get("Alice")); // Output: 25
Explanation: HashMap is an implementation of the Map interface that stores key-value pairs.
30. Threads and Concurrency:
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread: " + i);
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
Explanation: Java supports multithreading, allowing multiple threads to execute concurrently.