Java Coding Examples
Java Coding Examples
til
Scanner scanner = new Scanner(System.in);
System.out.print("Enter any number: ");
int number = scanner.nextInt();
if (number % 2 == 0) {
}
}
} Pa
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
if (isPrime(number)) {
Pa
til
{
System.out.println(first + "");
next = second+first;
first = second;
second = next;
}
}
Output: 0 1 1 2 3 5 8 Pa
4.) Java program to swap two numbers without
using third variable
g
import java.util.Scanner;
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping: a = " + a + ", b = " + b);
}
}
import java.util.Scanner;
public
static void
main(String[
] args) {
int
factorial
til
=1;
Scanner
scanner = new
Scanner(Syste
m.in);
Input: 5!
Pa }
System.out.p
rint("Enter
any number
"); int
number = 5;
for (int i =
1; i <=
number;
i++){
g
factorial =
factorial *
i;
}
ra
System.out.println("Factorial
number is :" +factorial);
}
Output: 5! = 5*4*3*2*1 = 120
Pa
{
r = no%10; rev
= rev*10+r;
no=no/10;
}
}
}
Input: 15786
Output: 68751
til
Pa
g
ra
Pa
import java.util.Scanner;
public class ArmstrongNumber {
til
{
a = no%10;
no = no/10;
arm =arm+a*a*a;
}
}
}
if(arm==d){
else{ Pa
System.out.println("Armstrong number”);
}
import java.util.Scanner;
public class NumberOfDigits {
int no = 0, a = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter any number : ");
no = scanner.nextInt();
if(no<0)
{
no = no * -1;
} else if (no==0) {
no=1;
}
while(no>0)
{
no=no/10;
a++;}
System.out.println("Number of digits in given number is :" +a); }
if (isPalindrome(number)) {
System.out.println(number + " is a palindrome.");
til
} else {
System.out.println(number + " is not a palindrome.");
}
}
int reversedNumber = 0;
while (num != 0) {
int digit = num % 10;
Pa
public static boolean isPalindrome(int num) {
int originalNumber = num;
1001 is a palindrome.
til
sumOfDigits);
}
}
}
while (number > 0) {
} Pa
int digit = number % 10; // Extract the last digit
sum = sum + digit; // Add the digit to sum
number = number / 10; // Remove the last digit from number
return sum;
g
ra
Output:
Sum of digits of 12345 is: 15
Pa
Strings
til
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
char ch;
String nstr = "";
}
nstr = ch + nstr;
Pa
for (int i = 0; i < input.length(); i++) {
ch = input.charAt(i);
System.out.println(inputString);
System.out.println(reverseString);
}
til
Pa
g
ra
Pa
string
import java.util.HashMap;
import java.util.Set;
til
public class Main {
Pa
static void duplicateCharacterCount(String inputString) {
}
}
}
a : 4
g : 2
m : 2
n : 2
Parag Patil | [email protected] | 7666170317 | https://topmate.io/parag_patil02
r : 3
til
Pa
g
ra
Pa
Character in String
import java.util.HashMap;
til
public class Main {
{
Pa
static void CharacterCount(String inputString) {
HashMap<String,Integer> charCountMap = new HashMap<>();
for(String s : inputString.split(" "))
if(charCountMap.containsKey(s))
{
}
charCountMap.put(s,charCountMap.get(s)+1);
else
{
g
charCountMap.put(s,1);
}
}
System.out.println("Count of Characters in a given string : " +
ra
charCountMap);
}
}
Count of Characters in a given string : {Java=1, Automation=2, Test=1}
a string
public class Main {
public static void main(String[] args) {
System.out.println("Enter the String");
Scanner sc = new Scanner(System.in); String
s = sc.nextLine();
int count = 1;
}
System.out.println("Number of words in a string: " +count); }
}
Enter the String: Welcome to Java World Number
of words in a string: 4
til
Pa
g
ra
Pa
given string
til
import java.util.Scanner;
}
permute(str, "");
Pa
public static void main(String[] args) {
String str = "abc";
}
}
Pa
abc
acb
bac
bca
cab
cba
import java.util.Scanner;
til
public class Main {
public static void main(String[] args) {
String str = "madam";
System.out.println(isPalindrome(str));
}
int start = 0;
Pa
static boolean isPalindrome(String str) {
}
Pa
til
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
System.out.println(areAnagrams(str1,str2));
}
}
return false;
Pa
static boolean areAnagrams(String str1, String str2) {
if(str1.length() != str2.length())
{
{
if ( count !=0 )
{
return false;
}
}
return true;
Pa
}
}
in a given string
til
public class Main {
public static void main(String[] args) {
String str = "Hello World";
VowelConsonantCount(str);
{
}
str = str.toLowerCase();
Pa
static void VowelConsonantCount(String str) {
int vowels = 0, consonants = 0;
vowels++;
} else {
g
consonants++;
}
}
}
ra
Vowels : 3
Consonants : 7
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
til
System.out.println("Unique characters in \"" + input + "\":");
printUniqueCharacters(input);
Pa
public static void printUniqueCharacters(String str) {
// Assume ASCII characters (0-127), use boolean array to track
character occurrences
boolean[] unique = new boolean[128];
}
}
Pa
J a v A u t o m i n
import java.util.Scanner;
til
System.out.print("Enter a string: ");
String input = scanner.nextLine();
}
Pa
public static void printEvenIndexedCharacters(String str) {
for (int i = 0; i < str.length(); i++) {
if (i % 2 == 0) {
System.out.print(str.charAt(i));
}
}
g
}
}
ra
Atmto
import java.util.Scanner;
til
System.out.print("Enter a string with spaces: ");
String input = scanner.nextLine();
import java.util.Scanner;
til
public static void main(String[] args) {
}
Pa
String input = scanner.nextLine();
}
return doubled.toString();
}
}
Pa
import java.util.Scanner;
til
public class Main {
public static void main(String[] args) { Scanner
scanner = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = scanner.nextLine();
til
import java.util.Scanner;
}
Pa
System.out.print("Enter a string: ");
String input = scanner.nextLine();
+ 1)) { count++;
} else {
// Append the character and its
count to the result
result.append(str.cha
rAt(i)).append(count)
Pa
; count = 1; //
Reset the count
}
}
return result.toString();
}
}
Output: a2b2c3d2
til
import java.util.Scanner;
Pa
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
}
System.out.println("Original String is: "+ input);
separateCharacters(input);
for(char ch : input.toCharArray())
ra
{
if(Character.isLowerCase(ch))
{
lowerCase.append(ch);
}
else
{
Pa
upperCase.append(ch);
}
}
System.out.println("Output in lowercase: "+lowerCase);
System.out.println("Output in uppercase "+upperCase);
}
til
import java.util.Scanner;
Pa
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
}
System.out.println("Original String is: "+ input);
separateAplhaAndNumeric(input);
for(char ch : input.toCharArray())
ra
{
if(Character.isLetter(ch))
{
alphaPart.append(ch);
}
else if (Character.isDigit(ch))
Pa
{
numericPart.append(ch);
}
}
til
String input = "32400121200";
String output = rearrangeDigits(input);
System.out.println("Output: " + output);
}
Pa
public static String rearrangeDigits(String input) {
// Split the input into parts: digits and non-digits
StringBuilder digits = new StringBuilder();
StringBuilder nonDigits = new StringBuilder();
}
}
Output: 32412120000
19.)
Pa
til
Pa
g
ra
Pa
repeating characters
til
import java.util.HashSet;
return maxLength;
}
}
Arrays
til
import java.util.HashSet;
import java.util.Set;
array2);
}
Pa
int[] array2 = {4, 5, 6, 7, 8};
commonSet.add(num);
}
}
return commonSet;
}
}
til
Pa
g
ra
Pa
Arraylist
til
import java.util.ArrayList;
arrayList.add("Cherry");
arrayList.add("Date");
Pa
arrayList.add("Apple"); arrayList.add("Banana");
arrayList.add("Elderberry");
if (!arrayList.isEmpty()) {
String firstElement = arrayList.get(0);
String lastElement = arrayList.get(arrayList.size() - 1);
}
Pa
Output:
method
til
public class Main {
public static void main(String[] args) {
int[] array = {5, 2, 9, 1, 6};
selectionSort(array);
}
} Pa
System.out.println("Sorted array:");
for (int num : array) {
System.out.print(num + " ");
}
}
Output:
Sorted array:
Parag Patil | [email protected] | 7666170317 | https://topmate.io/parag_patil02
12569
til
Pa
g
ra
Pa
import java.util.HashSet;
import java.util.Set;
til
public class Main {
public static void main(String[] args) {
int[] array = {5, 2, 9, 1, 6, 2, 5};
}
}
Pa
System.out.println("Array with duplicates removed:");
for (int num : uniqueArray) {
System.out.print(num + " ");
return result;
}
Pa
Output:
Array with duplicates removed:
12569
Parag Patil | [email protected] | 7666170317 | https://topmate.io/parag_patil02
ArrayList
til
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
Pa
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(5);
arrayList.add(2);
arrayList.add(9);
arrayList.add(1);
arrayList.add(6);
arrayList.add(2);
arrayList.add(5);
g
ArrayList<Integer> uniqueList =
removeDuplicates(arrayList);
removed:");
for (int num : uniqueList) {
System.out.print(num + " ");
}
}
removeDuplicates(ArrayList<Integer> list) {
Set<Integer> set = new HashSet<>(list);
return new ArrayList<>(set);
}
}
Output:
ArrayList with duplicates removed:
Parag Patil | [email protected] | 7666170317 | https://topmate.io/parag_patil02
12569
til
Pa
g
ra
Pa
til
System.out.println("The missing number is: " + missingNumber);
}
should be n+1
int arraySum = 0;
for (int num : array) {
}
arraySum += num;
}
}
g
ra
Output:
Pa
element in an Array
public class Main {
public static void main(String[] args) {
int[] array = {5, 2, 9, 1, 6, 3};
til
int[] result = findLargestAndSmallest(array);
empty");
Pa
public static int[] findLargestAndSmallest(int[] array) {
if (array == null || array.length == 0) {
}
throw new IllegalArgumentException("Array must not be null or
smallest = num;
}
if (num > largest) {
largest = num;
}
Pa
}
return new int[]{smallest, largest};
}
}
Output:
Smallest element: 1
Parag Patil | [email protected] | 7666170317 | https://topmate.io/parag_patil02
Largest element: 9
til
Pa
g
ra
Pa
til
if (index != -1) {
System.out.println("Element " + target + " found at index: " +
index);
} else {
System.out.println("Element " + target + " not found in the
array.");
}
}
Pa
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
}
if (array[i] == target) {
}
return i; // Element found, return index
Output:
Pa
til
String[] array = {"5", "2", "9", "a", "1", "6", "#", "3"};
Pa
public static int sumIntegers(String[] array) {
int sum = 0;
for (String element : array) {
try {
int num = Integer.parseInt(element);
sum += num;
} catch (NumberFormatException e) {
// Ignore non-integer elements
g
}
}
return sum;
}
ra
Output:
Pa
from an Array
public class Main {
public static void main(String[] args) {
int[] array = {5, 2, 9, 1, 6, 3};
til
// Find maximum and minimum
int max = findMaximum(array);
int min = findMinimum(array);
}
Pa
System.out.println("Minimum value in the array: " + min);
System.out.println("Maximum value in the array: " + max);
}
throw new IllegalArgumentException("Array must not be empty");
Output:
til
Pa
g
ra
Pa
til
public class Main {
public static void main(String[] args) { int[]
array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
}
Pa
int[] count = countOddAndEven(array);
i
n
t
n
u
m
:
Pa
a
r
r
a
y
)
{
i
f
(
n
u
m
%
2
=
Parag Patil | [email protected] | 7666170317 | https://topmate.io/parag_patil02
= count
0 } else {
) count[0]++; // Increment odd
{ count
count[1]++; // Increment even
}
}
return count;
}
}
Output:
til
Even numbers count: 4
Pa
g
ra
Pa
given [ 1,1,2,2,3,4,5,5,6,6],
Output – [3,4]
til
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
}
Pa
public static void main(String[] args) {
int[] array = {1, 1, 2, 2, 3, 4, 5, 5, 6, 6};
List<Integer> result = findNonRepeatedElements(array);
System.out.println("Non-repeated elements: " + result);
countMap.getOrDefault(num, 0) + 1);
}
countMap.entrySet()) {
if (entry.getValue() == 1) {
nonRepeatedElements.add(entry.getKey());
}
}
return nonRepeatedElements;
}
}
Output :
Non-repeated elements: [3, 4]
Parag Patil | [email protected] | 7666170317 | https://topmate.io/parag_patil02
and equals
import java.util.Objects;
til
private String name;
// Constructor
public Student(int id, String name) {
this.id = id;
}
this.name = name;
// hashCode method
@Override
public int hashCode() {
return Objects.hash(id, name);
Pa
// Getters and setters (omitted for brevity)
}
g
// equals method
@Override
public boolean equals(Object obj) {
if (this == obj)
ra
return true;
if (obj == null || getClass() != obj.getClass())
return false;
Student student = (Student) obj;
return id == student.id && Objects.equals(name, student.name);
}
Pa
}
}
til
Pa
g
ra
Pa