[Go to site: main page, start]

0% found this document useful (0 votes)
1 views15 pages

Java Programs

The document contains multiple Java programs demonstrating various programming concepts including a basic calculator, factorial calculation, Fibonacci series, palindrome check, permutation and combination, pattern printing, binary search, heap sort, ArrayList manipulation, HashMap implementation, and matrix transposition. Each program includes code snippets and example outputs. The programs serve as practical examples for learning Java programming and algorithms.

Uploaded by

tanyafds
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views15 pages

Java Programs

The document contains multiple Java programs demonstrating various programming concepts including a basic calculator, factorial calculation, Fibonacci series, palindrome check, permutation and combination, pattern printing, binary search, heap sort, ArrayList manipulation, HashMap implementation, and matrix transposition. Each program includes code snippets and example outputs. The programs serve as practical examples for learning Java programming and algorithms.

Uploaded by

tanyafds
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Program 1. Write a Java program to perform basic Calculator operations.

import [Link];
public class Calculator {
public static void main(String[] args) {
Scanner reader = new Scanner([Link]);
[Link]("Enter two numbers: ");
// nextDouble() reads the next double from the keyboard
double first = [Link]();
double second = [Link]();
[Link]("Enter an operator (+, -, *, /): ");
char operator = [Link]().charAt(0);
double result;
//switch case for each of the operations
switch(operator)
{
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
// operator doesn't match any case constant (+, -, *, /)

default:
[Link]("Error! operator is not correct");
return;
}
//printing the result of the operations
[Link]("%.1f %c %.1f = %.1f", first, operator, second, result);
}
}
When you execute the above program, the output looks like as shown below:
1 Enter two numbers: 20 98
2 Enter an operator (+, -, *, /): /
3 20.0 / 98.0 = 0.2

