0% found this document useful (0 votes)
6 views37 pages

Instagram - Java Programs

The document contains a collection of Java programs aimed at preparing for SDET interviews, covering various topics such as finding odd/even numbers, prime numbers, Fibonacci series, and string manipulations. Each program is accompanied by code snippets and explanations, demonstrating fundamental programming concepts. The document serves as a practical guide for aspiring automation engineers to enhance their coding skills.
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)
6 views37 pages

Instagram - Java Programs

The document contains a collection of Java programs aimed at preparing for SDET interviews, covering various topics such as finding odd/even numbers, prime numbers, Fibonacci series, and string manipulations. Each program is accompanied by code snippets and explanations, demonstrating fundamental programming concepts. The document serves as a practical guide for aspiring automation engineers to enhance their coding skills.
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

TheAutomationEngineer

Crack the Interview


Top SDET
Java Programs

[Link] Odd Even [Link] Number


[Link] number [Link]
[Link] series [Link]
[Link] two num. [Link] the String Prog.
[Link] [Link] the Array Prog.
By Achal Singh
TheAutomationEngineer

1.) Java program to Find Odd or Even number


[Link];

publicclass OddEven {
public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);


[Link]("Enter any number: ");
intnumber = [Link]();

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

2.) Java program to find Prime number


[Link];
public class PrimeNumber {

publicstaticvoidmain(String[]args){
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
if (isPrime(number)) {
[Link](number+"isaprimenumber.");
} else {
[Link](number+"isnotaprime number.");
}
}

public static boolean isPrime(int num) {


for (int i = 2; i <= num / 2; i++) {
//try each number by using %
if (num % i == 0) {
return false;
}
} return true;
}

By Achal Singh
TheAutomationEngineer

3.) Java program to find Fibonacci series upto a


given number range
import [Link];

public class PrimeNumber {


publicstaticvoidmain(String[]args) {
Scannersc=newScanner([Link]);
[Link]("enternumberof terms");
int number = 6;
int first = 0, second = 1, next;
[Link]("Fibonacciseries 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
[Link];

publicclassSwapNumbers {
publicstaticvoid main(String[] args) {

Scannerscanner=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

By Achal Singh
TheAutomationEngineer

5.) Java program to Find Factorial on given Number


import [Link];

public class FactorialNumber{


public static void main(String[] args) {
intfactorial =1;
Scanner scanner = new Scanner([Link]);
[Link]("Enter any number ");
intnumber = 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.) Javaprogram 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

By Achal Singh
TheAutomationEngineer

7.) Javaprogram 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) {

intno = 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);}

By Achal Singh
TheAutomationEngineer

9.) Java program to find Palindrome number

import [Link];

public class Main {


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

if (isPalindrome(number)) {
[Link](number+"isapalindrome.");
} else {
[Link](number+"isnotapalindrome.");
}
}

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.

By Achal Singh
TheAutomationEngineer

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]("Sumofdigitsof"+number+"is: " +
sumOfDigits);
}

public static int calculateSumOfDigits(int number) {


int sum = 0;
while (number > 0) {
intdigit=number%10;//Extractthelastdigit
sum = sum + digit; // Add the digit to sum
number=number/10;//Removethelastdigitfrom number
}
return sum;
}
}

Output:
Sumofdigitsof12345 is: 15

By Achal Singh
TheAutomationEngineer

Strings
1.) Javaprogram to reverse a string
import [Link];
public class Test {
publicstaticvoidmain(String[] args) {
Scannerscanner=newScanner([Link]);
[Link]("Enterastring: ");
Stringinput=[Link]();
char ch;
String nstr = "";
for(inti=0;i<[Link](); i++) {
ch = [Link](i);
nstr = ch + nstr;
}
[Link]("ReversedString is : " + nstr);

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


string
public static void main(String[] args) {
reverseEachWordOfString("Javaisgoodprogramming langauges");
}
staticvoidreverseEachWordOfString(StringinputString)
{
String[] words = [Link](" ");

String reverseString = "";


for (int i = 0; i < [Link]; i++) {
String word = words[i];
String nstr = "";
char ch;
for(intj=0;j<[Link]();j++) {
ch = [Link](j);
nstr = ch + nstr;
}
reverseString = reverseString + nstr + " ";
}

[Link](inputString);
[Link](reverseString);
}

Input: Java is good programming langauges


Output: avaJ si doog gnimmargorp seguagnal

By Achal Singh
TheAutomationEngineer

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=newHashMap<>();
char[] strArray = [Link]();
for (char c : strArray) {
if ([Link](c)) {
[Link](c, [Link](c) + 1);
} else {
[Link](c, 1);
}
}

Set<Character> charsInString = [Link]();


[Link]("DuplicateCharactersin:"+inputString);
for (Character ch : charsInString) {
if ([Link](ch) > 1) {
[Link](ch+":"+[Link](ch));
}
}
}
}

