java practice question
Coding Round Question for java Candidate.
Basic Program
- Print Hello world.
- Addition/Subtraction/Multiplication/Division of two numbers.
- Find area of circle/Rectangle/Square.
- Find a Square and cube of number.
- Take input from user and display your full name, age, college name, address.
- Read and print an integer value in java.
- Take input from user and find Addition/Subtraction/Multiplication/Division of two numbers.
- Take input from user and find Square and cube of number.
- Find greatest between two numbers using if else statement
- Find lowest between two numbers using if else statement
- Fibonacci Series.
- Armstrong Number.
- Perfect number.
- Prime number.
- Prime number in range.
- Factorial of a number.
- Reverse a string.
- Reverse a String With out using Built-in Function
- Reverse a number.
- Palindrome number
- Palindrome string.
- Find duplicate characters in a string.
- Find frequency of duplicate character in a String.
- Find frequency of each character in a string .
- Remove duplicate characters in a String
- Find Second highest number.
- Find min and max in array .
- Find sum of digit of an integer .
- Reverse of an array.
- Swap two number without temp.
- Remove white space from string.
- Binary search.
- Shorting a number in ascending order.
- Second largest using for loop shorting.
- find the sum of all the numbers in an array.
- Find square of an array.
- Find cube of an array.
- Addition of two array.
- Addition, subtraction, multiplication of array.
- Perform Linear search on array.
- Make an array and find second largest value.
- Addition of 2D array.
- Transpose of an array.
- Program to Count the Number of Digits in a Number.
- to check if two strings are anagrams.
- program to check if a vowel is present in a string.
- How To Find Duplicates Element in Array in Java.
- How To remove Duplicates element In Array in Java.
- reverse each word of a string in Java.
- read sentence by user then find out number of word in sentence.
- count the total number of characters in a string.
- count the total number of vowels and consonants in a string.
- find the duplicate words in a string.
- Remove white space from string
Object Oriented Programming
- Write a programm to demostrate Single Inharitance in java?
- Give me a example in java like system.out.println where system have reference variable like out.
- Perform single inheritance.
- Perform Hierarchical inheritance.
- Perform default parameterize and copy constructor.
- Implement this keyword.
- Implement super keyword.
- Implement final keyword.
- Explain that aggregation (or composition) in Java involves creating a class that contains references to other objects as instance variables.
- Write a program using various access modifier.
- Create a package and display “Hello World”.
- Perform Encapsulation using package.
- Implement ZeroDivisionException in Exception handling.
- Explain the code provided that demonstrates multithreading in Java.
- Explain the Java code provided that demonstrates the use of different collection types (
List
,Set
, andMap
).
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Q2.Addition/Subtraction/Multiplication/Division of two numbers.
public class ArithmeticOperations {
public static void main(String[] args) {
int num1 = 20;
int num2 = 5;
// Addition
System.out.println("Addition: " +(num1 + num2));
// Subtraction
System.out.println("Subtraction:"+(num1 - num2));
// Multiplication
System.out.println("Multiplication: "+(num1 * num2));
// Division (integer division)
System.out.println("Division: "+(num1 / num2));
}
}
Q3.Find area of circle/Rectangle/Square.
public class AreaCalculations {
public static void main(String[] args) {
// Circle
double radius = 5.0;
double areaOfCircle = 3.14 * radius * radius;
System.out.println("Area of Circle: " + areaOfCircle);
// Rectangle
double length = 10.0;
double width = 5.0;
double areaOfRectangle = length * width;
System.out.println("Area of Rectangle: " + areaOfRectangle);
// Square
double side = 7.0;
double areaOfSquare = side * side;
System.out.println("Area of Square: " + areaOfSquare);
}
}
Q.4.Find a Square and cube of number.
public class SquareAndCube {
public static void main(String[] args) {
int number = 5;
// Calculate square
int square = number * number;
System.out.println("Square of " + number + " is: " + square);
// Calculate cube
int cube = number * number * number;
System.out.println("Cube of " + number + " is: " + cube);
}
}
Q5. Take input from user and display your full name, age, college name, address.
import java.util.Scanner;
public class UserDetails {
public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);
// Prompt the user for their details
System.out.print("Enter your full name: ");
String fullName = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Consume newline left-over
System.out.print("Enter your college name: ");
String collegeName = scanner.nextLine();
System.out.print("Enter your address: ");
String address = scanner.nextLine();
// Display the collected information
System.out.println("\nUser Details:");
System.out.println("Full Name: " + fullName);
System.out.println("Age: " + age);
System.out.println("College Name: " + collegeName);
System.out.println("Address: " + address);
}
}
Q6.Read and print an integer value in java.
import java.util.Scanner;
public class ReadInteger {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter an integer
System.out.print("Enter an integer: ");
// Read the integer entered by the user
int number = scanner.nextInt();
// Print the integer value
System.out.println("You entered: " + number);
}
}
Q7.Take input from user and find Addition/Subtraction/Multiplication/Division of two numbers.
import java.util.Scanner;
public class ArithmeticOperations {
public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the first number
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
// Prompt the user to enter the second number
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
// Perform addition, subtraction, multiplication, and division
double sum = num1 + num2;
double difference = num1 - num2;
double product = num1 * num2;
double quotient = num1 / num2;
// Display the results
System.out.println(sum); // Addition
System.out.println(difference); // Subtraction
System.out.println(product); // Multiplication
System.out.println(quotient); // Division
}
}
Q8.Take input from user and find Square and cube of number.
import java.util.Scanner;
public class SquareAndCube {
public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a number
System.out.print("Enter a number: ");
double number = scanner.nextDouble();
// Calculate square and cube
double square = number * number;
double cube = number * number * number;
// Display the results
System.out.println("Square of " + number + " is: " + square);
System.out.println("Cube of " + number + " is: " + cube);
}
}
Q9.Find greatest between two numbers using if else statement
import java.util.Scanner;
public class GreatestNumber {
public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the first number
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
// Prompt the user to enter the second number
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Determine the greatest number using if-else statements
if (num1 > num2) {
System.out.println(num1 + " is the greatest.");
} else {
System.out.println(num2 + " is the greatest.");
}
}
}
Q10.Find lowest between two numbers using if else statement
import java.util.Scanner;
public class LowestNumber {
public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the first number
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
// Prompt the user to enter the second number
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Determine the lowest number using if-else statements
if (num1 < num2) {
System.out.println(num1 + " is the lowest.");
} else {
System.out.println(num2 + " is the lowest.");
}
}
}
Q11.Write a program to print Fibonacci Series to N-th term ?
// print Fibonacci Series.
import java.util.Scanner;
public class Student {
public static void main(String[] args) {
int a = 0;
int b = 1;
int c, count;
System.out.println("Enter count number for this series ");
Scanner sc = new Scanner(System.in);
count = sc.nextInt();
System.out.println("Fibonacci Series is ");
System.out.print(a + "," + b);
for (int i = 1; i < count; ++i) {
c = a + b;
System.out.print("," + c);
a = b;
b = c;
}
}
}
Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.
Let's try to understand why 153 is an Armstrong number.
153 = (1*1*1)+(5*5*5)+(3*3*3)
where:
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So:
1+125+27=153
public class Student {
public static void main(String[] args) {
int num = 153, reminder, sumofCube = 0, temp;
temp = num;
while (num > 0) {
reminder = num % 10;
num = num / 10;
sumofCube = sumofCube + (reminder * reminder * reminder);
}
if (temp == sumofCube) {
System.out.println("its Armstrong");
} else {
System.out.println("its not Armstrong");
}
}
}
Q13.Perfect number.
=> a perfect number is a positive integer that is equal to the sum of its positive proper divisors,
if the sum of its positive divisors excluding the number itself is equal to that number. For example, 28 is a perfect number because 28 is divisible by 1, 2, 4, 7, 14, and 28 and the sum of these values is 1+2+4+7+14=28.
some perfect number Exampe : 6 , 28 , 496 , 8128
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input number from the user
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Calculate sum of proper divisors
int sum = 0;
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i;
}
}
// Check if the number is a perfect number
if (sum == number) {
System.out.println(number + " is a perfect number.");
} else {
System.out.println(number + " is not a perfect number.");
}
}
}
Q14.prime number
A prime number is a whole number greater than 1, which is only divisible by 1 and itself. The first few prime numbers are 2 3 5 7 11 13 17 19 23
import java.util.Scanner;
public class Student {
public static void main(String[] args) {
int num = 0;
int flage = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter A Number Which You Want to Check.");
num = sc.nextInt();
if (num == 0 || num == 1) {
flage = 1;
}
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
flage = 1;
break;
}
}
if (flage == 0) {
System.out.println("its Prime Number");
} else {
System.out.println("its not Prime Number");
}
}
}
using function
import java.util.Scanner;
public class Student {
static boolean checkprime(int num) {
boolean isprime = true;
if (num == 1 || num == 0) {
return isprime = false;
}
for (int i = 2; i <num; i++)
if (num % i == 0) {
isprime = false;
}
return isprime;
}
public static void main(String[] args) {
int num;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
num = sc.nextInt();
if (checkprime(num)) {
System.out.println("its prime number ");
} else {
System.out.println("its not prime number");
}
}
}
import java.util.Scanner;
public class Student {
static boolean checkprime(int num) {
boolean isprime = true;
if (num == 0 || num == 1) {
isprime = false;
}
for (int i = 2; i < num; i++) {
if (num % i == 0) {
isprime = false;
}
}
return isprime;
}
public static void main(String[] args) {
int low;
int high;
Scanner sc = new Scanner(System.in);
System.out.println("Enter lower bound");
low = sc.nextInt();
System.out.println("Enter Higher bound");
high = sc.nextInt();
for (int i = low; i <= high; i++) {
if (checkprime(i)) {
System.out.print(i + ",");
}
}
}
}
Factorial of 5 is: 120
import java.util.Scanner;
public class Student {
static int findfactorial(int num) {
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial = factorial * i;
}
return factorial;
}
public static void main(String[] args) {
int num;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number ");
num = sc.nextInt();
System.out.println(findfactorial(num));
}
}
import java.util.Scanner;
public class Student {
public static void main(String[] args) {
String str;
Scanner sc = new Scanner(System.in);
System.out.println("enter any string ");
str = sc.nextLine();
StringBuffer b = new StringBuffer(str);
b.reverse();
System.out.println("Reverse string is " + b);
}
}
Reverse a String without using Built-in Function in java?
public class Student {
public static void main(String[] args) {
String str = "sandip";
String reversedStr = "";
// Traverse the original string from end to beginning
for (int i = str.length() - 1; i >= 0; i--) {
reversedStr += str.charAt(i); // Append each character to reversedStr
}
// Print the original and reversed strings
System.out.println("Original String: " + str);
System.out.println("Reversed String: " + reversedStr);
}
}
import java.util.Scanner;
public class Student {
public static void main(String[] args) {
int num, rev = 0, reminder;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number ");
num = sc.nextInt();
while (num != 0) {
reminder = num % 10;
rev = rev * 10 + reminder;
num = num / 10;
}
System.out.println("Reverse =" + rev);
}
}
import java.util.Scanner;
public class Student {
public static void main(String[] args) {
int num, rev = 0, reminder, temp;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number ");
num = sc.nextInt();
temp = num;
while (num != 0) {
reminder = num % 10;
rev = rev * 10 + reminder;
num = num / 10;
}
if (temp == rev) {
System.out.println("Number " + temp + " is palindrome");
} else {
System.out.println("Number " + temp + " is not palindrome");
}
}
}
import java.util.Scanner;
public class Student {
public static void main(String[] args) {
String str;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string");
str = sc.nextLine();
String rev = "";
for (int i = str.length() - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (str.equals(rev)) {
System.out.println("its Palindrome");
} else {
System.out.println("its not Palindrome");
}
}
}
Q21.Find duplicate characters in a string.
public class Student {
static void find_duplicate(String str) {
char charArray[] = str.toCharArray();
int count;
System.out.println("String : " + str);
System.out.println("Duplicate Element is :");
for (int i = 0; i < charArray.length; i++) {
count = 1;
for (int j = i + 1; j < charArray.length; j++) {
if (charArray[i] == charArray[j] && charArray[i] != ' ') {
count++;
charArray[j] = '0';
}
}
if (count > 1 && charArray[i] != '0') {
// Only duplicate element
System.out.println(charArray[i]);
// frequency of duplicate element
// System.out.println(charArray[i]+" : "+count +" Times");
}
}
}
public static void main(String[] args) {
String str = "sandip kumar raj";
find_duplicate(str);
}
}
Q22.Find frequency of duplicate character in a String.
public class Student {
static void find_duplicate(String str) {
char charArray[] = str.toCharArray();
int count;
System.out.println("String : " + str);
System.out.println("Duplicate Element is :");
for (int i = 0; i < charArray.length; i++) {
count = 1;
for (int j = i + 1; j < charArray.length; j++) {
if (charArray[i] == charArray[j] && charArray[i] != ' ') {
count++;
charArray[j] = '0';
}
}
if (count > 1 && charArray[i] != '0') {
// Only duplicate element
System.out.println(charArray[i]);
// frequency of duplicate element
// System.out.println(charArray[i]+" : "+count +" Times");
}
}
}
public static void main(String[] args) {
String str = "sandip kumar raj";
find_duplicate(str);
}
}
Q23.Find frequency of each character in a string.
public class Student {
static void find_duplicate(String str) {
char charArray[] = str.toCharArray();
int count;
System.out.println("String : " + str);
System.out.println(" Frequency of each character :");
for (int i = 0; i < charArray.length; i++) {
count = 1;
for (int j = i + 1; j < charArray.length; j++) {
if (charArray[i] == charArray[j] && charArray[i] != ' ') {
count++;
charArray[j] = '0';
}
}
if (charArray[i] != '0' && charArray[i]!=' ') {
System.out.println(charArray[i]+" : "+ count);
}
}
}
public static void main(String[] args) {
String str = "sandip kumar raj";
find_duplicate(str);
}
}
Q24.Remove duplicate characters in a String
public class Student {
static void find_duplicate(String str) {
char charArray[] = str.toCharArray();
int count;
System.out.println("String : " + str);
System.out.println("After Removed Duplicate Element is :");
for (int i = 0; i < charArray.length; i++) {
count = 1;
for (int j = i + 1; j < charArray.length; j++) {
if (charArray[i] == charArray[j] && charArray[i] != ' ') {
count++;
charArray[j] = '0';
}
}
// without white space => if (charArray[i] != '0' && charArray[i]!=' ')
if (charArray[i] != '0') {
System.out.print(charArray[i]);
}
}
}
public static void main(String[] args) {
String str = "sandip kumar raj";
find_duplicate(str);
}
}
Q25.Find Second highest number.
import java.lang.reflect.Array;
import java.util.Arrays;
public class Student {
static int findsecondLargest(int[] num) {
int total_length = num.length;
Arrays.sort(num);
return num[total_length - 2];
}
public static void main(String[] args) {
int num[] = { 33, 44, 55, 23, 76, 89, 34 };
System.out.println("Second Largest = " + findsecondLargest(num));
}
}
Q26.Find min and max in array.
public class Student {
public static void main(String[] args) {
int num[] = { 22, 33, 79, 56, 12, 76, 34 };
int greatest = num[0];
int smallest = num[0];
for (int i = 0; i < num.length; i++) {
if (num[i] > greatest) {
greatest = num[i];
}
if (num[i] < smallest) {
smallest = num[i];
}
}
System.out.println("Largest value is " + greatest);
System.out.println("Smallest value is " + smallest);
}
}
Q27.Find sum of digit of an integer.
public class Student {
public static void main(String[] args) {
int num =152;
int reminder,sum=0;
while (num!=0) {
reminder= num%10;
sum=sum+reminder;
num=num/10;
}
System.out.println("Sum of digit is "+sum);
}
}
public class Student {
public static void main(String[] args) {
int num[] = { 3, 4, 5, 9, 6, 2 };
System.out.println("Array is = {3,4,5,9,6,2}");
System.out.println("Reverse is ");
for (int i = num.length - 1; i >= 0; i--) {
System.out.print(num[i] + " ");
}
}
}
Q29.Swap two number without temp.
public class Student {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Actual Number is ");
System.out.println("a : " + a + " b : " + b);
System.out.println("after swaping ");
a = a + b;
b = a - b;
a = a - b;
System.out.println("a : " + a + " b : " + b);
}
}
Q30.Remove white space from string.
public class Student {
public static void main(String[] args) {
String str = "hello how are you ";
char charstr[] = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
if (charstr[i] == ' ') {
charstr[i] = 0;
}
}
for (int i = 0; i < str.length(); i++) {
if (charstr[i] != 0) {
System.out.print(charstr[i]);
}
}
}
Q31.Binary search.
import java.util.Scanner;
public class Student {
public static void main(String[] args) {
int num[] = { 22, 4, 56, 76, 32, 56, 43, 89 };
int found = 0;
int position = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number for search");
int search = sc.nextInt();
for (int i = 0; i < num.length; i++) {
if (num[i] == search) {
found = 1;
position = i + 1;
}
}
if (found == 1) {
System.out.println("data is exists at " + position + " position");
} else {
System.out.println("data is not exists");
}
}
}
Q32.Shorting a number in ascending order.
import java.util.Arrays;
public class SortNumberDigits {
public static int sortDigits(int number) {
// Convert number to string to manipulate digits
String numberStr = Integer.toString(number);
// Convert string to char array
char[] digits = numberStr.toCharArray();
// Sort the char array
Arrays.sort(digits);
// Convert sorted char array back to string
String sortedNumberStr = new String(digits);
// Parse string back to integer
int sortedNumber = Integer.parseInt(sortedNumberStr);
return sortedNumber;
}
public static void main(String[] args) {
int number = 352674;
// Sort the digits of the number
int sortedNumber = sortDigits(number);
System.out.println("Original number: " + number);
System.out.println("Number with digits sorted in ascending order: " + sortedNumber);
}
}
Q33.Second largest using for loop shorting.
public class Student {
public static void main(String[] args) {
int num[] = { 12, 3, 4, 52, 33, 44, 65, 34, 23 };
int temp;
System.out.println("Original array data is ");
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] + " ");
}
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
if (num[i] > num[j]) {
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
System.out.println("");
System.out.println("After sorting array data is ");
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] + " ");
}
System.out.println("\nSecond largest number is " + num[num.length - 2]);
}
}
Q34.find the sum of all the numbers in an array.
public class Student {
public static void main(String[] args) {
int[] numbers = { 2, 4, 6, 8, 10 };
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
System.out.println("Total sum is " + sum);
}
}
public class SquareOfArray {
public static void main(String[] args) {
int[] array = {2, 3, 4, 5, 6};
// Iterate through the array and square each element
for (int i = 0; i < array.length; i++) {
array[i] = array[i] * array[i];
}
// Print the squared array
System.out.print("Squared array: [");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i != array.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.print("Original array: ");
printArray(array);
System.out.print("Cubed array: ");
for (int i = 0; i < array.length; i++) {
int cube = array[i] * array[i] * array[i];
System.out.print(cube + " ");
}
}
public static void printArray(int[] array) {
System.out.print("[ ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println("]");
}
}
public class Array
{
public static void main(String args[])
{
int vs[]={1,2,3,4,5};
int sv[]={5,4,3,2,1};
int a[]=new int[vs.length];
for(int i=0; i<vs.length;i++)
{
a[i]=vs[i]+sv[i];
}
System.out.println("Addition of two arrays");
for(int num:a)
{
System.out.println(num + " ");
}
}
}
Q38.Addition, subtraction, multiplication, of array.
public class Array
{
public static void main(String args[])
{
int vs[]={1,2,3,4,5};
for(int i=0; i<vs.length;i++)
{
System.out.println(vs[i] );
}
for(int i=0; i<1;i++)
{
System.out.println(vs[0]+vs[1]+vs[2]+vs[3]+vs[4]);
System.out.println(vs[0]-vs[1]-vs[2]-vs[3]-vs[4]);
System.out.println(vs[0]*vs[1]*vs[2]*vs[3]*vs[4]);
}
}
}
Q39.Perform Linear search on array.
public class Student {
public static void main(String[] args) {
int[] array = {12, 45, 67, 23, 91, 56, 78};
int target = 23;
int index = linearSearch(array, target);
if (index != -1) {
System.out.println("Element " + target + " found at index: " + index);
} else {
System.out.println("Element " + target + " not found in the array.");
}
}
public static int linearSearch(int[] arr, int target) {
// Iterate through each element of the array
for (int i = 0; i < arr.length; i++) {
// If the target element is found, return its index
if (arr[i] == target) {
return i;
}
}
// If target element is not found, return -1
return -1;
}
}
Q40.Make an array and find second largest value.
import java.lang.reflect.Array;
import java.util.Arrays;
public class Student {
static int findsecondLargest(int[] num) {
int total_length = num.length;
Arrays.sort(num);
return num[total_length - 2];
}
public static void main(String[] args) {
int num[] = { 33, 44, 55, 23, 76, 89, 34 };
System.out.println("Second Largest = " + findsecondLargest(num));
}
}
import java.util.*;
public class Array
{
public static void main(String[] args)
{
int[][] num = new int[3][3];
Scanner sc = new Scanner(System.in);
System.out.println("enter a 2d array");
for(int i = 0; i < num.length; i++)
{
for(int j=0; j<num[i].length; j++)
{
num[i][j] = sc.nextInt();
}
}
System.out.println("addition of 2d array is :");
System.out.println(num[0][0]+num[0][1]+num[0][2]+num[1][0]+num[1][1]+num[1][2]+num[2][0]+num[2][1]+num[2][2]);
}
}
public class TransposeArray {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Original Matrix:");
displayMatrix(matrix);
int[][] transposeMatrix = transpose(matrix);
System.out.println("\nTransposed Matrix:");
displayMatrix(transposeMatrix);
}
public static int[][] transpose(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
int[][] transposeMatrix = new int[columns][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
transposeMatrix[j][i] = matrix[i][j];
}
}
return transposeMatrix;
}
public static void displayMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
Q43.Program to Count the Number of Digits in a Number.
import java.util.Scanner;
public class Student {
public static void main(String[] args) {
int num;
int count = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter any number");
num = sc.nextInt();
while (num != 0) {
num = num / 10;
count++;
}
System.out.println("number of digit is " + count);
}
}
Q44.To check if two strings are anagrams.
import java.util.Arrays;
public class Student {
public static void main(String[] args) {
String str1 = "Race";
String str2 = "Care";
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
// check if length is same
if (str1.length() == str2.length()) {
// convert strings to char array
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
// sort the char array
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// if sorted char arrays are same
// then the string is anagram
boolean result = Arrays.equals(charArray1, charArray2);
if (result) {
System.out.println(str1 + " and " + str2 + " are anagram.");
} else {
System.out.println(str1 + " and " + str2 + " are not anagram.");
}
} else {
System.out.println(str1 + " and " + str2 + " are not anagram.");
}
}
}
Q45.program to check if a vowel is present in a string.
public class Student {
public static void main(String[] args) {
String str = "hello";
boolean check = false;
str = str.toLowerCase();
if (str.matches(".*[aeiou]*.")) {
System.out.println("its contain vowel");
} else {
System.out.println("its not contain vowel");
}
}
}
Example 2:
public class Student {
public static boolean stringContainsVowels(String str) {
return str.toLowerCase().matches(".*[aeiou].*");
}
public static void main(String[] args) {
// String str = "Hello";
String str = "TV";
if (stringContainsVowels(str)) {
System.out.println("Its Contain Vowel");
} else {
System.out.println("Not Contain Vowel");
}
}
}
Q46.How To Find Duplicates Element in Array in Java.
public class Student {
public static void main(String[] args) {
int numbers[] = { 1, 2, 3, 4, 2, 7, 8, 8, 3 };
System.out.println("Duplicate Array Element is ");
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] == numbers[j]) {
System.out.print(numbers[i] + " ");
}
}
}
}
}
Q47.How To remove Duplicates element In Array in Java.
public class Student {
public static void main(String[] args) {
int numbers[] = { 1, 2, 3, 4, 2, 7, 8, 8, 3 };
System.out.println("Removed Duplicate Array Element");
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] == numbers[j]) {
numbers[j] = 0;
}
}
}
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] != 0) {
System.out.print(numbers[i] + " ");
}
}
}
}
Q48.reverse each word of a string in Java.
public class Student {
static void reverseEachWordOfString(String inputString) {
String[] words = inputString.split(" ");
String reverseString = "";
for (int i = 0; i < words.length; i++) {
String word = words[i];
String reverseWord = "";
for (int j = word.length() - 1; j >= 0; j--) {
reverseWord = reverseWord + word.charAt(j);
}
reverseString = reverseString + reverseWord + " ";
}
System.out.println(inputString);
System.out.println(reverseString);
System.out.println("-------------------------");
}
public static void main(String[] args) {
reverseEachWordOfString("Java Concept Of The Day");
}
}
Q49.Read sentence by user then find out number of word in sentence.
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read the sentence from the user
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();
// Split the sentence into words using space as the delimiter
String[] words = sentence.trim().split("\\s+");
// Count the number of words
int wordCount = words.length;
System.out.println("The number of words in the sentence is: " + wordCount);
}
}
Q50.count the total number of characters in a string.
public static void main(String[] args) {
String string = "The best of both worlds";
int count = 0;
// Counts each character except space
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) != ' ')
count++;
}
System.out.println("Total number of characters in a string: " + count);
}
}
Q51.count the total number of vowels and consonants in a string.
public class Student {
public static void main(String[] args) {
int vCount = 0, cCount = 0;
String str = "This is a really simple sentence";
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o'
|| str.charAt(i) == 'u') {
vCount++;
} else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
cCount++;
}
}
System.out.println("Number of vowels: " + vCount);
System.out.println("Number of consonants: " + cCount);
}
}
Q52.find the duplicate words in a string
public class Student {
public static void main(String[] args) {
String string = "Big black bug bit a big black dog on his big black nose";
int count;
string = string.toLowerCase();
String words[] = string.split(" ");
System.out.println("Duplicate words in a given string : ");
for (int i = 0; i < words.length; i++) {
count = 1;
for (int j = i + 1; j < words.length; j++) {
if (words[i].equals(words[j])) {
count++;
words[j] = "0";
}
}
// Displays the duplicate word if count is greater than 1
if (count > 1 && words[i] != "0")
System.out.println(words[i]);
}
}
}
Q53.Remove white space from string.
public class Student {
public static void main(String[] args) {
String str = "hello how are you ";
char charstr[] = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
if (charstr[i] == ' ') {
charstr[i] = 0;
}
}
for (int i = 0; i < str.length(); i++) {
if (charstr[i] != 0) {
System.out.print(charstr[i]);
}
}
}
}
Q54 Give me a example in java like system.out.println where system have reference variable like out
something similar to System.out.println
where a class has a reference variable like out
and you can call it similarly to System.out.println
, we can define a class with a static reference to another object that handles the printing.
Example: Creating a Custom Class with a Reference Variable
class MyPrinter {
// Static reference variable like 'out' in System
public static PrintHelper out = new PrintHelper();
// Helper class that contains the printOn method
static class PrintHelper {
public void printOn(String message) {
System.out.println(message);
}
}
}
public class Main {
public static void main(String[] args) {
// Call the printOn method using the reference variable 'out'
MyPrinter.out.printOn("Hello from custom printOn method with 'out' reference!");
}
}
Explanation:
- MyPrinter: This class contains a static reference variable
out
, which is an instance of thePrintHelper
class. This is similar to howSystem
has a reference variableout
that is an instance ofPrintStream
. - PrintHelper: A nested static class inside
MyPrinter
, which has a methodprintOn
that behaves likeSystem.out.println
. - Main: The main class where
MyPrinter.out.printOn(...)
is called, mimickingSystem.out.println(...)
.
Output:
Hello from custom printOn method with 'out' reference!
How It Works:
MyPrinter
has a static referenceout
to an instance ofPrintHelper
.- You can access
printOn
throughMyPrinter.out
, just likeSystem.out
. - This provides a structure similar to how
System.out.println
works in Java.
Q54.Perform single inheritance.
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args)
{
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}
Q55.Perform Hierarchical inheritance.
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat is meowing");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.eat();
dog.bark();
cat.eat();
cat.meow();
}
}
Q56.Write a code using abstract keyword.
abstract class Animal {
abstract void makeSound();
void sleep() {
System.out.println("Zzz");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.makeSound();
dog.sleep();
cat.makeSound();
cat.sleep();
}
}
Q57.Perform default parameterize and copy constructor.
class V
{
int x,y;
V()
{
x=20;
y=10;
}
V(int a,int b)
{
x=a;
y=b;
}
V(V s)
{
x=s.x;
y=s.y;
}
public void get()
{
System.out.println(x+y);
}
}
public class Student
{
public static void main(String[] args)
{
V v1= new V();
V v2= new V(3,6);
V v3= new V(v1);
v1.get();
v2.get();
v3.get();
}
}
class Studentinfo
{
int roll;
String name;
Studentinfo(int roll, String name)
{
this.roll = roll;
this.name = name;
}
void display()
{
System.out.println(" my roll is " + roll + " and my name is " +name);
}
}
public class Array
{
public static void main(String[] args) {
Studentinfo s = new Studentinfo(140,"Sandip");
s.display();
}
}
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Q61.Write a program to implement aggregation.
public class Address
{
String city, state, country;
Address(String city, String state, String country)
{
this.city = city;
this.state = state;
this.country = country;
}
}
public class Aggregation
{
int roll;
String name;
Address address;
Aggregation(int roll, String name, Address address)
{
this.roll = roll;
this.name = name;
this.address = address;
}
void display()
{
System.out.println(" my roll is " + roll + " and my name is " + name);
System.out.println("city: " + address.city + " state: " + address.state + " country: " + address.country);
}
public static void main(String[] args)
{
Address a = new Address("Mumbai", "Maharashtra", "India");
Aggregation s = new Aggregation(140, "Sandip", a);
s.display();
}
}
Q62.Write a program using various access modifier.
// private access modifier
class Student{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
//default access modifier
package pack;
class A{
void msg(){System.out.println("Hello");}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
//protected access modifier
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
// public access modifier
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Q63.Create a package and display “Hello World”.
package mypackage;
public class Greeting {
public static String getMessage() {
return "Hello World";
}
}
package mypackage;
public class HelloWorld {
public static void main(String[] args) {
String message = Greeting.getMessage();
System.out.println(message);
}
}
Q64.Perform Encapsulation using package.
package com;
public class Student
{
private String name;
public String getname()
{
return name;
}
public void setname(String name)
{
this.name=name;
}
}
package com;
public class Student1 {
public static void main(String args[])
{
Student s=new Student();
s.setname("Sandip");
System.out.println(s.getname());
}
}
Q65.Implement ZeroDivisionException in Exception handling.
import java.util.*;
class Student
{
public static void main(String[] args)
{
int x,y;
System.out.println("enter two numbers: ");
Scanner sv=new Scanner(System.in);
x=sv.nextInt();
y=sv.nextInt();
try
{
System.out.println(x/y);
}
catch(Exception e)
{
System.out.println("wrong input");
}
finally
{
System.out.println("finaly executed");
}
}
}
Q66.Explain the code provided that demonstrates multithreading in Java.
class MyThread extends Thread {
private String threadName;
MyThread(String name) {
threadName = name;
}
public void run() {
System.out.println("Thread " + threadName + " is running.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
}
public class Student {
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread 1");
MyThread thread2 = new MyThread("Thread 2");
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
public class Student {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
System.out.println("List Example:");
for (String fruit : list) {
System.out.println(fruit);
}
System.out.println();
Set<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
set.add(10);
System.out.println("Set Example:");
for (int number : set) {
System.out.println(number);
}
System.out.println();
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
System.out.println("Map Example:");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
Last Updated on : 21st Dec 2024 18:52:34 PM
Latest Update
- JavaScript Interview Question MongoDb Command Curd Operation Node MonogoDb Express EJSC Practice Question Example Data Structure with CPPjava practice questionCurd operation with localstorage in javascriptComplete curd operation in react with json server and axios and router-domCPP Practice Question React Interview Question Java Pattern Program