0% found this document useful (0 votes)
24 views

Coding Questions IN JAVA

Uploaded by

khushi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Coding Questions IN JAVA

Uploaded by

khushi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Write a code to reverse a number

JAVA
import java.util.Scanner;

public class reverse_of_number

public static void main(String[] args)

//scanner class declaration

Scanner sc = new Scanner(System.in);

//input from user

System.out.print("Enter a number : ");

int number = sc.nextInt();

System.out.print("Reverse of "+number+" is ");

int reverse = 0;

String s = "";

while(number != 0)

int pick_last = number % 10;

//use function to convert pick_last from integer to string

s = s + Integer.toString(pick_last);

number = number / 10;

//display the reversed number

System.out.print(s);

//closing scanner class(not compulsory, but good practice)

sc.close();

}
Write the code to find the Fibonacci series upto the
nth term.
C

JAVA
public class Main
{
public static void main (String[]args)
{

int num = 15;


int a = 0, b = 1;

// Here we are printing 0th and 1st terms


System.out.print (a + " , " + b + " , ");

int nextTerm;

// printing the rest of the terms here


for (int i = 2; i < num; i++)
{
nextTerm = a + b;
a = b;
b = nextTerm;
System.out.print (nextTerm + " , ");
}

}
}

Write code of Greatest Common Divisor


C

JAVA
import java.util.Scanner;
public class gcd_or_hcf
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from the user
System.out.print("Enter the first number : ");
int num1 = sc.nextInt();
//input from the user
System.out.print("Enter the second number : ");
int num2 = sc.nextInt();
int n = 1;
System.out.print("HCF of "+num1+" and "+num2+" is ");
if( num1 != num2)
{
while(n != 0)
{
//storing remainder
n = num1 % num2;
if(n != 0)
{
num1 = num2;
num2 = n;
}
}
//result
System.out.println(num2);
}
else
System.out.println("Wrong Input");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Write code of Perfect number


C

JAVA
import java.util.Scanner;
public class perfect_number_or_not
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");
int number = sc.nextInt();
//declare a variable to store sum of factors
int sum = 0;
for(int i = 1 ; i < number ; i++)
{
if(number % i == 0)
sum = sum + i;
}
//comparing whether the sum is equal to the given number or not
if(sum == number)
System.out.println("Perfect Number");
else
System.out.println("Not an Perfect Number");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Write code to Check if two strings are Anagram or not


C

JAVA
import java.util.Arrays;
import java.util.Scanner;
public class CheckIfTwoStringsAreAnagramAreNot {
static boolean isAnagram(String str1 , String str2) {
String s1 = str1.replaceAll("[\\s]", "");
String s2 = str2.replaceAll("[\\s]", "");
boolean status=true;

if(s1.length()!=s2.length())
status = false;
else {
char[] a1 = s1.toLowerCase().toCharArray();
char[] a2 = s2.toLowerCase().toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
status = Arrays.equals(a1, a2);
}
return status;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two String :");
String s1 = sc.next();
String s2 = sc.next();
boolean status = isAnagram(s1,s2);
if(status)
System.out.println(s1+" and "+s2+" are Anagram");
else
System.out.println(s1+" and "+s2+" are not Anagram");
}
}

Write code Check if the given string is Palindrome or


not
C

JAVA
import java.util.Scanner;

public class StringIsAPalindromeOrNot {

public static void main(String[] args) {


Scanner sc =new Scanner(System.in);
System.out.println("Enter string");
String s = sc.next();
String rev = "";
for (int i = s.length()-1; i >=0 ; i--)
rev=rev+s.charAt(i);
if(s.equals(rev))
System.out.println("String is palindrome");
else
System.out.println("String is not palindrome");

Write code to Calculate frequency of characters in a


string
C

JAVA
import java.util.Scanner;

public class FrequencyOfCharactersInAString {


public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
System.out.print("Enter String : ");
String str = sc.nextLine();
int[] freq = new int[str.length()];
int i, j;

//Converts given string into character array


char string[] = str.toCharArray();
for(i = 0; i <str.length(); i++) {
freq[i] = 1;
for(j = i+1; j <str.length(); j++) {
if(string[i] == string[j]) {
freq[i]++;

//Set string[j] to 0 to avoid printing visited character


string[j] = '0';
}
}
}
//Displays the each character and their corresponding frequency
System.out.println("Characters and their corresponding frequencies");
for(i = 0; i <freq.length; i++) {
if(string[i] != ' ' && string[i] != '0')
System.out.println(string[i] + "-" + freq[i]);
}
}
}
Write a code for bubble sort
C

JAVA
// Time Complexity : O(N^2)
// Space Complexity : O(1)
class Main
{
static void bubbleSort(int a[])
{
int len = a.length; // calculating the length of array
for (int i = 0; i < len-1; i++)
for (int j = 0; j < len-i-1; j++)
if (a[j] > a[j+1]) //comparing the pair of elements
{
// swapping a[j+1] and a[i]
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}

/* Prints the array */


static void printArray(int a[])
{
int len = a.length;
for (int i = 0; i < len; i++)
System.out.print(a[i] + " "); //printing the sorted array

System.out.println();
}

// Main method to test above


public static void main(String args[])
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};

bubbleSort(arr);//calling the bubbleSort function

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

printArray(arr); //calling the printArray function


}
}

