0% found this document useful (0 votes)
14 views36 pages

Java Programs for QA/SDET Interviews

The document contains a collection of Java programs designed for QA/SDET interviews, covering various topics such as finding odd/even numbers, prime numbers, Fibonacci series, and string manipulations. Each program is presented with its code, input, and expected output. The document serves as a resource for learning and practicing Java programming concepts relevant to tech careers.

Uploaded by

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

Java Programs for QA/SDET Interviews

The document contains a collection of Java programs designed for QA/SDET interviews, covering various topics such as finding odd/even numbers, prime numbers, Fibonacci series, and string manipulations. Each program is presented with its code, input, and expected output. The document serves as a resource for learning and practicing Java programming concepts relevant to tech careers.

Uploaded by

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

Recursive Coders Bengaluru

Premium Structured Courses for ‘Tech Career’

JAVA Programs for QA/SDET Interview


1.) Java program to Find Odd or Even number
import [Link];

public class OddEven {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter any number: ");
int number = [Link]();

if (number % 2 == 0) {
[Link](number + " is even.");

} else {
[Link](number + " is odd.");
}
}
}

2.) Java program to find Prime number


import [Link];

public class PrimeNumber {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
if (isPrime(number)) {
[Link](number + " is a prime number.");
} [Link](number
else { + " is not a prime number.");
}
}

public static boolean isPrime(int num) {


for (int
//try i =number
each 2; i <=
bynum / 2;
using % i++) {
if (num % i == 0) {
return false;
}
} return true;
}
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

3.) Java program to find Fibonacci series upto a


given number range
import [Link];

public class PrimeNumber {

public static
Scanner sc =void
new main(String[] args) {
Scanner([Link]);
[Link]("enter number of terms");
int number = 6;
int first = 0, second = 1, next;
[Link]("Fibonacci series is ");
for ( int i = 0; i<=number; i++)

{ [Link](first + "");
next = second+first;
first = second;
second = next;

}
}

Output: 0 1 1 2 3 5 8

4.) Java program to swap two numbers without


using third variable
import [Link];

public class SwapNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first number: ");
int a = 5,
[Link]("Enter the second number: ");
int b = 10;
[Link]("Before swapping: a = " + a + ", b = " + b);
a = a + b;
b = a - b;
a = a - b;
[Link]("After swapping: a = " + a + ", b = " + b);

}
}

Output: After Swapping: a = 10,b=5


Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

5.) Java program to Find Factorial on given Number


import [Link];

public class FactorialNumber {

public static void main(String[] args) {


int factorial
Scanner scanner=1;
= new Scanner([Link]);
[Link]("Enter any number ");
int number = 5;
for (int i = 1; i <= number; i++){

factorial = factorial * i;
}
[Link]("Factorial number is :" +factorial);

}
}

Input: 5!
Output:5! = 5*4*3*2*1= 120

6.) Java program to Reverse Number


import [Link];

public class ReverseNumber {

public static void main(String[] args) {


int no, rev=0,r,a;
Scanner scanner = new Scanner([Link]);
[Link]("Enter any number : ");
no = [Link]();
a = no;
while(no>0)
{
r = no%10;
rev = rev*10+r;
no=no/10;
}
[Link]("Reverse : " +rev);

}
}

Input: 15786
Output: 68751
Nextgen_IT_Careers
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

7.) Java program to find Armstrong Number