1
Program 2. Write a simple Java program to calculate a Factorial of a
number.
import [Link];
public class Factorial {
public static void main(String args[]){
//Scanner object for capturing the user input
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number:");
//Stored the entered value in variable
int num = [Link]();
//Called the user defined function fact
int factorial = fact(num);
[Link]("Factorial of entered number is: "+factorial);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}

On executing the above program, you will get factorial of a number as shown below:
1Enter the number:
212
3Factorial of entered number is: 47900160

2
Program 3. Write a simple Java program to calculate Fibonacci Series up
to n numbers.
public class Fibonacci {
public static void main(String[] args) {
//initializing the constants
int n = 100, t1 = 0, t2 = 1;
[Link]("Upto " + n + ": ");
//while loop to calculate fibonacci series upto n numbers
while (t1<= n)
{
[Link](t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}

On executing the above code, the output looks like :


1Upto 100: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 +

3
Program 4. Write a Java program to find out whether the given String is
Palindrome or not.
1. import [Link];
2. public class Palindrome {
3. static void checkPalindrome(String input) {
4. //Assuming result to be true
5. boolean res = true;
6. int length = [Link]();
7. //dividing the length of the string by 2 and comparing it.
8. for(int i=0; i<= length/2; i++) {
9. if([Link](i) != [Link](length-i-1)) {
10. res = false;
11. break;
12. }
13. }
14. [Link](input + " is palindrome = "+res);
15. }
16. public static void main(String[] args) {
17. Scanner sc = new Scanner([Link]);
18. [Link]("Enter your Statement: ");
19. String str = [Link]();
20. //function call
21. checkPalindrome(str);
22. }
23. }

When y When you run the code, it will check whether the given string is a palindrome or not
as shown below:
1Enter your Statement: RACECAR
2RACECAR is palindrome = true
3
4Enter your Statement: EDUREKA
5EDUREKA is palindrome = false
ou run the code, it will check whether the given string is a palindrome or not as shown below:
Enter your Statement: RACECAR
RACECAR

1
2 is palindrome = true
3
4Enter your Statement: EDUREKA
5EDUREKA is palindrome = false

4
Program 5. Write a Java program to calculate Permutation and
Combination of 2 numbers.
import [Link];
public class nprandncr {
//calculating a factorial of a number
public static int fact(int num)
{
int fact=1, i;
for(i=1; i<=num; i++)
{
fact = fact*i;
}
return fact;
}
public static void main(String args[])
{
int n, r;
Scanner scan = new Scanner([Link]);
[Link]("Enter Value of n : ");
n = [Link]();
[Link]("Enter Value of r : ");
r = [Link]();
// NCR and NPR of a number
[Link]("NCR = " +(fact(n)/(fact(n-r)*fact(r))));
[Link]("nNPR = " +(fact(n)/(fact(n-r))));
}
}

On executing the above code, the output looks like as shown below:
1 Enter Value of n : 5
2 Enter Value of r : 3
3 NCR = 10
4 NPR = 60

5
Program 6. Write a program in Java to find out Alphabet and Diamond
Pattern.

import [Link];
public class PatternA {
// Java program to print alphabet A pattern
void display(int n)
{
// Outer for loop for number of lines
for (int i = 0; i<=n; i++) {
// Inner for loop for logic execution
for (int j = 0; j<= n / 2; j++) {
// prints two column lines
if ((j == 0 || j == n / 2) && i != 0 ||
// print first line of alphabet
i == 0 && j != n / 2 ||
// prints middle line
i == n / 2)
[Link]("*");
else
[Link](" ");
}
[Link]();
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
PatternA a = new PatternA();
[Link](7);
}
}

Output:

6
Program 7. Diamond Pattern Program in Java
import [Link];
public class DiamondPattern
{
public static void main(String args[])
{
int n, i, j, space = 1;
[Link]("Enter the number of rows: ");
Scanner s = new Scanner([Link]);
n = [Link]();
space = n - 1;
for (j = 1; j<= n; j++)
{
for (i = 1; i<= space; i++)
{
[Link](" ");
}
space--;
for (i = 1; i <= 2 * j - 1; i++)
{
[Link]("*");
}
[Link]("");
}
space = 1;
for (j = 1; j<= n - 1; j++)
{
for (i = 1; i<= space; i++)
{
[Link](" ");
}
space++;
for (i = 1; i<= 2 * (n - j) - 1; i++)
{
[Link]("*");
}
[Link]("");}}
Output:
Enter the number of rows: 5
*
***
*****
*******
*********
*******
*****
***
*

7
Program 8. Write a Java program to implement a Binary Search
Algorithm.

public class BinarySearch {


// Java implementation of recursive Binary Search
// Returns index of x if it is present in arr[l..
// r], else return -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the
// middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] >x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not present
// in array
return -1;
}
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int arr[] = { 2, 3, 4, 10, 40 };
int n = [Link];
int x = 40;
int result = [Link](arr, 0, n - 1, x);
if (result == -1)
[Link]("Element not present");
else
[Link]("Element found at index " + result);
}
}
On executing the above program, it will locate the element present at the particular index

1Element found at index 4

8
Program 9. Write a Java program to implement HeapSort Algorithm.

public class HeapSort


{
public void sort(int arr[])
{
int n = [Link];
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--)
{
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l< n && arr[l] >arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = [Link];
for (int i=0; i<n; ++i)
[Link](arr[i]+" ");

9
[Link]();
}
// Driver program
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = [Link];
HeapSort ob = new HeapSort();
[Link](arr);
[Link]("Sorted array is");
printArray(arr);
}
}
Output:

15,6,7,11,12,13

10
Program 10. Write a Java program to remove elements from an ArrayList.

import [Link];
import [Link];
import [Link];

public class ArrayListExample {


public static void main(String[] args) {
List<String> programmingLanguages = new ArrayList<>();
[Link]("C");
[Link]("C++");
[Link]("Java");
[Link]("Kotlin");
[Link]("Python");
[Link]("Perl");
[Link]("Ruby");

[Link]("Initial List: " + programmingLanguages);

// Remove the element at index `5`


[Link](5);
[Link]("After remove(5): " + programmingLanguages);

// Remove the first occurrence of the given element from the ArrayList
// (The remove() method returns false if the element does not exist in the ArrayList)
boolean isRemoved = [Link]("Kotlin");
[Link]("After remove(\"Kotlin\"): " + programmingLanguages);

// Remove all the elements that exist in a given collection


List<String> scriptingLanguages = new ArrayList<>();
[Link]("Python");
[Link]("Ruby");
[Link]("Perl");

[Link](scriptingLanguages);
[Link]("After removeAll(scriptingLanguages): " + programmingLanguages);

// Remove all the elements that satisfy the given predicate


[Link](new Predicate<String>() {
@Override
public boolean test(String s) {
return [Link]("C");
}
});

[Link]("After Removing all elements that start with \"C\": " +


programmingLanguages);

11
// Remove all elements from the ArrayList
[Link]();
[Link]("After clear(): " + programmingLanguages);
}
}

Output on execution of the program looks like:

1Initial List: [C, C++, Java, Kotlin, Python, Perl, Ruby]


2After remove(5): [C, C++, Java, Kotlin, Python, Ruby]
3After remove("Kotlin"): [C, C++, Java, Python, Ruby]
4After removeAll(scriptingLanguages): [C, C++, Java]
5After Removing all elements that start with "C": [Java]
6After clear(): []

12
Program 11. Write a program in Java to implement HashMap.

import [Link];
import [Link];

public class Hashmap


{
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<>();
print(map);
[Link]("abc", 10);
[Link]("mno", 30);
[Link]("xyz", 20);

[Link]("Size of map is" + [Link]());

print(map);
if ([Link]("abc"))
{
Integer a = [Link]("abc");
[Link]("value for key \"abc\" is:- " + a);
}
[Link]();
print(map);
}
public static void print(Map<String, Integer> map)
{
if ([Link]())
{
[Link]("map is empty");
}
else
{
[Link](map);
}
}
}
On executing the HashMap program, output goes like this:

1map is empty
2Size of map is:- 3
3{abc=10, xyz=20, mno=30}
4value for key "abc" is:- 10
5map is empty

13
Program 12. Write a Java Program to find the Transpose of a given
Matrix.

public class Transpose


{
static final int N = 4;

// This function stores transpose


// of A[][] in B[][]
static void transpose(int A[][], int B[][])
{
int i, j;
for (i = 0; i< N; i++)
for (j = 0; j <N; j++)
B[i][j] = A[j][i];
}

public static void main (String[] args)


{
int A[][] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};

int B[][] = new int[N][N], i, j;

transpose(A, B);

[Link]("Result matrix is n");


for (i = 0; i<N; i++)
{
for (j = 0; j<N; j++)
[Link](B[i][j] + " ");4
[Link]("n");
}
}
}
On executing the above program, output goes like this:

1Result matrix is
21 2 3 4
31 2 3 4
41 2 3 4
51 2 3 4

14
15

You might also like