How is the merge sort algorithm implemented?


C

JAVA
//Java Program for Merge Sort
class Main {
// this function display the array
public static void display(int[] arr, int size)
{
for(int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// main function of the program
public static void main(String[] args)
{
int[] a = {12, 8, 4, 14, 36, 64, 15, 72, 67, 84};

int size = a.length;


display(a, size);

mergeSort(a, 0, size - 1);


display(a, size);
}

// this function apply merging and sorting in the array


static void mergeSort(int[] a, int left, int right)
{
int mid;
if(left < right)
{
// can also use mid = left + (right - left) / 2
// this can avoid data type overflow
mid = (left + right) / 2;

// recursive calls to sort first half and second half sub-arrays


mergeSort(a, left, mid);
mergeSort(a, mid + 1, right);
merge(a, left, mid, right);
}
}
// after sorting this function merge the array
static void merge(int[] arr, int left, int mid, int right)
{
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;

// create temp arrays to store left and right sub-arrays


int L[] = new int[n1];
int R[] = new int[n2];

// Copying data to temp arrays L[] and R[]


for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

// here we merge the temp arrays back into arr[l..r]


i = 0; // Starting index of L[i]
j = 0; // Starting index of R[i]
k = left; // Starting index of merged sub-array

while (i < n1 && j < n2)


{
// place the smaller item at arr[k] pos
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of L[], if any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
// Copy the remaining elements of R[], if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
}

Write to code to check whether a given year is leap


year or not.
C

JAVA
// Leap year program in Java
// If the year satisfies either of the conditions, it's considered a leap year -
// 1. The year must be divisible by 400.
// 2. The year must be divisible by 4 but not 100.public class Main
{
public static void main (String[]args)
{

int year = 2020;


if (year % 400 == 0)
System.out.println (year + " is a Leap Year");

else if (year % 4 == 0 && year % 100 != 0)


System.out.println (year + " is a Leap Year");

else
System.out.println (year + " is not a Leap Year");

}
}

Find non-repeating characters in a string


C

JAVA
import java.util.*;

class Solution
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
System.out.println ("Enter the string");

String str = sc.next (); //Taking input as a string from the user
int freq[] = new int[256];

//Calculating frequency of each character


for (int i = 0; i < str.length (); i++)
freq[str.charAt (i)]++;

System.out.println ("The non repeating characters are : ");

for (int i = 0; i < 256; i++)


if (freq[i] == 1) //finding the character whose frequency is 1
System.out.print ((char) i + " ");
}
}

Write a code to replace a substring in a string.


C

JAVA
//Replace Substring in a String Java code
import java.util.Scanner;
public class ReplaceASubstringInAString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String : ");
String s1 = sc.nextLine();
System.out.print("Enter the String to be replaced : ");
String oldString = sc.nextLine();
System.out.print("Enter the new String : ");
String newString =sc.nextLine();

String replaceString = s1.replace(oldString, newString);


System.out.println("New String is :"+replaceString);
}
}

Write a code for Heap sort.


C
JAVA
// Java program for implementation of Heap Sort
public class PrepInsta
{
//Main() for the execution of the program
public static void main(String args[])
{
int a[] = {12, 11, 13, 5, 6, 7};
int len = a.length;

PrepInsta ob = new PrepInsta();


ob.sort(a);

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


printArray(a);
}
public void sort(int a[])
{
int len = a.length;

// Build heap (rearrange array)


for (int i = len / 2 - 1; i >= 0; i--)
heapify(a, len, i);

// One by one extract an element from heap


for (int i=len-1; i>=0; i--)
{
// Move current root to end
int temp = a[0];
a[0] = a[i];
a[i] = temp;

// call max heapify on the reduced heap


heapify(a, i, 0);
}
}

// To heapify a subtree rooted with node i which is


// an index in arr[]. n is size of heap
void heapify(int a[], int len, 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 < len && a[l] > a[largest])
largest = l;

// If right child is larger than largest so far


if (r < len && a[r] > a[largest])
largest = r;

// If largest is not root


if (largest != i)
{
int swap = a[i];
a[i] = a[largest];
a[largest] = swap;

// Recursively heapify the affected sub-tree


heapify(a, len, largest);
}
}