import [Link];
public class ArmstrongNumber {

public static void main(String[] args) {


int arm=0, a,b,c,d,no;
Scanner scanner = new Scanner([Link]);
[Link]("Enter any number : ");
no = [Link]();
d = no;
while(no>0)
{
a = no%10;
no = no/10;
arm =arm+a*a*a;
}
if(arm==d){
[Link]("Armstrong number”);
}
else{
[Link]("Not Armstrong number”);
}
}
}

8.) Java program to find number of digits in given


number
import [Link];
public class NumberOfDigits {

public static void main(String[] args) {


int no = 0, a = 0;
Scanner scanner = new Scanner([Link]);
[Link]("Enter any number : ");
no = [Link]();
if(no<0)
{
no = no * -1;

} else if (no==0) {
no=1;
}
while(no>0)
{
no=no/10;
a++;}
[Link]("Number of digits in given number is :" +a);}
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

9.) Java program to find Palindrome number

import [Link];

public class Main {


public static
Scanner void main(String[]
scanner args) {
= new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
if (isPalindrome(number)) {
[Link](number + " is a palindrome.");
} else {
[Link](number + " is not a palindrome.");
}
}

public static boolean isPalindrome(int num) {


int originalNumber = num;
int reversedNumber = 0;

while (num != 0) {
int digit = num % 10;
reversedNumber = reversedNumber * 10 + digit;
num = num/10;
}

return originalNumber == reversedNumber;


}
}

Enter a number: 1001

1001 is a palindrome.
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

10.) Java program to calculate the sum of digits of


a number

public class Main {


public static void main(String[] args) {
int number = 12345;
int sumOfDigits = calculateSumOfDigits(number);

[Link]("Sum of digits of " + number + " is:" +


sumOfDigits);
}
public static int calculateSumOfDigits(int number) {
int sum = 0;
while (number > 0) { // Extract the last digit
int digit = number //
% 10;
Add the digit to sum
sum = sum + digit; //Removethelastdigitfromnumber
number = number / 10;
}
return sum;
}
}

Output:
Sum of digits of 12345 is: 15
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

Strings
1.) Java program to reverse a string
import [Link];
public class Test {
public static
Scanner void=main(String[]
scanner args) {
new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
char ch;
String nstr = "";
for (int i = 0; i < [Link](); i++) {

ch = [Link](i);
nstr = ch + nstr;
}
[Link]("Reversed String is : " + nstr);

2.) Java program to reverse each word of a given


string
public static void main(String[] args) {
reverseEachWordOfString
("Java is good programming langauges");
}
static void reverseEachWordOfString(String inputString)
{
String[] words = [Link](" ");

String reverseString = "";


for (int i = 0; i < [Link]; i++) {
String word = words[i];
String nstr = "";
char ch;
for (int j = 0; j < [Link](); j++) {
ch = [Link](j);
nstr = ch + nstr;
}
reverseString = reverseString + nstr + " ";
}
out
[Link](inputString);
System. .println(reverseString);
}
Input: Java is good programming langauges
Output: avaJ si doog gnimmargorp seguagnal
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

3.) Java program to find duplicate characters in a


string
import [Link];
import [Link];
public class Main {

public static void main(String[] args) {


duplicateCharacterCount
("Learn Java Programming");
}

static void duplicateCharacterCount(String inputString) {

HashMap<Character, Integer> charCountMap = new HashMap<>();


char[] strArray = [Link]();
for (char c : strArray) {
if ([Link](c)) {
[Link](c, [Link](c) + 1);
} else {
[Link](c, 1);
}
}

Set<Character>
out charsInString = [Link]();
System. .println("Duplicate Characters in : " + inputString);

for (Character ch : charsInString) {


if ([Link](ch)
[Link](ch>+1) { " + [Link](ch));
" :
}
}
}
}

Duplicate Characters in : Learn Java Programming

a : 4

g : 2

m : 2

n : 2

r : 3
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

4.) Java program to count Occurrences of Each


Character in String
import [Link];

public class Main {

public static void main(String[] args) {


CharacterCount
("Test Automation Java Automation");
}

static void CharacterCount(String inputString) {


HashMap<String,Integer> charCountMap = new HashMap<>();
for(String s : [Link](" "))
{
if([Link](s))
{
[Link](s,[Link](s)+1);
}
else
{
[Link](s,1);
}
}
[Link]("Count of Characters in a given string:" +
charCountMap);
}
}
CountofCharacters in a givenstring : {Java=1,Automation=2,Test=1}

5.) Java program to count the number of words in


