OBJECT-ORIENTED CONCEPTS
This program
demonstrates the following object-oriented concepts:
- Classes: Classes
are the blueprints for objects. They define the attributes and methods of
an object.
- Objects: Objects
are instances of classes. They have the attributes and methods defined by
their class.
- Constructors: Constructors are special methods that are used
to initialize objects.
- Methods: Methods
are the actions that an object can perform.
- Inheritance: Inheritance is the ability of one class to
inherit the attributes and methods of another class.
- Polymorphism: Polymorphism is the ability of an object to take
on different forms.
// This program demonstrates the object-oriented concepts
class Person {
// The `name`
attribute is a string
String name;
// The `age`
attribute is an integer
int age;
// The `Person` constructor takes the name and age of the person as parameters
Person(String
name, int age) {
// The `this` keyword refers to the current object
this.name =
name;
this.age =
age;
}
// The `greet()` method
prints a greeting message
void greet() {
System.out.println("Hello, my name is " + name);
}
// The `getAge()`
method returns the age of the person
int getAge() {
return age;
}
// The `main()` method
is the entry point of the program
static void
main(String[] args) {
// Create two
objects of the `Person` class
Person
person1 = new Person("John Doe", 30);
Person
person2 = new Person("Jane Doe", 25);
// Call the
`greet()` method on each object
person1.greet();
person2.greet();
// Print the age
of each object
System.out.println("The age of person1 is: " +
person1.getAge());
System.out.println("The age of person2 is: " +
person2.getAge());
}
}
//Java program to perform all array operations
// This program first declares an array of
integers and then prints the array. It then finds the sum, average, maximum,
and minimum of the elements in the array. The program then sorts the array in
ascending order and reverses the array. Finally, the program prints the sorted
and reversed arrays.
import java.util.Arrays;
public class ArrayOperations {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
// Print the array
System.out.println("The array is: " + Arrays.toString(arr));
// Find the sum of the elements in the array
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("The sum of the elements in the array is: "
+ sum);
// Find the average of the elements in the array
double average = sum / arr.length;
System.out.println("The average of the elements in the array is:
" + average);
// Find the maximum element in the array
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
System.out.println("The maximum element in the array is: " +
max);
// Find the minimum element in the array
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
System.out.println("The minimum element in the array is: " +
min);
// Sort the array in ascending order
Arrays.sort(arr);
System.out.println("The sorted array is: " +
Arrays.toString(arr));
// Reverse the array
int[] reversedArr = new int[arr.length];
for (int i = arr.length - 1; i >= 0; i--) {
reversedArr[arr.length - 1 - i] = arr[i];
}
System.out.println("The reversed array is: " +
Arrays.toString(reversedArr));
}
Java program to perform all linked list operations.
This
program first declares a linked list of integers and then adds elements to the
linked list. It then prints the linked list, finds the size of the linked list,
finds the first element in the linked list, finds the last element in the
linked list, and removes the first element from the linked list. Finally, the
program removes the last element from the linked list and prints the linked
list again.
import java.util.LinkedList;
public class LinkedListOperations {
public static void main(String[] args) {
LinkedList<Integer> linkedList = new LinkedList<Integer>();
// Add elements to the linked list
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
linkedList.add(4);
linkedList.add(5);
// Print the linked list
System.out.println("The linked list is: " + linkedList);
// Find the size of the linked list
int size = linkedList.size();
System.out.println("The size of the linked list is: " + size);
// Find the first element in the linked list
Integer firstElement = linkedList.getFirst();
System.out.println("The first element in the linked list is: "
+ firstElement);
// Find the last element in the linked list
Integer lastElement = linkedList.getLast();
System.out.println("The last element in the linked list is: "
+ lastElement);
// Remove the first element from the linked list
linkedList.removeFirst();
System.out.println("The linked list after removing the first
element is: " + linkedList);
// Remove the last element from the linked list
linkedList.removeLast();
System.out.println("The linked list after removing the last element
is: " + linkedList);
}
}
Java program to create a singly linked list
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
LinkedList() {
this.head = null;
}
void addNode(int data)
{
Node newNode = new
Node(data);
if (this.head == null) {
this.head = newNode;
} else {
Node currentNode =
this.head;
while
(currentNode.next != null) {
currentNode = currentNode.next;
}
currentNode.next = newNode;
}
}
void printList() {
Node currentNode =
this.head;
while (currentNode !=
null) {
System.out.println(currentNode.data);
currentNode =
currentNode.next;
}
}
public static void
main(String[] args) {
LinkedList list = new
LinkedList();
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.printList();
}
}
This program creates a
singly linked list and adds three nodes to it. The nodes contain the data 1, 2,
and 3. The program then prints the list, which should print the following
output:
1
2
3
Java program to create a doubly linked list
// A doubly linked list node
class Node {
int data;
Node prev;
Node next;
// Constructor
Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
// A doubly linked list
class DoublyLinkedList {
// Head of the list
Node head;
// Tail of the list
Node tail;
// Constructor
DoublyLinkedList() {
this.head = null;
this.tail = null;
}
// Add a node to the list
void addNode(int data) {
// Create a new node
Node newNode = new Node(data);
// If the list is empty, make the new
node the head and tail
if (this.head == null) {
this.head = newNode;
this.tail = newNode;
} else {
// Otherwise, add the new node
after the tail
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
}
// Print the list
void printList() {
// Start at the head of the list
Node currentNode = this.head;
// Print the data in each node
while (currentNode != null) {
System.out.println(currentNode.data);
currentNode = currentNode.next;
}
}
public static void main(String[] args) {
// Create a doubly linked list
DoublyLinkedList list = new DoublyLinkedList();
// Add three nodes to the list
list.addNode(1);
list.addNode(2);
list.addNode(3);
// Print the list
list.printList();
}
}
This
program creates a doubly linked list and adds three nodes to it. The nodes
contain the data 1, 2, and 3. The program then prints the list, which should
print the following output:
1
2
3
Java program to create a circular linked list
// A node in a circular linked list
class Node {
int data;
Node next;
// Constructor
Node(int data) {
this.data = data;
this.next = null;
}
}
// A circular linked list
class CircularLinkedList {
// The head of the list
Node head;
// Constructor
CircularLinkedList() {
this.head = null;
}
// Add a node to the list
void addNode(int data) {
// Create a new node
Node newNode = new Node(data);
// If the list is empty, make the new
node the head and tail
if (this.head == null) {
this.head = newNode;
newNode.next = this.head;
} else {
// Otherwise, find the tail of the
list and add the new node after it
Node currentNode = this.head;
while (currentNode.next !=
this.head) {
currentNode = currentNode.next;
}
currentNode.next = newNode;
newNode.next = this.head;
}
}
// Print the list
void printList() {
// Start at the head of the list
Node currentNode = this.head;
// Print the data in each node
do {
System.out.println(currentNode.data);
currentNode = currentNode.next;
} while (currentNode != this.head);
}
public static void main(String[] args) {
// Create a circular linked list
CircularLinkedList list = new CircularLinkedList();
// Add three nodes to the list
list.addNode(1);
list.addNode(2);
list.addNode(3);
// Print the list
list.printList();
}
}
The do-while
loop in
the printList()
method
ensures that we print the data in all the nodes in the list, even the last
node, which points back to the head.
Java program to perform stack and queue operations.
This program first declares a stack and a queue
of integers. It then pushes and enqueues elements into the stack and queue,
respectively. The program then prints the stack and queue, pops and dequeues
elements from the stack and queue, respectively, and checks if the stack and
queue are empty.
import java.util.Stack;
import java.util.Queue;
public class StackQueueOperations {
public static void main(String[] args) {
// Create a stack
Stack<Integer> stack = new Stack<Integer>();
// Push elements onto the stack
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
// Print the stack
System.out.println("The stack is: " + stack);
// Pop elements from the stack
Integer poppedElement = stack.pop();
System.out.println("The popped element is: " + poppedElement);
poppedElement = stack.pop();
System.out.println("The popped element is: " + poppedElement);
// Check if the stack is empty
boolean isEmpty = stack.isEmpty();
System.out.println("The stack is empty: " + isEmpty);
// Create a queue
Queue<Integer> queue = new LinkedList<Integer>();
// Enqueue elements into the queue
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
queue.add(5);
// Print the queue
System.out.println("The
queue is: " + queue);
// Dequeue elements from the queue
Integer dequeuedElement =
queue.remove();
System.out.println("The dequeued element is: " +
dequeuedElement);
dequeuedElement =
queue.remove();
System.out.println("The
dequeued element is: " + dequeuedElement);
// Check if the queue is empty
isEmpty = queue.isEmpty();
System.out.println("The queue is empty: " + isEmpty);
}
}
Java program to perform priority queue operations.
This
program first declares a priority queue of integers. It then adds elements to
the priority queue, prints the priority queue, removes the element with the
highest priority, and checks if the priority queue is empty.
import
java.util.PriorityQueue;
public class PriorityQueueOperations {
public static void main(String[] args) {
// Create a priority queue
PriorityQueue<Integer> priorityQueue = new
PriorityQueue<Integer>();
// Add elements to the priority queue
priorityQueue.add(10);
priorityQueue.add(5);
priorityQueue.add(1);
priorityQueue.add(7);
priorityQueue.add(3);
// Print the priority queue
System.out.println("The priority queue is: " +
priorityQueue);
// Remove the element with the highest priority
Integer highestPriorityElement = priorityQueue.poll();
System.out.println("The element with the highest
priority is: " + highestPriorityElement);
// Check if the priority queue is empty
boolean isEmpty = priorityQueue.isEmpty();
System.out.println("The priority queue is empty: "
+ isEmpty);
}
}
Java program to reverse a linked list
public class
Linked_List {
static Node head;
static class Node {
int data;
Node next;
Node (int value) {
data = value;
next = null;
}
}
// display the list
static void printList(Node node) {
System.out.print("\n[");
//start from the beginning
while(node != null) {
System.out.print(" " +
node.data + " ");
node = node.next;
}
System.out.print("]");
}
static Node reverseList(Node head) {
Node prev = null;
Node cur = head;
Node temp = null;
while (cur != null) {
temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
head = prev;
return head;
}
public static void main(String args[]) {
Linked_List list = new Linked_List();
list.head = new Node(33);
list.head.next = new Node(50);
list.head.next.next = new Node(44);
list.head.next.next.next = new Node(22);
list.head.next.next.next.next = new
Node(12);
System.out.println("Linked List:
");
// print list
list.printList(head);
head = list.reverseList(head);
System.out.println("\nReversed
linked list ");
list.printList(head);
}
}
================
create a doubly linked list and print all the nodes present
in the list.
public class DoublyLinkedList {
//Represent a node of the doubly linked
list
class Node{
int data;
Node previous;
Node
next;
public Node(int data) {
this.data
= data;
}
}
//Represent the
head and tail of the doubly linked list
Node head, tail =
null;
//addNode() will
add a node to the list
public void
addNode(int data) {
//Create a new
node
Node newNode =
new Node(data);
//If list is
empty
if(head ==
null) {
//Both
head and tail will point to newNode
head =
tail = newNode;
//head's
previous will point to null
head.previous = null;
//tail's
next will point to null, as it is the last node of the list
tail.next
= null;
}
else {
//newNode
will be added after tail such that tail's next will point to newNode
tail.next
= newNode;
//newNode's previous will point to tail
newNode.previous = tail;
//newNode will become new tail
tail =
newNode;
//As it is last node, tail's next will point
to null
tail.next
= null;
}
}
//display() will
print out the nodes of the list
public void
display() {
//Node current
will point to head
Node current =
head;
if(head ==
null) {
System.out.println("List is empty");
return;
}
System.out.println("Nodes of doubly linked list: ");
while(current
!= null) {
//Prints
each node by incrementing the pointer.
System.out.print(current.data + " ");
current =
current.next;
}
}
public static void
main(String[] args) {
DoublyLinkedList dList = new DoublyLinkedList();
//Add nodes to
the list
dList.addNode(1);
dList.addNode(2);
dList.addNode(3);
dList.addNode(4);
dList.addNode(5);
//Displays the
nodes present in the list
dList.display();
}
}
==========================
Try Linked List here
https://www.w3schools.com/java/java_linkedlist.asp
==============
Java program that uses the Hashtable class:
public class HashtableDemo {
public static void main(String[] args) {
Hashtable<Integer, String> hashtable = new Hashtable<>();
hashtable.put(1, "One");
hashtable.put(2, "Two");
hashtable.put(3, "Three");
String value = hashtable.get(2);
System.out.println("The value for key 2 is: " + value);
for (Integer key : hashtable.keySet()) {
String value1 = hashtable.get(key);
System.out.println("The value for key " + key + " is: " + value1);
}
}
}
==================================================
Java program to implement Dijkstra's algorithm
import
java.util.*;
public
class Dijkstra {
static class Node {
int vertex;
int distance;
Node(int vertex, int distance) {
this.vertex = vertex;
this.distance = distance;
}
}
public static void main(String[] args) {
// Create a graph
Map<Integer, List<Node>>
graph = new HashMap<>();
graph.put(0, Arrays.asList(new Node(1,
10), new Node(2, 5)));
graph.put(1, Arrays.asList(new Node(2,
3)));
graph.put(2, Arrays.asList());
// Initialize the distances
int[] distances = new int[3];
Arrays.fill(distances,
Integer.MAX_VALUE);
// Set the distance of the source
vertex to 0
distances[0] = 0;
// Create a priority queue to store the
vertices
PriorityQueue<Node> pq = new
PriorityQueue<>((n1, n2) -> n1.distance - n2.distance);
pq.add(new Node(0, 0));
// While the priority queue is not
empty
while (!pq.isEmpty()) {
// Get the vertex with the minimum
distance
Node currentVertex = pq.poll();
// For each neighbor of the current
vertex
for (Node neighbor :
graph.get(currentVertex.vertex)) {
// If the distance to the
neighbor is less than the current distance
if (distances[neighbor.vertex]
> currentVertex.distance + neighbor.distance) {
// Update the distance to the
neighbor
distances[neighbor.vertex]
= currentVertex.distance + neighbor.distance;
// Add the neighbor to the
priority queue
pq.add(new
Node(neighbor.vertex, distances[neighbor.vertex]));
}
}
}
// Print the distances
System.out.println(Arrays.toString(distances));
}
}
The above program first creates a graph. The graph is a map of vertices to lists of neighbors. Each neighbor has a distance
associated with it.
The program then initializes the distances to all vertices to infinity. The
distance of the source vertex is set to 0.
The program then creates a priority queue to store the vertices. The priority queue
is sorted by the distance of each vertex.
The program then iterates through the priority queue. For each vertex in the
priority queue, the program iterates through its neighbors. If the distance to
a neighbor is less than the current distance, the program updates the distance
to the neighbor. The program then adds the neighbor to the priority queue. The
program continues iterating through the priority queue until the priority queue
is empty.
Finally, the program prints the distances.
Java program to implement static Huffman coding:
import
java.util.*;
public
class HuffmanCoding {
static class Node implements
Comparable<Node> {
int frequency;
char character;
Node left;
Node right;
Node(int frequency, char character) {
this.frequency = frequency;
this.character = character;
this.left = null;
this.right = null;
}
@Override
public int compareTo(Node other) {
return this.frequency -
other.frequency;
}
}
public static void main(String[] args) {
// Create a map of characters to
frequencies
Map<Character, Integer>
frequencies = new HashMap<>();
for (char c = 'a'; c <= 'z'; c++) {
frequencies.put(c, 0);
}
// Read the input text and update the
frequencies
Scanner scanner = new
Scanner(System.in);
while (scanner.hasNext()) {
char c = scanner.next().charAt(0);
frequencies.put(c,
frequencies.get(c) + 1);
}
// Create a priority queue to store the
nodes
PriorityQueue<Node> pq = new
PriorityQueue<>();
for (Character c :
frequencies.keySet()) {
Node node = new
Node(frequencies.get(c), c);
pq.add(node);
}
// While the priority queue is not empty
while (pq.size() > 1) {
// Get the two nodes with the
minimum frequencies
Node left = pq.poll();
Node right = pq.poll();
// Create a new node with the sum
of the frequencies of the two nodes
Node parent = new
Node(left.frequency + right.frequency, '\0');
// Add the new node to the priority
queue
parent.left = left;
parent.right = right;
pq.add(parent);
}
// Get the root of the Huffman tree
Node root = pq.poll();
// Create a map of characters to codes
Map<Character, String> codes =
new HashMap<>();
traverse(root, "", codes);
// Print the codes
for (Character c :
frequencies.keySet()) {
System.out.println(c + ":
" + codes.get(c));
}
}
private static void traverse(Node node,
String code, Map<Character, String> codes) {
if (node.character != '\0') {
codes.put(node.character, code);
} else {
traverse(node.left, code +
"0", codes);
traverse(node.right, code +
"1", codes);
}
}
}
The above program first creates a map of characters to frequencies. The program
then reads the input text and updates the frequencies.
The program then creates a priority queue to store the nodes. The priority queue is
sorted by the frequency of each node.
The program then iterates through the priority queue. For each node in the priority
queue, the program creates a new node with the sum of the frequencies of the
two nodes. The program then adds the new node to the priority queue.
The program continues iterating through the priority queue until the priority queue
is empty.
The program then gets the root of the Huffman tree and creates a map of characters
to codes. The program traverses the Huffman tree and stores the codes for each
character in the map. Finally, the program prints the codes.
===================