Duplicate Characters in : Learn Java Programming

a : 4 g : 2 m : 2 n : 2 r : 3

By Achal Singh
TheAutomationEngineer

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);
{ }

[Link](s,1);

}
[Link]("Count of Characters in a given string:"+
charCountMap);
}
}
CountofCharacters in a given string : {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[] args) {
[Link]("Enter 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

By Achal Singh
TheAutomationEngineer

6.) Java program to find all permutations of a


given string

import [Link];

public class Main {


publicstaticvoidmain(String[]args) {
String str = "abc";
permute(str, "");
}

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

abc

acb

bac

bca

cab

cba

By Achal Singh
TheAutomationEngineer

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

[Link];

public class Main {


publicstaticvoidmain(String[] args) {
Stringstr="madam";
[Link](isPalindrome(str));
}

staticbooleanisPalindrome(String str) {
int start = 0;
intend=[Link]() - 1;

while(start<end) {
if([Link](start) != [Link](end)){
returnfalse;
}
start++;
end--;
}
return true;
}
}

By Achal Singh
TheAutomationEngineer

8.) Java program to determine if Two Strings are


Anagrams

public class Main {

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

staticbooleanareAnagrams(String str1, String str2){


if([Link]()!=[Link]())
{ }
return false;
int[]charCount=newint[256];
for(inti=0;i<[Link](); i++)
{

charCount[[Link](i)]++;
charCount[[Link](i)]--;
}
for(intcount:charCount)
{
if ( count !=0 )
{ }
return false;

}
return true;
}
}

By Achal Singh
TheAutomationEngineer

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

By Achal Singh
TheAutomationEngineer

10.) Java program to print unqiue characters

import [Link];

public class Main {


public static void main(String[] args) {
Scannerscanner=newScanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();

[Link]("Uniquecharactersin \"" + input + "\":");


printUniqueCharacters(input);

publicstaticvoidprintUniqueCharacters(String str) {
//AssumeASCIIcharacters(0-127),useboolean array to track
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 + " ");
}
}

}
}

Enterastring:JavaAutomation

Uniquecharactersin"Java Automation":

Jav Automin

By Achal Singh
TheAutomationEngineer

11.) Java program to print even indexed


characters

[Link];

public class Main {


publicstaticvoidmain(String[] args) {
Scannerscanner=new Scanner([Link]);
[Link]("Enter a string: ");
Stringinput=[Link]();

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


printEvenIndexedCharacters(input);

publicstaticvoidprintEvenIndexedCharacters(String str){
for(inti=0;i<[Link](); i++) {
if(i%2==0){
[Link]([Link](i));
}
}

}
}

Enter a string: Automation

Evenindexedcharactersin"Automation":

Atmto

By Achal Singh
TheAutomationEngineer

12.) Java program to remove space from a


given string

import [Link];

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enterastringwithspaces:");
String input = [Link]();

StringstringWithoutSpaces=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

By Achal Singh
TheAutomationEngineer

13.) Java program to print each letter twice


from a given string

import [Link];

public class Main {

publicstaticvoidmain(String[]args) {

Scannerscanner=newScanner([Link]);
[Link]("Enterastring: ");
Stringinput=[Link]();

StringdoubledString=doubleCharacters(input);
[Link]("Doubledcharacters: " + doubledString);
}

publicstaticStringdoubleCharacters(String str) {

StringBuilderdoubled=newStringBuilder();
for(inti=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

By Achal Singh
TheAutomationEngineer

14.) Java program to swap two string without


using 3rd variable
import [Link];

public class Main {


public static void main(String[] args) {
Scanner scanner = 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 = [Link](0, [Link]() - [Link]());
// Extract the initial part (original str1) from the concatenated
string
str1 = [Link]([Link]()); // Extract the
remaining part (original str2) from the concatenated string

[Link]("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

By Achal Singh
TheAutomationEngineer

15.) Java program to gives Output: a2b2c3d2


for the Input String Str = “aabbcccdd”

import [Link];

public class Main {


public static void main(String[] args) {
Scanner scanner = 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 i = 0; i < [Link](); i++) {
// If the next character is the same, increase the count
if (i + 1 < [Link]() && [Link](i) == [Link](i
+ 1)) {
count++;
} else {
//Appendthecharacteranditscounttotheresult
[Link]([Link](i)).append(count);
count = 1; // Reset the count
}
}

return [Link]();
}
}

Enter a string: aabbcccdd

Output: a2b2c3d2

By Achal Singh
TheAutomationEngineer

16.) Java program to gives two Output:


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

import [Link];

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
[Link]("OriginalStringis:"+ 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);
{ }

[Link](ch);

}
[Link]("Outputinlowercase:"+lowerCase);
[Link]("Outputinuppercase"+upperCase);
}

