Java Programs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

1) // Java Program to find the solutions of specified equations

public class GFG {

// Method to check for solutions of equations


static void checkSolution(int a, int b, int c)
{

// If the expression is greater than 0,


// then 2 solutions
if (((b * b) - (4 * a * c)) > 0)
System.out.println("2 solutions");

// If the expression is equal 0, then 2 solutions


else if (((b * b) - (4 * a * c)) == 0)
System.out.println("1 solution");

// Else no solutions
else
System.out.println("No solutions");
}

// Driver Code
public static void main(String[] args)
{
int a = 2, b = 5, c = 2;
checkSolution(a, b, c);
}
}

2) // Java Code for Linked List Implementation

public class StackAsLinkedList {

StackNode root;
static class StackNode {

int data;

StackNode next;

StackNode(int data) { this.data = data; }

public boolean isEmpty()

if (root == null) {

return true;

else

return false;

public void push(int data)

StackNode newNode = new StackNode(data);


if (root == null) {

root = newNode;

else {

StackNode temp = root;

root = newNode;

newNode.next = temp;

System.out.println(data + " pushed to stack");

public int pop()

int popped = Integer.MIN_VALUE;

if (root == null) {

System.out.println("Stack is Empty");

else {

popped = root.data;

root = root.next;

return popped;
}

public int peek()

if (root == null) {

System.out.println("Stack is empty");

return Integer.MIN_VALUE;

else {

return root.data;

// Driver code

public static void main(String[] args)

StackAsLinkedList sll = new StackAsLinkedList();

sll.push(10);

sll.push(20);

sll.push(30);
System.out.println(sll.pop()

+ " popped from stack");

System.out.println("Top element is " + sll.peek());

Output
10 pushed to stack
20 pushed to stack
30 pushed to stack
30 popped from stack
Top element is 20
Elements present in stack : 20 10

4a) // Java program to implement a queue using an array

class Queue {

static private int front, rear, capacity;

static private int queue[];

Queue(int c)
{

front = rear = 0;

capacity = c;

queue = new int[capacity];

// function to insert an element

// at the rear of the queue

static void queueEnqueue(int data)

// check queue is full or not

if (capacity == rear) {

System.out.printf("\nQueue is full\n");

return;

// insert element at the rear

else {

queue[rear] = data;

rear++;

return;
}

// function to delete an element

// from the front of the queue

static void queueDequeue()

// if queue is empty

if (front == rear) {

System.out.printf("\nQueue is empty\n");

return;

// shift all the elements from index 2 till rear

// to the right by one

else {

for (int i = 0; i < rear - 1; i++) {

queue[i] = queue[i + 1];

// store 0 at rear indicating there's no element

if (rear < capacity)

queue[rear] = 0;
// decrement rear

rear--;

return;

// print queue elements

static void queueDisplay()

int i;

if (front == rear) {

System.out.printf("\nQueue is Empty\n");

return;

// traverse front to rear and print elements

for (i = front; i < rear; i++) {

System.out.printf(" %d <-- ", queue[i]);

return;

}
// print front of queue

static void queueFront()

if (front == rear) {

System.out.printf("\nQueue is Empty\n");

return;

System.out.printf("\nFront Element is: %d",

queue[front]);

return;

public class StaticQueueinjava {

// Driver code

public static void main(String[] args)

// Create a queue of capacity 4

Queue q = new Queue(4);


// print Queue elements

q.queueDisplay();

// inserting elements in the queue

q.queueEnqueue(20);

q.queueEnqueue(30);

q.queueEnqueue(40);

q.queueEnqueue(50);

// print Queue elements

q.queueDisplay();

// insert element in the queue

q.queueEnqueue(60);

// print Queue elements

q.queueDisplay();

q.queueDequeue();

q.queueDequeue();

System.out.printf(
"\n\nafter two node deletion\n\n");

// print Queue elements

q.queueDisplay();

// print front of the queue

q.queueFront();

Output
Queue is Empty
20 <-- 30 <-- 40 <-- 50 <--
Queue is full
20 <-- 30 <-- 40 <-- 50 <--

after two node deletion

40 <-- 50 <--
Front Element is: 40

6) // Java program to multiply

// two matrices of any size.


import java.io.*;

// Driver Class

class GFG {

// Function to print Matrix

static void printMatrix(int M[][], int rowSize,

int colSize)

for (int i = 0; i < rowSize; i++) {

for (int j = 0; j < colSize; j++)

System.out.print(M[i][j] + " ");

System.out.println();

// Function to multiply

// two matrices A[][] and B[][]

static void multiplyMatrix(int row1, int col1,

int A[][], int row2,

int col2, int B[][])

{
int i, j, k;

// Print the matrices A and B

System.out.println("\nMatrix A:");

printMatrix(A, row1, col1);

System.out.println("\nMatrix B:");

printMatrix(B, row2, col2);

// Check if multiplication is Possible

if (row2 != col1) {

System.out.println(

"\nMultiplication Not Possible");

return;

// Matrix to store the result

// The product matrix will

// be of size row1 x col2

int C[][] = new int[row1][col2];


// Multiply the two matrices

for (i = 0; i < row1; i++) {

for (j = 0; j < col2; j++) {

for (k = 0; k < row2; k++)

C[i][j] += A[i][k] * B[k][j];

// Print the result

System.out.println("\nResultant Matrix:");

printMatrix(C, row1, col2);

// Driver code

public static void main(String[] args)

int row1 = 4, col1 = 3, row2 = 3, col2 = 4;

int A[][] = { { 1, 1, 1 },

{ 2, 2, 2 },

{ 3, 3, 3 },
{ 4, 4, 4 } };

int B[][] = { { 1, 1, 1, 1 },

{ 2, 2, 2, 2 },

{ 3, 3, 3, 3 } };

multiplyMatrix(row1, col1, A, row2, col2, B);

Output
Matrix A:
1 1 1
2 2 2
3 3 3
4 4 4

Matrix B:
1 1 1 1
2 2 2 2
3 3 3 3

Resultant Matrix:
6 6 6 6
12 12 12 12
18 18 18 18
24 24 24 24
7b) // Optimized java implementation of Bubble sort

import java.io.*;

class GFG {

// An optimized version of Bubble Sort

static void bubbleSort(int arr[], int n)

int i, j, temp;

boolean swapped;

for (i = 0; i < n - 1; i++) {

swapped = false;

for (j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// Swap arr[j] and arr[j+1]

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

swapped = true;
}

// If no two elements were

// swapped by inner loop, then break

if (swapped == false)

break;

// Function to print an array

static void printArray(int arr[], int size)

int i;

for (i = 0; i < size; i++)

System.out.print(arr[i] + " ");

System.out.println();

// Driver program

public static void main(String args[])

{
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };

int n = arr.length;

bubbleSort(arr, n);

System.out.println("Sorted array: ");

printArray(arr, n);

// This code is contributed

Output
Sorted array:
11 12 22 25 34 64 90

9) // Java program for the above approach

import java.util.*;

class GFG{

// Function to calculate

// factorial of N

static int fact(int n)

{
// Base Case

if (n == 1 || n == 0)

return 1;

// Otherwise, recursively

// calculate the factorial

else

return n * fact(n - 1);

// Function to find the value of

// P(n + r) for polynomial P(X)

static int findValue(int n, int r, int a)

// Stores the value of k

int k = (a - 1) / fact(n);

// Store the required answer

int answer = k;
// Iterate in the range [1, N] and

// multiply (n + r - i) with answer

for(int i = 1; i < n + 1; i++)

answer = answer * (n + r - i);

// Add the constant value C as 1

answer = answer + 1;

// Return the result

return answer;

// Driver Code

public static void main(String args[])

int N = 1;

int A = 2;

int R = 3;

System.out.print(findValue(N, R, A));

}
}

Output:
4

10) // Java code for thread creation by extending

// the Thread class

class MultithreadingDemo extends Thread {

public void run()

try {

// Displaying the thread that is running

System.out.println(

"Thread " + Thread.currentThread().getId()

+ " is running");

catch (Exception e) {

// Throwing an exception

System.out.println("Exception is caught");

}
}

// Main Class

public class Multithread {

public static void main(String[] args)

int n = 8; // Number of threads

for (int i = 0; i < n; i++) {

MultithreadingDemo object

= new MultithreadingDemo();

object.start();

Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
11)
// Java Program to Illustrate binarySearch() method

// of Collections class

// Importing required classes

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

// Main class

public class GFG {

// Main driver method

public static void main(String[] args)

// Creating empty List

List<Integer> al = new ArrayList<Integer>();

// Adding elements to the List

al.add(12);

al.add(53);
al.add(23);

al.add(46);

al.add(54);

// Using binarySearch() method of Collections class

// over random inserted element and storing the

// index

int index = Collections.binarySearch(al, 23);

// Print and display the index

System.out.print(index);

Output
2

13) // Java program to demonstrate working of

// interface

import java.io.*;
// A simple interface

interface In1 {

// public, static and final

final int a = 10;

// public and abstract

void display();

// A class that implements the interface.

class TestClass implements In1 {

// Implementing the capabilities of

// interface.

public void display(){

System.out.println("Geek");

// Driver Code

public static void main(String[] args)


{

TestClass t = new TestClass();

t.display();

System.out.println(a);

Output
Geek
10

You might also like