/* A utility function to print array of size n */


static void printArray(int a[])
{
int len = a.length;
for (int i=0; i<len; ++i)
System.out.print(a[i]+" ");
System.out.println();
}

Write a code to replace each element in an array by its


rank in the array
C
JAVA
import java.util.*;

class Main {

static void changeArr(int[] input)


{
// Copy input array into newArray
int newArray[] = Arrays.copyOfRange(input, 0, input.length);

// Sort newArray[] in ascending order


Arrays.sort(newArray);
for(int i=0; i< input.length; i++){

for(int j=0; j< input.length; j++){


if(newArray[j]==input[i])
{
input[i] = j+1;
break;
}
}
}
}

// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int[] arr = { 100, 2, 70, 12 , 90};

// Function Call
changeArr(arr);

// Print the array elements


System.out.println(Arrays.toString(arr));
}
}

Write a code to find circular rotation of an array by K


positions.
C

JAVA
class Main {
/*Function to left rotate arr[] of size n by d*/
static void leftRotate(int arr[], int d, int n) {
for (int i = 0; i < d; i++) leftRotatebyOne(arr, n);
}
static void leftRotatebyOne(int arr[], int n) {
int i, temp;
temp = arr[0];
for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1];
arr[n - 1] = temp;
}
/* utility function to print an array */
static void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");
}
// Driver program to test above functions
public
static void main(String[] args) {
// RotateArray rotate = new RotateArray();
int arr[] = {1, 2, 3, 4, 5};
leftRotate(arr, 2, 5);
printArray(arr, 5);
}
}

Write a code to find non-repeating elements in an


array.
C

JAVA
import java.util.Arrays;

class Main
{
public static void countFreq(int arr[], int n)
{
boolean visited[] = new boolean[n];
Arrays.fill(visited, false);

// Traverse through array elements and


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

// Skip this element if already processed


if (visited[i] == true)
continue;

// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
visited[j] = true;
count++;
}
}
if(count==1)
System.out.println(arr[i]);
}

// Driver code
public static void main(String []args)
{
int arr[] = new int[]{10, 30, 40, 20, 10, 20, 50, 10};
int n = arr.length;
countFreq(arr, n);
}
}

Write a code to check for the longest palindrome in an


array.
C

JAVA
import java.util.*;

class Main
{
// Function to check if n is palindrome
static boolean isPalindrome(int n)
{
// Find the appropriate divisor
// to extract the leading digit
int divisor = 1;
while (n / divisor >= 10)
divisor *= 10;

while (n != 0) {
int x = n / divisor;
int y = n % 10;

// If first and last digits are


// not same then return false
if (x != y)
return false;

// Removing the leading and trailing


// digits from the number
n = (n % divisor) / 10;

// Reducing divisor by a factor


// of 2 as 2 digits are dropped
divisor = divisor / 100;
}
return true;
}

// Function to find the largest palindromic number


static int largestPalindrome(int []A, int n)
{
int res = -1;

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

// If a palindrome larger than the currentMax is found


if (A[i] > res && isPalindrome(A[i]))
res = A[i];
}

// Return the largest palindromic number from the array


return res;
}

// Driver program
public static void main(String []args)
{
int []A = { 121, 2322, 54545, 999990 };
int n = A.length;

// print required answer


System.out.println(largestPalindrome(A, n));
}

Write a code to find the factorial of a number.


C

JAVA
//Java program to find factorial of a number
import java.util.Scanner;
public class LearnCoding
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = sc.nextInt();

if(num >= 0)
{
System.out.println(num + " Factorial: " + getFact(num));
}
else
System.out.println("Negative Number: No Factorial");
}

private static int getFact(int num) {

if(num == 1 || num == 0)
return 1;

return num * getFact(num-1);


}
}

Write the code to for Armstrong number


C

JAVA
public class Main
{
public static void main (String[]args)
{
int num = 407, len;

// function to get order(length)


len = order (num);

// check if Armstrong
if (armstrong (num, len))
System.out.println(num + " is armstrong");
else
System.out.println(num + " is armstrong");

static int order (int x)


{
int len = 0;
while (x != 0 )
{
len++;
x = x / 10;
}
return len;
}

static boolean armstrong (int num, int len)


{

int sum = 0, temp, digit;


temp = num;

// loop to extract digit, find power & add to sum


while (temp != 0)
{
// extract digit
digit = temp % 10;

// add power to sum


sum = sum + (int)Math.pow(digit, len);
temp /= 10;
};

return num == sum;


}
}
Write a program to find the sum of Natural Numbers
using Recursion.
C

JAVA
public class Main
{
public static void main (String[]args)
{

int n = 10;
int sum = getSum (n);

System.out.println (sum);
}

static int getSum (int n)


{
if (n == 0)
return n;

return n + getSum (n - 1);


}
}

Write a program to add Two Matrices using Multi-


dimensional Array.
C
#include
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}