a string
public class Main {
public static void main(String[]
[Link]("Enter args){
the String");
Scanner sc = new Scanner([Link]);
String s = [Link]();
int count = 1;

for (int i = 0; i < [Link]() - 1; i++) {


if (([Link](i) == ' ') && ([Link](i + 1) != ' ')){
count++;
}
}
[Link]("Number of words in a string: " +count); }
}
Enter the String: Welcome to Java World
Number of words in a string: 4
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

6.) Java program to find all permutations of a


given string

import [Link];

public class Main {


public static void main(String[] args) {
String str = "abc";
permute(str, "");
}

static void permute(String str, String prefix) {


if ([Link]() == 0) {
[Link](prefix);
} else {
for (int i = 0; i < [Link](); i++) {
String rem = [Link](0,i) + [Link](i+1);
permute(rem,prefix + [Link](i));
}
}
}
}

abc

acb

bac

bca

cab

cba
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

7.) Java program to find if a string is Palindrome

import [Link];

public class Main {


public static void main(String[] args) {
String str = "madam";
[Link](isPalindrome(str));
}

static boolean isPalindrome(String str) {


int start = 0;
int end = [Link]() - 1;

while (start < end) {


if ([Link](start) != [Link](end)){
return false;
}
start++;
end--;
}
return true;
}
}
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

8.) Java program to determine if Two Strings are


Anagrams

public class Main {

public static void main(String[] args) {


String str1 = "listen";
String str2 = "silent";
[Link](areAnagrams(str1,str2));
}

static boolean areAnagrams(String str1, String str2){


if([Link]() != [Link]())
{
return false;
}

int[] charCount = new int[256];


for( int i = 0; i < [Link](); i++)
{
charCount[[Link](i)]++;
charCount[[Link](i)]--;
}

for ( int count : charCount)


{
if ( count !=0 )
{
return false;
}
}
return true;
}
}
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

9.) Java program to Count Vowels and Consonants


in a given string

public class Main {


public static void main(String[] args) {
String str = "Hello World";
VowelConsonantCount(str);
}

static void VowelConsonantCount(String str) {


int vowels = 0, consonants = 0;
str = [Link]();
for (char c : [Link]()) {
if (c >= 'a' && c <= 'z') {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
vowels++;
} else {
consonants++;
}
}
}
[Link]("Vowels : " + vowels);
[Link]("Consonants : " + consonants);
}
}

Vowels : 3
Consonants : 7
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

10.) Java program to print unqiue characters

import [Link];

public class Main {


public static
Scanner void main(String[]
scanner args) {
= new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
[Link]("Unique characters in \"" + input + "\":");
printUniqueCharacters
(input);

public static void printUniqueCharacters


// AssumeASCII (String str){ to track
characters (0-127),usebooleanarray
character occurrences
boolean[] unique = new boolean[128];

for (int i = 0; i < [Link]();i++){


char ch = [Link](i);
if (!unique[ch]) {
unique[ch] = true;
[Link](ch + "");
}
}

}
}

Enter a string: Java Automation

Unique characters in "Java Automation":

J a v A u t o m i n
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

11.) Java program to print even indexed


characters

import [Link];

public class Main {


publiScc asntnaetri cs cvaoninde rm a=i nn(eSwt rSicnagn[n]e ra(rSgyss)t e{m .in);
[Link]("Enter a string: ");
String input = [Link]();

[Link]("Even indexed characters in \"" + input + "\":");


printEvenIndexedCharacters
(input);

public static void printEvenIndexedCharacters(String str){


for (int i = 0; i < [Link](); i++) {
if (i % 2 == 0) {
[Link]([Link](i));
}
}

}
}

Enter a string: Automation

Even indexed characters in "Automation":

Atmto
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

12.) Java program to remove space from a


given string

import [Link];