Enter a string: aBACbcEDed

Output in lowercase: abced

Output in uppercase: ABCED

By Achal Singh
TheAutomationEngineer

17.) Java program to gives two Output:


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

import [Link];

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
[Link]("OriginalStringis:"+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);
if ([Link](ch))
{ }

[Link](ch);

[Link]("OutputinAlpha:"+[Link]());
[Link]("Output in Numeric:
"+[Link]());
}

Enter a string: Subbu123raj

Output in lowercase: Subburaj

Output in uppercase: 123

By Achal Singh
TheAutomationEngineer

18.) Java program to gives Output:


“32412120000” for the Input
String Str = “32400121200”
public class Main {
publicstaticvoidmain(String[] args) {
Stringinput="32400121200";
Stringoutput=rearrangeDigits(input);
[Link]("Output: " + output);
}
publicstaticStringrearrangeDigits(String input) {
//Splittheinputinto parts: digits and non-digits
StringBuilderdigits = new StringBuilder();
StringBuildernonDigits = new StringBuilder();
for(charc:[Link]()) {
if([Link](c)) {
[Link](c);
} else {
[Link](c);
}
}

//Concatenatenon-digits followed by digits


[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

By Achal Singh
TheAutomationEngineer

20.) Java program to find the longest without


repeating characters

import [Link];

public class Main {


publicstaticvoidmain(String[]args) {
Strings1="abcabcbb";//Expected: "abc", length 3
Strings2="bbbbb"; //Expected: "b", length 1
Strings3="pwwkew"; //Expected: "wke", length 3
Strings4=""; //Expected: "", length 0

[Link]("Longestsubstring without repeating


charactersins1:"+lengthOfLongestSubstring(s1)); // Output:3
[Link]("Longestsubstring without repeating
charactersins2:"+lengthOfLongestSubstring(s2)); // Output:1
[Link]("Longestsubstring without repeating
charactersins3:"+lengthOfLongestSubstring(s3)); // Output:3
[Link]("Longestsubstring without repeating
charactersins4:"+lengthOfLongestSubstring(s4)); // Output:0
}

publicstaticintlengthOfLongestSubstring(String s) {
HashSet<Character>set=newHashSet<>();
int maxLength = 0;
int start = 0;
int end = 0;

while (end < [Link]()) {


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

return maxLength;
}
}

By Achal Singh
TheAutomationEngineer

Arrays
1.) Find common elements between
two arrays
import [Link];
import [Link];
publicclassCommonElements {
publicstaticvoid 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);


}
publicstaticSet<Integer> findCommonElements(int[] array1,
int[] array2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> commonSet = new HashSet<>();
//Addelements of the first array to the set
for(intnum : array1) {
[Link](num);
}
//Checkfor common elements in the second array
for(intnum : 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]

By Achal Singh
TheAutomationEngineer

2.) Find first and last element of


Arraylist

[Link];

publicclass 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

By Achal Singh
TheAutomationEngineer

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:");
for (int num : array) {
[Link](num + " ");
}
}

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

By Achal Singh
TheAutomationEngineer

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]("Arraywithduplicates removed:");
for (int num : uniqueArray) {
[Link](num + " ");
}
}

publicstaticint[]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

By Achal Singh
TheAutomationEngineer

5.) Remove duplicates from an


ArrayList

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

removeDuplicates(arrayList);

[Link]("ArrayListwithduplicates
removed:");
for (int num : uniqueList) {
[Link](num + " ");
}
}
public static ArrayList<Integer>
removeDuplicates(ArrayList<Integer> list) {
Set<Integer>set=newHashSet<>(list);
return new ArrayList<>(set);
}
}

Output:
ArrayList with duplicates removed:
12569

By Achal Singh
TheAutomationEngineer

6.) Find the missing number in an Array

public class Main {


publicstaticvoidmain(String[] args) {
int[]array={1,2,4,5, 6}; // Missing number is 3
intmissingNumber=findMissingNumber(array);
[Link]("Themissing number is: " + missingNumber);
}

publicstaticintfindMissingNumber(int[] array) {
intn=[Link]+1;//Since one number is missing, the length
should be n+1
inttotalSum=n*(n+1)/2; // Sum of first n natural numbers
int arraySum = 0;
for (int num : array) {
arraySum += num;
}
return totalSum - arraySum;
}
}

