Contents
- Introduction to Java
- Java Basics
- Control Flow Statements
- Object-Oriented Programming
- Exception Handling
- Strings and String Handling
- Arrays and Collections
- Searching and Sorting
- Working with Date and Time
- Problem Solving and Sample Exercises
- DSA Java
Java is a platform-independent language, meaning it can run on any device that has a Java Virtual Machine (JVM). It's known for its object-oriented structure and simplicity, making it a powerful language for beginners and advanced users alike.
The first step in learning any language is to write a program that prints "Hello, World!" to the screen.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
-
Explanation:
public class HelloWorld
: Defines a class namedHelloWorld
. In Java, all code should be inside a class.public static void main(String[] args)
: The main method is the entry point for any Java program. It must be written exactly as shown.System.out.println("Hello, World!");
: This line prints "Hello, World!" to the console.
-
Output:
Hello, World!
Java supports several primitive data types:
- int: Stores integers (e.g.,
10
,-45
). - double: Stores decimal numbers (e.g.,
3.14
). - char: Stores single characters (e.g.,
'A'
). - boolean: Stores true/false values.
int age = 25;
double salary = 50000.50;
char grade = 'A';
boolean isStudent = false;
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Grade: " + grade);
System.out.println("Is Student: " + isStudent);
- Output:
Age: 25 Salary: 50000.5 Grade: A Is Student: false
Variables store values that can change, while constants use final
to prevent changes.
int num = 5; // Variable
final double PI = 3.14; // Constant
Control flow statements determine the order in which statements are executed in a program.
Used for conditional logic.
int age = 20;
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
- Explanation: Checks if
age
is 18 or more; if true, it prints "Adult"; otherwise, "Minor." - Output:
Adult
- for loop: Executes a set number of times.
- while loop: Repeats while a condition is true.
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
- Output:
Iteration: 0 Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4
Switch-case is used to select one of many code blocks based on the value of a variable.
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"); break;
default: System.out.println("Invalid day");
}
- Output:
Wednesday
Java is object-oriented, which means it models real-world entities using classes and objects.
A class is a blueprint, and an object is an instance of a class.
class Car {
String color;
int speed;
Car(String color, int speed) {
this.color = color;
this.speed = speed;
}
void display() {
System.out.println("Color: " + color + ", Speed: " + speed);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Red", 100);
myCar.display();
}
}
- Explanation:
Car
class has propertiescolor
andspeed
, and a methoddisplay
to show them. - Output:
Color: Red, Speed: 100
- Inheritance: Allows a class to inherit properties from another.
- Polymorphism: Lets an object take many forms (method overloading/overriding).
- Encapsulation: Hides data using
private
and exposes it throughpublic
methods. - Abstraction: Shows only essential details; hides the complex parts.
Java's exception handling ensures errors are caught and managed without crashing.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("Done!");
}
- Output:
Cannot divide by zero! Done!
Java has the String
class with powerful methods for handling text.
String s = "Hello, World!";
System.out.println("Length: " + s.length());
System.out.println("Uppercase: " + s.toUpperCase());
System.out.println("Substring: " + s.substring(7));
- Output:
Length: 13 Uppercase: HELLO, WORLD! Substring: World!
An array is a fixed-size collection of elements of the same type.
int[] numbers = {1, 2, 3};
System.out.println(numbers[0]); // Accessing element
Part of java.util
, it allows dynamic resizing.
ArrayList<String> list = new ArrayList<>();
list.add("Element");
System.out.println(list.get(0));
- Output:
Element
Sequentially checks each element until the desired one is found.
public static int linearSearch(int[] array, int key) {
for (int i = 0; i < array.length; i++) {
if (array[i] == key) return i;
}
return -1;
}
Efficient for sorted arrays by repeatedly dividing the search interval.
Arrays.binarySearch(array, key);
- Arrays.sort(): Sorts arrays.
- Collections.sort(): Sorts collections.
The java.time
package provides classes to work with date and time.
LocalDate date = LocalDate.now();
System.out.println("Today's date: " + date);
- Output:
Today's date: 2023-10-30 (example)
Reverse a String
public static String reverse(String str) {
return new StringBuilder(str).reverse().toString();
}
Output:
reverse("Java") -> "avaJ"
- Introduction to Java DSA
- Arrays
- Linked Lists
- Stacks
- Queues
- Trees
- Graphs
- Sorting Algorithms
- Searching Algorithms
- String Manipulation
- Hashing
- Recursion
- Dynamic Programming
- Conclusion and Best Practices
Data Structures and Algorithms (DSA) in Java are essential for efficient problem-solving and optimizing code performance. Key concepts include:
- Data Structures: Organize data for efficient access.
- Algorithms: Step-by-step instructions for solving problems.
Arrays store elements in contiguous memory locations.
int[] arr = new int[5];
int[] arr = {1, 2, 3, 4, 5};
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println(number);
}
Output
10
20
30
40
50
Linked Lists consist of nodes connected by pointers. Types include singly, doubly, and circular linked lists.
class Node {
int data;
Node next;
}
class Node {
int data;
Node next;
Node(int data) { this.data = data; }
}
class LinkedList {
Node head;
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) temp = temp.next;
temp.next = newNode;
}
}
public void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
}
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(10);
list.add(20);
list.add(30);
list.display();
}
}
Output
10 20 30
Stacks use LIFO (Last-In, First-Out) order.
Stack<Integer> stack = new Stack<>();
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
System.out.println(stack.pop());
System.out.println(stack.peek());
Output
20
10
Queues use FIFO (First-In, First-Out) order.
Queue<Integer> queue = new LinkedList<>();
Queue<Integer> queue = new LinkedList<>();
queue.add(10);
queue.add(20);
System.out.println(queue.remove());
System.out.println(queue.peek());
Output
10
20
A tree is a hierarchical structure with nodes and edges.
class Node {
int data;
Node left, right;
}
class Node {
int data;
Node left, right;
public Node(int data) { this.data = data; }
}
public class Tree {
Node root;
public void inOrder(Node node) {
if (node == null) return;
inOrder(node.left);
System.out.print(node.data + " ");
inOrder(node.right);
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.inOrder(tree.root);
}
}
Output
2 1 3
Graphs consist of vertices connected by edges. They can be represented using adjacency lists or matrices.
class Graph {
private int V;
private LinkedList<Integer> adj[];
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v, int w) {
adj[v].add(w);
}
void printGraph() {
for (int i = 0; i < V; i++) {
System.out.print("Node " + i + ":");
for (Integer pCrawl : adj[i]) {
System.out.print(" -> " + pCrawl);
}
System.out.println("\n");
}
}
}
public class Main {
public static void main(String args[]) {
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.printGraph();
}
}
Output
Node 0: -> 1 -> 2
Node 1: -> 2
Node 2: -> 0 -> 3
Node 3: -> 3
Popular sorting algorithms include:
- Bubble Sort
- Selection Sort
- Merge Sort
- Quick Sort
Popular searching algorithms include:
- Linear Search
- Binary Search
String handling involves processing and modifying strings efficiently.
Hashing stores data in a structure called a hash table.
Recursion involves functions that call themselves to solve subproblems.
Dynamic Programming (DP) optimizes recursive solutions by storing subproblem results.
To excel in Java DSA:
- Focus on mastering data structures.
- Practice solving algorithmic problems.
- Use Java’s built-in libraries for efficient coding where possible.