public class Main {


public static
Scanner void main(String[]
scanner args) {
= new Scanner([Link]);
[Link]("Enter a string with spaces: ");
String input = [Link]();
String stringWithoutSpaces = removeSpaces(input);
[Link]("String without spaces: " +

stringWithoutSpaces);
}
public static String removeSpaces(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < [Link](); i++) {
if ([Link](i) != ' ') {
[Link]([Link](i));
}
}
return [Link]();
}
}

Enter a string with spaces: Welcome to Java World


String without spaces: WelcometoJavaWorld
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

13.) Java program to print each letter twice


from a given string

import [Link];

public class Main {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
String doubledString = doubleCharacters(input);
[Link]("Doubled characters: " + doubledString);
}

public static String doubleCharacters(String str) {

StringBuilder doubled = new StringBuilder();


for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
[Link](ch).append(ch); // Append each character
twice
}
return [Link]();
}
}

Enter a string: hello


Doubled characters: hheelllloo
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

14.) Java program to swap two string without


using 3rd variable
import [Link];

public class Main {


public static voidscanner
Scanner main(String[]
= args)new{ Scanner([Link]);
[Link]("Enter first string: "); String str1 =
[Link](); [Link]("Enter second string:
"); String str2 = [Link]();
[Link]("Before swapping: str1 = " + str1 + ",

str2 = " + str2);


// Swapping without using a third variable
str1 = str1 + str2; // Concatenate str1 and str2 and
store in str1
str2
// Extract =
the [Link](0, [Link]()
initial part (original - [Link]());
str1) from the concatenated
string
str1 = [Link]([Link]()); // Extract the
remaining part (original str2) from the concatenated string

out
System. .println("After swapping: str1 = " + str1 + ",
str2 = " + str2);
}
}

Enter first string:Hello

Enter second string:World

Before swapping: str1= Hello, str2= World

After swapping: str1= World, str2= Hello


Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

15.) Java program to gives Output: a2b2c3d2


for the Input String Str = “aabbcccdd”

import [Link];

public class Main {


public static
Scanner void main(String[]
scanner args) {
= new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
String output = getCharacterCount(input);
[Link]("Output: " + output);

public static String getCharacterCount(String str) {


StringBuilder result = new StringBuilder();
int count = 1;

for //
(int
Ifithe
= 0; i <character
next [Link](); i++)
is the { increase the count
same,
if (i + 1 < [Link]() && [Link](i) == [Link](i
+ 1)){
count++;
} else {
//Appendthecharacteranditscounttothe result
[Link]([Link](i)).append(count);
count = 1; // Reset the count
}
}

return [Link]();
}
}

Enter a string: aabbcccdd

Output: a2b2c3d2
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

16.) Java program to gives two Output:


“abcde”, “ABCDE” for the Input
String Str = “aBACbcEDed”

import [Link];

public class Main {


public static
Scanner void =
scanner main(String[] args) {
new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
[Link]("Original String is: "+ input);
separateCharacters(input);
}

public static void separateCharacters(String input)


{
StringBuilder lowerCase = new StringBuilder();
StringBuilder upperCase = new StringBuilder();

for(char ch : [Link]())
{ if([Link](ch))
{
[Link](ch);
}
else
{
[Link](ch);
}
}
[Link]("Output in lowercase: "+lowerCase);
[Link]("Output in uppercase "+upperCase);
}

Enter a string: aBACbcEDed

Output in lowercase: abced

Output in uppercase: ABCED


Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

17.) Java program to gives two Output:


“Subburaj”, “123” for the Input
String Str = “Subbu123raj”

import [Link];

public class Main {


public static
Scanner void =
scanner main(String[] args) {
new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
[Link]("Original String is: "+ input);
separateAplhaAndNumeric(input);
}

public static void separateAlphaAndNumeric(String input)


{
StringBuilder alphaPart = new StringBuilder();
StringBuilder numericPart = new StringBuilder();

for(char ch : [Link]())
{ if([Link](ch))
{
[Link](ch);
}
else if ([Link](ch))
{
[Link](ch);
}
}
[Link]("Output in Alpha: "+[Link]());
[Link]("Output in Numeric:
"+[Link]());
}

Enter a string: Subbu123raj

Output in lowercase: Subburaj

Output in uppercase: 123


Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

18.) Java program to gives Output:


“32412120000” for the Input
String Str = “32400121200”
public class Main {
public static void main(String[] args) {
String input = "32400121200";
String output = rearrangeDigits(input);
[Link]("Output: " + output);
}

public static String rearrangeDigits(String input){


//Splittheinputintoparts:digitsandnon-digits
StringBuilder digits = new StringBuilder();
StringBuilder nonDigits = new StringBuilder();
for (char c : [Link]()) {
if ([Link](c)) {

[Link](c);
} else {
[Link](c);
}
}
// Concatenate non-digits followed by digits
return [Link]() + [Link]();
}
}
Output:32412120000

19.) Java program to gives Output:


“00003241212” for the Input
String Str = “32400121200”
public class Main {
public static void main(String[] args) {
String input = "32400121200";
String formattedOutput = [Link]("%011d",
[Link](input));
[Link]("Formatted output: " + formattedOutput);
}
}
Formatted output: 00003241212
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

20.) Java program to find the longest without


repeating characters

import [Link];

public class Main {


public static
String void
s1 = main(String[]
"abcabcbb"; args) { "abc", length 3
// Expected:
// Expected: "b", length 1
String s2 = "bbbbb"; // Expected: "wke", length 3
String s3 = "pwwkew"; // Expected: "", length 0
String s4 = "";
[Link]("Longest substring without repeating
characters in s1: " + lengthOfLongestSubstring(s1)); // Output:3
[Link]("Longest substring without repeating
characters in s2: " + lengthOfLongestSubstring(s2)); // Output:1
[Link]("Longest substring without repeating
characters in s3: " + lengthOfLongestSubstring(s3)); // Output:3
[Link]("Longest substring without repeating
characters in s4: " + lengthOfLongestSubstring(s4)); // Output:0

public static int lengthOfLongestSubstring(String s) {


HashSet<Character> set = new HashSet<>();
int maxLength = 0;
int start = 0;
int end = 0;

while (end < [Link]()) {


char currentChar = [Link](end);
if (![Link](currentChar)) {
[Link](currentChar);
maxLength = [Link](maxLength, end - start + 1);
end++;
} else {
[Link]([Link](start));
start++;
}
}

return maxLength;
}
}
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

Arrays

1.) Find common elements between


two arrays
import [Link];
import [Link];

public class CommonElements {


public static void main(String[] args) {
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {4, 5, 6, 7, 8};
Set<Integer> commonElements = findCommonElements(array1,
array2);
[Link]("Common elements: " + commonElements);
}

public static Set<Integer> findCommonElements(int[] array1,


int[] array2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> commonSet = new HashSet<>();
// Add elements of the first array to the set

for (int num : array1) {


[Link](num);
}
//Checkforcommonelementsin the second array
for (int num : array2) {
if ([Link](num)){
[Link](num);
}
}

return commonSet;
}
}

Input: array1 = {1,2,3,4,5} and


array2 = {4,5,6,7,8}
Output: Common elements: [4, 5]
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

2.) Find first and last element of


Arraylist

import [Link];

public class Main {


public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Date");
[Link]("Elderberry");

if (![Link]()) {
String firstElement = [Link](0);
String lastElement = [Link]([Link]() - 1);
[Link]("First element: " + firstElement);
[Link]("Last element: " + lastElement);
} else {
[Link]("The ArrayList is empty.");
}
}
}

Output:
First element: Apple
Last element: Elderberry
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

3.) Sort an array without using in-built


method

public class Main {


public static void main(String[] args) {
int[] array = {5, 2, 9, 1, 6};
selectionSort
(array);
[Link]("Sorted array:");

[Link](num
(int num : array) { + " ");

}
}

public static void selectionSort(int[] array){


int n = [Link];
for (int i = 0; i < n - 1; i++){
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]){
minIndex = j;
}
}
// Swap array[i] and array[minIndex]

int temp = array[i];


array[i] = array[minIndex];
array[minIndex] = temp;
}
}
}