Output:
The missing number is: 3

By Achal Singh
TheAutomationEngineer

7.) Find the largest and smallest


element in an Array
public class Main {
publicstaticvoidmain(String[]args) {
int[]array={5,2,9,1,6,3};

int[]result=findLargestAndSmallest(array);

[Link]("Smallestelement: " + result[0]);


[Link]("Largestelement: " + result[1]);
}

publicstaticint[]findLargestAndSmallest(int[] array) {
if(array==null||[Link] == 0) {
thrownewIllegalArgumentException("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;
}
}
returnnewint[]{smallest,largest};
}
}

Output:
Smallest element: 1
Largest element: 9

By Achal Singh
TheAutomationEngineer

8.) Search element in an Array


public class Main {
publicstaticvoidmain(String[] args) {
int[]array={5,2, 9, 1, 6, 3};
int target = 6;

intindex=linearSearch(array, target);

if (index != -1) {
[Link]("Element " + target + " found at index:"+
index);
} else {
[Link]("Element " + target + " not found in the
array.");
}
}
publicstaticintlinearSearch(int[] array, int target) {
for(inti=0;i<[Link]; i++) {
if(array[i]==target) {
returni;//Element found, return index
}
}
return-1;//Elementnot found
}
}

Output:
Element 6 found at index: 4
Element 10 not found in the array

By Achal Singh
TheAutomationEngineer

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]("Sumofintegersinthearray: " + sum);


}

public static int sumIntegers(String[] array) {


int sum = 0;
for (String element : array) {
try {
int num = [Link](element);
sum += num;
} catch (NumberFormatException e) {
// Ignore non-integer elements
}
}
return sum;
}
}

Output:
Sum of integers in the array: 26

By Achal Singh
TheAutomationEngineer

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(array);
int min = findMinimum(array);

// Print the results


[Link]("Minimumvalueinthearray: " + min);
[Link]("Maximumvalueinthearray: " + max);
}
public static int findMaximum(int[] array) {
if ([Link] == 0) {
thrownewIllegalArgumentException("Array must not be empty");
}
intmax=array[0];//Initializemaxtothe first element
for (int i = 1; i < [Link]; i++) {
if (array[i] > max) {
max=array[i];//Updatemaxifcurrent element is larger
}
}
return max;
}
public static int findMinimum(int[] array) {
if ([Link] == 0) {
thrownewIllegalArgumentException("Array must not be empty");
}
intmin=array[0];//Initializemintothe first element
for (int i = 1; i < [Link]; i++) {
if (array[i] < min) {
min=array[i];//Updateminifcurrent element is smaller
}
}
returnmin; }
}

Output:
Minimum value in the array: 1
Maximum value in the array: 9

By Achal Singh
TheAutomationEngineer

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]("Evennumberscount:"+count[1]);
[Link]("Oddnumberscount:"+count[0]);
}

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


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

for (int num : array) {


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

Output:
Even numbers count:4

Odd numbers count:5

By Achal Singh
TheAutomationEngineer

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 using a


HashMap
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : array) {
[Link](num, [Link](num, 0) + 1);
}
// Step 2: Identify elements with count equal to 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]

By Achal Singh
TheAutomationEngineer

Java program to implement hashcode


and equals
import [Link];

public class Student {


private int id;
private String name;

// Constructor
publicStudent(intid,String name) {
[Link] = id;
[Link] = name;
}

//Gettersandsetters(omitted for brevity)

// hashCode method
@Override
public int hashCode() {
[Link](id, name);
}

// equals method
@Override
publicbooleanequals(Object obj) {
if (this == obj)
return true;
if(obj==null||getClass() != [Link]())
return false;
Studentstudent=(Student) obj;
returnid==[Link] && [Link](name, [Link]);
}
publicstaticvoidmain(String[] args) {
//Creatingobjectsof Student class
Studentstudent1=new Student(1, "Alice");
Studentstudent2=new Student(2, "Bob");
Studentstudent3=new Student(1, "Alice");

//Testingequalsmethod
[Link]("[Link](student2): " +
[Link](student2));// Output: false
[Link]("[Link](student3): " +
[Link](student3));// Output: true

//TestinghashCodemethod
[Link]("Hashcode of student1: " + [Link]());
[Link]("Hashcode of student2: " + [Link]());
[Link]("Hashcode of student3: " + [Link]());
}
}

By Achal Singh

You might also like