Basic Syntax
1. Variables
Definition:
Variablesare containers for storing data values. In Java, every variable has a data type that defines the
type of data it can hold.
Syntax:
dataType variableName = value;
13.
2. Data Types
Definition:
Datatypes specify the type of data that a variable can hold. Java has two categories: primitive data
types (e.g., int, char, float, boolean) and non-primitive data types (e.g., String, Array, Class).
Primitive Data Types Syntax:
int num = 10;
char letter = 'A';
float decimal = 3.14f;
boolean flag = true;
3. Operators
Definition:
Operators are symbols that perform operations on variables and values. Java supports various operators
like arithmetic, relational, logical, and assignment operators.
14.
Syntax:
Arithmetic Operators:
int sum= a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;
Relational Operators:
boolean isEqual = a == b;
boolean isNotEqual = a != b;
boolean isGreater = a > b;
boolean isLess = a < b;
boolean isGreaterOrEqual = a >= b;
boolean isLessOrEqual = a <= b;
Logical Operators:
boolean and = (a > b) && (a < c);
boolean or = (a > b) || (a < c);
boolean not = !(a > b);
Assignment Operators:
int a = 5;
a += 3; // equivalent to a = a + 3;
a -= 2; // equivalent to a = a - 2;
a *= 4; // equivalent to a = a * 4;
a /= 2; // equivalent to a = a / 2;
a %= 3; // equivalent to a = a % 3;
Conditional Loops inJava
1. if-else Statement
Definition: The if-else statement is used to execute
different blocks of code based on whether a specific
condition is true or false.
17.
2. switch Case
Definition:The switch statement allows a variable
to be tested against multiple values (cases) and
executes the block of code corresponding to the
matching value.
18.
3. Break andContinue Keywords
Break: The break statement is used to exit a loop or
a switch statement immediately.
Continue: The continue statement skips the current
iteration of a loop and continues with the next
iteration.
19.
4. for Loop
Definition:The for loop is used for iterating over a
range of values or elements, executing a block of
code multiple times.
20.
5. while Loop
Definition:The while loop repeatedly executes a
block of code as long as a specified condition
remains true.
21.
6. do-while Loop
Definition:The do-while loop is similar to the
while loop but guarantees that the code block is
executed at least once before the condition is
checked.
Problem Solving
1. Pattern
Question:Write a program to print the following pattern:
*
**
***
****
*****
2. Palindrome Check
Question: Write a program to check if a given string is a palindrome (reads the same forward and
backward).
24.
3. Fibonacci Series
Question:Write a program to print the first 10 numbers in the Fibonacci series.
4. Prime Number
Question: Write a program to check if a given number is a prime number.
Menu-Based Code Example
Question: Write a menu-based program in Java that allows the user to perform the following
operations:
• Check if a number is prime.
• Display the first n numbers of the Fibonacci series.
• Check if a given string is a palindrome.
• Exit the program.
25.
Arrays and ArrayOperations
1. Introduction to 1D and 2D Arrays
1D Array:
Definition: A one-dimensional (1D) array is a linear collection of elements, where each element
is identified by a single index.
Example: int[] arr = {1, 2, 3, 4, 5};
2D Array:
Definition: A two-dimensional (2D) array is an array of arrays, forming a matrix with rows and
columns.
Example: int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
1. Create:
1D Array:Initialize an array and assign values.
int[] arr = new int[5]; // Create an array of size 5
arr[0] = 10; // Assign value to the first element
2D Array: Initialize a 2D array and assign values.
int[][] matrix = new int[3][3]; // Create a 3x3 matrix
matrix[0][0] = 1; // Assign value to the first element of the matrix
2. Read:
1D Array: Access elements using the index.
int value = arr[2]; // Read the value at index 2
2D Array: Access elements using row and column indices.
int value = matrix[1][1]; // Read the value at row 1, column 1
28.
3. Update:
1D Array:Modify an existing element.
arr[3] = 25; // Update the value at index 3
2D Array: Modify an existing element.
matrix[2][2] = 10; // Update the value at row 2, column 2
4. Delete:
1D Array: While you can't technically delete an element, you can set it to a default value.
arr[4] = 0; // Set the value at index 4 to 0 (or any other default value)
2D Array: Similarly, set a specific element to a default value.
matrix[0][1] = 0; // Set the value at row 0, column 1 to 0
Functions (Methods) inJava
1. Method Creation and Calling
Method Creation:
Definition: A method in Java is a block of code that performs a specific task and can be called from
other parts of the program. It must be defined within a class.
Syntax:
returnType methodName(parameters) {
// method body}
Method Calling:
Definition: To execute a method, you need to call it from another part of your code. This can be done
within the same class or from another class if the method is accessible.
Syntax:
methodName(arguments);
31.
2. Default Parameters
Definition:Java does not support default parameters directly like some other languages. However,
you can achieve similar functionality by overloading methods—creating multiple methods with the
same name but different parameters.
3. Return Type
Definition: The return type of a method specifies the type of value that the method will return to the
caller. If a method does not return a value, its return type is void.
Syntax:
returnType methodName(parameters) {
// method body
return value; // value must match the returnType
}
Recursion
Understanding Recursion andIts Use Cases
• Definition: Recursion is a programming technique where a method calls itself to solve a problem.
A recursive method typically includes a base case to stop the recursion and a recursive case to
continue it.
• Use Cases:
• Problem Solving: Recursive algorithms are useful for problems that can be broken down into
smaller, similar sub-problems. Examples include sorting algorithms (like quicksort and
mergesort), tree traversals, and mathematical problems (like factorial calculation).
• Data Structures: Recursion is often used with data structures like trees and graphs, where
problems are naturally hierarchical or interconnected.
34.
Recursive Algorithms
Factorial Calculation:
Definition:The factorial of a non-negative integer n is the product of all positive integers less than or
equal to n. It is denoted as n!.
Recursive Implementation:
public int factorial(int n) {
if (n == 0) { // Base case
return 1;
} else { // Recursive case
return n * factorial(n - 1);
}
}
35.
Fibonacci Series:
Definition: TheFibonacci sequence is a series of numbers where each number is the sum of the two
preceding ones, starting from 0 and 1. The sequence begins as 0, 1, 1, 2, 3, 5, 8, etc.
Recursive Implementation:
public int fibonacci(int n) {
if (n <= 1) { // Base case
return n;
} else { // Recursive case
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
Key Points
• Base Case: The condition under which the recursion stops to prevent infinite loops. It provides a
straightforward answer to the simplest instance of the problem.
• Recursive Case: The part of the method where the problem is divided into smaller sub-problems,
calling the method itself to solve these sub-problems.
Pointers and PointerArithmetic
• Basics of Pointers:
Definition: A pointer is a variable that holds the memory address of another variable. It allows for
dynamic memory management and manipulation of data stored at specific memory locations.
Declaration and Initialization:
int *ptr; // Declaration of a pointer to an integer
int var = 10;
ptr = &var; // Initialization: ptr now holds the address of var
• Pointer Arithmetic:
Definition: Pointer arithmetic involves performing arithmetic operations on pointers to navigate through
an array or block of memory.
Operations:
• Increment/Decrement: ptr++; // Moves the pointer to the next integer location (size of int)
ptr--; // Moves the pointer to the previous integer location
39.
• Addition/Subtraction:
ptr =ptr + 2; // Moves the pointer forward by 2 integer locations
ptr = ptr - 1; // Moves the pointer backward by 1 integer location
• Pointer Difference:
ptr1 - ptr2; // Gives the number of elements between ptr1 and ptr2
• Pointer to Pointer:
Definition: A pointer to pointer is a variable that holds the address of another pointer variable.
Declaration and Initialization:
int **ptr2Ptr; // Declaration of a pointer to a pointer to an integer
int *ptr;
int var = 10;
ptr = &var; // ptr points to var
ptr2Ptr = &ptr; // ptr2Ptr points to ptr
40.
• Pointer andArray Relationship:
Definition: In C++, an array name acts as a pointer to its first element. Array indexing and pointer
dereferencing are closely related.
Array to Pointer Conversion:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // Equivalent to int *ptr = &arr[0];
Accessing Array Elements Using Pointers:
int value = *(ptr + 2); // Accesses the third element of the array (arr[2])
Linked Lists
Concepts ofSingly, Doubly, and Circularly Linked Lists
Singly Linked List:
Definition: A singly linked list is a linear data structure where each element (node) contains a data part
and a pointer to the next node in the sequence.
Structure:
struct Node {
int data;
Node* next;
};
43.
Doubly Linked List:
Definition:A doubly linked list is a linear data structure where each node contains a data part and two
pointers: one pointing to the next node and one pointing to the previous node.
Structure:
struct Node {
int data;
Node* next;
Node* prev;
};
44.
Circular Linked List:
Definition:A circular linked list is a variation where the last node points back to the first node, creating
a circular structure.
Singly Circular:
struct Node {
int data;
Node* next;
};
Node* head; // Head points to the first node, and the last node's next points to head.
45.
Doubly Circular:
struct Node{
int data;
Node* next;
Node* prev;
};
Node* head; // Head points to the first node, and the last node's next points to head.
Stacks and Queues
Conceptand Real-World Usage
• Stacks:
• Concept: A stack is a linear data structure that follows the Last In, First Out (LIFO) principle.
The last element added to the stack is the first one to be removed.
• Real-World Usage:
• Function Call Management: In programming, the call stack keeps track of function calls and
local variables.
• Undo Mechanism: Many applications use stacks to implement undo features (e.g., text
editors).
• Expression Evaluation: Stacks are used in algorithms to evaluate expressions and parse
syntax.
50.
Queues:
• Concept: Aqueue is a linear data structure that follows the First In, First Out (FIFO) principle. The
first element added to the queue is the first one to be removed.
• Real-World Usage:
• Task Scheduling: Operating systems use queues for managing processes and tasks.
• Print Queue: Printers use queues to manage print jobs.
• Order Processing: Queues are used in various applications to handle incoming requests or orders
in the order they arrive.
51.
Implementation of Stacksand Queues
Using Arrays
&
Using Linked Lists
Operations
• Stack Operations:
• Push: Adds an element to the top of the stack.
• Pop: Removes and returns the element from the
top of the stack.
• Peek: Returns the element at the top of the stack
without removing it.
52.
• Queue Operations:
•Enqueue: Adds an element to the rear of the
queue.
• Dequeue: Removes and returns the element
from the front of the queue.
• Peek: Returns the element at the front of the
queue without removing it.
Sorting and SearchingAlgorithms
1. Introduction to Sorting Algorithms
• Bubble Sort:
A simple comparison-based sorting algorithm where adjacent elements are repeatedly compared and
swapped if they are in the wrong order.
Syntax:
55.
• Selection Sort:
Acomparison-based algorithm that divides the array into a sorted and unsorted region. It repeatedly
selects the smallest (or largest) element from the unsorted region and swaps it with the leftmost
unsorted element.
Syntax:
56.
• Insertion Sort:
Acomparison-based algorithm that builds the final sorted array one item at a time. It picks an element
from the unsorted region and inserts it into its correct position in the sorted region.
Syntax:
57.
2. Introduction toSearching Algorithms
•Linear Search:
A simple searching algorithm that checks each element in the array sequentially until the
target value is found or the end of the array is reached.
Syntax:
58.
• Binary Search:
Amore efficient searching algorithm that works on sorted arrays by repeatedly dividing the search
interval in half. It compares the target value to the middle element, and based on the comparison, it
narrows down the search range.
Syntax:
Trees
Tree Representation
Array Representation:
Concept:Trees can be represented in an array where the relationship between parent and child
nodes is maintained using indices.
Binary Tree:
Left Child: 2*i + 1
Right Child: 2*i + 2
Parent: (i - 1) / 2
63.
Linked List Representation:
Concept:Trees are represented using nodes where each node contains data and pointers to its children.
Binary Tree Node Structure:
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int value) : data(value), left(nullptr), right(nullptr) {}
};
64.
Binary Tree TraversalAlgorithms
In-order Traversal:
Concept: Visits the left subtree, the root node, and then the right subtree.
Recursive:
void inOrder(TreeNode* root) {
if (root) {
inOrder(root->left);
std::cout << root->data << " ";
inOrder(root->right);
}
}
65.
Pre-order Traversal:
Concept: Visitsthe root node, then the left subtree, and then the right subtree.
Recursive:
void preOrder(TreeNode* root) {
if (root) {
std::cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
}
66.
Post-order Traversal:
Concept: Visitsthe left subtree, then the right subtree, and finally the root node.
Recursive:
void postOrder(TreeNode* root) {
if (root) {
postOrder(root->left);
postOrder(root->right);
std::cout << root->data << " ";
}
}
67.
Level-order Traversal:
Concept: Visitsnodes level by level from top to bottom and left to right.
Iterative (using a queue):
void levelOrder(TreeNode* root) {
if (root == nullptr) return;
std::queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
std::cout << node->data << " ";
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
Time Complexity andSpace Complexity
Understanding Notations
• Big O Notation (O):
Definition: Describes the upper bound of the time complexity, representing the worst-case scenario.
Example: O(n) indicates that the algorithm's time complexity grows linearly with the input size n.
• Big Ω Notation (Ω):
Definition: Describes the lower bound of the time complexity, representing the best-case scenario.
Example: Ω(n) indicates that the algorithm's time complexity has at least a linear growth with input size
n.
• Big Θ Notation (Θ):
Definition: Describes the tight bound of the time complexity, representing both upper and lower bounds.
Example: Θ(n) indicates that the algorithm’s time complexity grows linearly with the input size n and is
bounded above and below by linear functions.
70.
• Little oNotation (o):
Definition: Describes an upper bound that is not tight; the algorithm's time complexity grows slower
than a given function.
Example: o(n^2) indicates that the growth rate is strictly less than n^2.
• Little ω Notation (ω):
Definition: Describes a lower bound that is not tight; the algorithm's time complexity grows faster than
a given function.
Example: ω(n) indicates that the growth rate is strictly more than linear.
71.
Calculating Time andSpace Complexity
Time Complexity Calculation:
Identify Basic Operations: Determine the operations that contribute most significantly to the running
time (e.g., loops, recursive calls).
Analyze Loops:
Single Loop: O(n) where n is the number of iterations.
Nested Loops: Multiply the complexities of the loops (e.g., two nested loops each running n times result
in O(n^2)).
Analyze Recursive Algorithms:
Use recurrence relations to solve (e.g., T(n) = T(n/2) + O(1) can be solved using the Master Theorem).
Example: For a loop iterating n times: for (int i = 0; i < n; i++), time complexity is O(n).
72.
Space Complexity Calculation:
IdentifySpace Usage: Calculate the additional memory used by the algorithm (e.g., variables, data
structures).
Analyze Variables: Consider the memory used by the algorithm's variables and data structures.
Recursive Space: Consider the space used by recursive calls (e.g., call stack).
Example: For an algorithm that uses an array of size n, space complexity is O(n).
73.
Examples
Linear Search:
Time Complexity:O(n) (since it checks each element once).
Space Complexity: O(1) (uses constant extra space).
Binary Search:
Time Complexity: O(log n) (searches in half of the array each step).
Space Complexity: O(1) (uses constant extra space if implemented iteratively; O(log n) for
recursive stack space).
Merge Sort:
Time Complexity: O(n log n) (divides and merges the array).
Space Complexity: O(n) (requires extra space for merging).