Output:
Sorted array:
12569
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

4.) Remove duplicates from an Array

import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
int[] array = {5, 2, 9, 1, 6, 2, 5};

int[] uniqueArray = removeDuplicates(array);

[Link]("Array with duplicates removed:");


for (int num : uniqueArray) {
[Link](num + " ");
}
}
public static int[] removeDuplicates(int[] array) {
Set<Integer> set = new HashSet<>();
for (int num : array) {
[Link](num);
}

int[] result = new int[[Link]()];


int i = 0;
for (int num : set) {
result[i++] = num;
}

return result;
}
}

Output:
Array with duplicates removed:
12569
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

5.) Remove duplicates from an


ArrayList

import [Link];
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
[Link](5);
[Link](2);
[Link](9);
[Link](1);
[Link](6);
[Link](2);
[Link](5);

ArrayList<Integer> uniqueList =
removeDuplicates
(arrayList);
[Link]("ArrayList with duplicates
removed:");
for [Link](num
(int num : uniqueList) { ");
+ "

}
}
public static ArrayList<Integer>
removeDuplicates(ArrayList<Integer> list) {
Set<Integer> set = new HashSet<>(list);
return new ArrayList<>(set);
}
}

Output:
ArrayList with duplicates removed:
12569
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

6.) Find the missing number in an Array