// adding two matrices


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}

// printing the result


printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}
Write a Program to Find the Sum of Natural Numbers
using Recursion.
C

JAVA
public class Main
{
public static void main (String[]args)
{

int n = 10;
int sum = getSum (n);

System.out.println (sum);
}

static int getSum (int n)


{
if (n == 0)
return n;

return n + getSum (n - 1);


}
}

Write code to check a String is palindrome or not?


C

JAVA
import java.util.Scanner;
public class Palindrome{

public static void main(String args[]) {

Scanner reader = new Scanner(System.in);


System.out.println("Please enter a String");
String input = reader.nextLine();

System.out.printf("Is %s a palindrome? : %b %n",


input, isPalindrome(input));

System.out.println("Please enter another String");


input = reader.nextLine();

System.out.printf("Is %s a palindrome? : %b %n",


input, isPalindrome(input));

reader.close();

public static boolean isPalindrome(String input) {


if (input == null || input.isEmpty()) {
return true;
}

char[] array = input.toCharArray();


StringBuilder sb = new StringBuilder(input.length());
for (int i = input.length() - 1; i >= 0; i--) {
sb.append(array[i]);
}

String reverseOfString = sb.toString();

return input.equals(reverseOfString);
}

Write a program for Binary to Decimal to conversion


C

JAVA
//Java program to convert Binary number to decimal number
import java.util.Scanner;
public class Binary_To_Decimal
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a binary number : ");
int binary = sc.nextInt();
//Declaring variable to store decimal number
int decimal = 0;
//Declaring variable to use in power
int n = 0;
//writing logic for the conversion
while(binary > 0)
{
int temp = binary%10;
decimal += temp*Math.pow(2, n);
binary = binary/10;
n++;
}
System.out.println("Decimal number : "+decimal);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Write a program to check whether a character is a


vowel or consonant
C

JAVA
//JAVA Program to check whether the character entered by user is Vowel or Consonant.

import java.util.Scanner;
public class vowelorconsonant
{
//class declaration
public static void main(String[] args)
{
//main method declaration
Scanner sc=new Scanner(System.in); //scanner class object creation

System.out.println(" Enter a character");


char c = sc.next().charAt(0); //taking a character c as input from user

if(c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'

|| c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') //condition for the vowels

System.out.println(" Vowel");

else if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) //condition for the
consonants

System.out.println(" Consonant");
else
System.out.println(" Not an Alphabet");

sc.close() //closing scanner class(not mandatory but good practice)


} //end of main method
} //end of class
Write a code to find an Automorphic number
C

JAVA
//Java program to check whether a number is Automorphic number or not
import java.util.Scanner;
public class automorphic_number_or_not
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a number : ");
int number = sc.nextInt();
//Convert the number to string
String s1 = Integer.toString(number);
//Calculate the length
int l1 = s1.length();
int sq = number * number;
String s2 = Integer.toString(sq);
int l2 = s2.length();
//Create Substring
String s3 = s2.substring(l2-l1);
if(s1.equals(s3))
System.out.println("Automorphic Number");
else
System.out.println("Not an Automorphic Number");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Write a code to find Find the ASCII value of a


character
C

JAVA
//Java program to print ASCII values of a character

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
//scanner class object creation
Scanner sc=new Scanner(System.in);

//input from user


System.out.print("Enter a Character: ");
char c=sc.next().charAt(0);

//typecasting from character type to integer type


int i = c;

//printing ASCII value of the character


System.out.println("ASCII value of "+c+" is "+i);

//closing scanner class(not compulsory, but good practice)


sc.close();
}
}

Write a code to Remove all characters from string


except alphabets
C

JAVA
import java.util.Scanner;

class RemoveCharactersInAtringExceptAlphabets {

public static void main(String[] args) {


Scanner sc =new Scanner(System.in);
System.out.print("Enter String : ");
String s = sc.nextLine();
s=s.replaceAll("[^a-zA-Z]","");
System.out.println(s);
}
}

Write a code to find Fibonacci Series using Recursion


C

JAVA
//Fibonacci Series using Recursion
class fibonacci
{
static int fibo(int n)
{
if (n <= 1)
return n;
return fibo(n-1) + fibo(n-2);
}

public static void main (String args[])


{
int n = 9;
System.out.println(fibo(n));
}
}

You might also like