public class Main {


public
int[]static void
array = {1,main(String[] args)
2, 4, 5, 6}; // {
Missing number is 3
int missingNumber = findMissingNumber(array);
[Link]("The missing number is: " + missingNumber);
}

public static int findMissingNumber(int[] array){


//Sinceonenumber is missing, the length
int n
should be n+1 = [Link] + 1;
//Sumoffirst n natural numbers
int totalSum = n * (n + 1) / 2;

int arraySum = 0;
for (int num : array) {
arraySum += num;
}
return totalSum - arraySum;
}
}

Output:
The missing number is: 3
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

7.) Find the largest and smallest


element in an Array
public class Main {

public static void main(String[] args){


int[] array = {5, 2, 9, 1, 6, 3};
findLargestAndSmallest
int[] result = (array);
out
[Link]("Smallest element: " + result[0]);
System. .println("Largest element: " + result[1]);
}

public static int[] findLargestAndSmallest(int[] array) {


if (array == null || [Link] == 0) {
throw new IllegalArgumentException("Array must not be null or
empty");
}

int smallest = array[0];


int largest = array[0];

for (int num : array) {


if (num < smallest) {
smallest = num;
}
if (num > largest) {
largest = num;
}
}
return new int[]{smallest, largest};
}
}

Output:
Smallest element: 1
Largest element: 9
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

8.) Search element in an Array


publicclass Main {
public static void main(String[] args) {
int[] array = {5, 2, 9, 1, 6, 3};
int target = 6;
int index = linearSearch(array, target);

[Link]("Element
(index != -1) { " + target + " found at index:" +
index);
} else {
[Link]("Element " + target + " not found in the
array.");
}
}

public static int linearSearch(int[] array, int target) {


for (int i = 0; i < [Link]; i++) {
if (array[i]
return i;==
//target)
Element{found, return index
}
}
return -1; // Element not found
}
}

Output:
Element 6 found at index: 4
Element 10 not found in the array
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

9.) Array consists of integers and special


characters,sum only integers

public class Main {


public static void main(String[] args) {
String[] array = {"5", "2", "9", "a", "1", "6", "#", "3"};
int sum = sumIntegers(array);

[Link]("Sum of integers in the array: " + sum);


}

public static int sumIntegers(String[] array){


int sum = 0;
for (String element : array) {
tryint
{ num = [Link](element);
sum += num;

} catch (NumberFormatException
// Ignore e) {
non-integer elements
}
}
return sum;
}
}

Output:
Sum of integers in the array: 26
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

10.) Find Minimum and Maximum


from an Array
public class Main {
public static void main(String[] args){
int[] array = {5, 2, 9, 1, 6, 3};
// Find maximum and minimum
int max = findMaximum
int min = findMinimum(array);
(array);
// Print the results
out
[Link]("Minimum value in the array: " + min);
System. .println("Maximum value in the array: " + max);
}
public static int findMaximum(int[] array) {
if ([Link] == 0) {
throw new IllegalArgumentException("Array must not be empty");
}
int max = array[0]; // Initialize max to the first element
for (int i = 1; i < [Link]; i++) {
if (array[i] > max) //
max = array[i]; { Update max if current element is larger

}
}
return max;
}
public static int findMinimum(int[] array) {
if ([Link] == 0) {
throw new IllegalArgumentException("Array must not be empty");
}
int min = array[0]; // Initialize min to the first element
for (int i = 1; i < [Link]; i++) {
if (array[i] < min) //Updateminifcurrentelementissmaller
{
min = array[i];
}
}
return min; }
}

Output:
Minimum value in the array: 1
Maximum value in the array: 9
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

11.) Java program to count Odd and


Even number from given array
Input: {1,2,3,4,5,6,7,8,9}

public class Main {


public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] count = countOddAndEven(array);

[Link]("Even numbers count: " + count[1]);


[Link]("Odd numbers count: " + count[0]);
}

public static int[] countOddAndEven(int[] array) {


//Index0foroddcount,Index 1 for
even count int[] count = new int[2];

for (int num : array){


if (num % 2 == //Increment
0){ even count
count[1]++;
} else { //Increment odd count
count[0]++;
}
}
return count;
}
}

Output:
Even numbers count: 4

Odd numbers count:5


Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

12.) Java program – input array was


given [ 1,1,2,2,3,4,5,5,6,6],
Output – [3,4]
import [Link];
import [Link];
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
int[] array = {1, 1, 2, 2, 3, 4, 5, 5, 6, 6};
List<Integer> result = findNonRepeatedElements(array);
[Link]("Non-repeated elements: " + result);
}

public static List<Integer> findNonRepeatedElements(int[]


array) {
// Step 1: Count occurrences of each element usinga
HashMap
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : array) {
[Link](num, [Link](num, 0) + 1);
}
// Step2:Identifyelementswithcountequalto 1 (non-
repeated)
List<Integer> nonRepeatedElements = new ArrayList<>();
for ([Link]<Integer, Integer> entry :
[Link]()) {
if ([Link]() == 1) {
[Link]([Link]());
}
}
return nonRepeatedElements;
}
}

Output :
Non-repeated elements: [3, 4]
Recursive Coders Bengaluru
Premium Structured Courses for ‘Tech Career’

Java program to implement hashcode


and equals
import [Link];

public class Student {


private int id;
private String name;
// Constructor
public Student(int id, String name){
[Link] = id;
[Link] = name;
}
// Getters and setters (omitted for brevity)

// hashCode method
@Override
public int hashCode() {
return [Link](id, name);
}
// equals method
@Override
public boolean equals(Object obj) {

if (this == obj)
return true;
if (obj == null || getClass() != [Link]())
return false;
Student student = (Student) obj;
return id == [Link] && [Link](name, [Link]);
}

public static void main(String[] args) {


// Creating objects of Student class
Student student1 = new Student(1, "Alice");
Student student2 = new Student(2, "Bob");
Student student3 = new Student(1, "Alice");
// Testing equals method
out
System. .println("[Link](student2):"
// Output: false +
[Link](student2));
out
System. .println("[Link](student3):"
// Output: true +
[Link](student3));
// Testing hashCode method
out
[Link]("Hashcode of student1: " + [Link]());
[Link]("Hashcode of student2: " + [Link]());
System. .println("Hashcode of student3: " + [Link]());
}
}

You might also like