Program to Sort the characters of a string
package selenium3;
import java.util.Arrays;
import java.util.Scanner;
public class CharAlphabeticOrder {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
try{
System.out.println("Enter the string");
String s = in.nextLine();
char[] chars = s.toCharArray();
Arrays.sort(chars);
System.out.print("String in sorted order:");
for(int i=chars.length-1;i>=0;i--)
{
System.out.print(chars[i]);
}
}
catch(Exception e){
System.out.println(e);
}
finally
{
in.close();
}
}
}
//without using Arrays.sort()
package com.sample.programs;
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
System.out.println("Enter the string:");
Scanner in = new Scanner(System.in);
String str = in.nextLine();
char[] chars = str.toCharArray();
for(int i=0;i<chars.length-1;i++)
{
for (int j=i;j<chars.length;j++)
{
if(chars[i]>chars[j])
{
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
}
String str_final = "";
for(int i=0;i<=chars.length-1;i++)
{
str_final += chars[i];
}
System.out.println(str_final);
}
}
Program to sort the digits of a number
package com.java.programs;
import java.util.ArrayList;
public class SortDigits {
public static void main(String[] args) {
int number = 947863;
ArrayList<Integer>digits = new ArrayList<Integer>();
while(number>0) {
int rem = number % 10;
digits.add(rem);
int num = number / 10;
number = num;
}
for (int i = 0; i < digits.size() - 1; i++) {
for (int j = i + 1; j < digits.size(); j++) {
int x = digits.get(i);
int y = digits.get(j);
if (digits.get(i) > digits.get(j)) {
int temp = digits.get(i);
temp = x;
x = y;
y = temp;
}
}
}
int sorted_num = 0;
for (int i = 0; i <= digits.size() - 1; i++) {
sorted_num = 10*sorted_num+digits.get(i);
}
System.out.println(sorted_num);
// for (int i = 0; i <= digits.size() - 1; i++) {
// System.out.print(digits.get(i));
// }
}
}
Program to remove the duplicates
package com.java.programs;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Scanner;
public class RemoveDuplicates {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Enter the String:");
String str = in.nextLine();
LinkedHashSet<Character> set = new LinkedHashSet<Character>();
for(int i=0;i<=str.length()-1;i++)
{
set.add(str.charAt(i));
}
System.out.println(set);
String final_string = "";
// for(char ch:set)
// {
// final_string = final_string + ch;
// }
Iterator<Character> itr = set.iterator();
while(itr.hasNext())
{
final_string = final_string + itr.next();
}
System.out.println(final_string);
}
}
Program to sort the strings in alphabetical order
package selenium3;
import java.util.Scanner;
public class StrAlphabeticOrder {
public static void main(String[] args) throws Exception {
int n;
String temp;
Scanner in = new Scanner(System.in);
System.out.println("Enter number of strings");
n = in.nextInt();
String names[]=new String[n];
Scanner s1 = new Scanner(System.in);
try{
for(int i=0; i<n; i++)
{
names[i]=s1.nextLine();
}
for(int i=1;i<=n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(names[i].compareTo(names[j])>0)
{
temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
}
System.out.print("Names in sorted order:");
for(int i=0;i<n-1;i++)
{
System.out.print(names[i]+",");
}
System.out.print(names[n-1]);
}
catch(Exception e){
System.out.println(e);
}
finally
{
s1.close();
in.close();
}
}
}
Program to find common elements in arraylists
package com.java.programs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FindCommonElements {
public static void main(String[] args)
{
ArrayList<Integer> a1 = new ArrayList<Integer>
(Arrays.asList(1,2,4,5,10,20));
ArrayList<Integer> a2 = new ArrayList<Integer>
(List.of(1,3,5,6,10,30));
ArrayList<Integer> a3 = new ArrayList<Integer>
(List.of(1,2,10));
ArrayList<Integer> common = new ArrayList<Integer>();
for(int i:a1)
{
if(a2.contains(i) && a3.contains(i))
{
common.add(i);
}
}
System.out.println(common);
// a1.retainAll(a2);
// a1.retainAll(a3);
// System.out.println(a1);
}
}
Prime Number
package com.java.programs;
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
System.out.println("Enter the number:");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
boolean isPrime1 = true;
if (n <= 1) {
isPrime1 = false;
} else {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
isPrime1 = false;
break;
}
}
}
if (isPrime1) {
System.out.println("number is prime");
} else {
System.out.println("number is not prime");
}
System.out.println("Prime numbers between 1 to 100:");
for (int num = 2; num <= 100; num++) {
boolean isPrime2 = true;
for (int j = 2; j <= num / 2; j++) {
if (num % j == 0) {
isPrime2 = false;
break;
}
}
if (isPrime2) {
System.out.println(num);
}
}
}
}
Continue statement
package com.java.programs;
public class Continue {
public static void main(String[] args) {
System.out.println("Numbers from 1 to 10, skipping multiples of 3:");
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue; // skip multiples of 3
}
System.out.print(i + " ");
}
}
}
Switch - Case statements
package com.java.programs;
import java.util.Scanner;
public class Switch {
public static void main(String[] args) {
System.out.println("Enter two numbers:");
Scanner in = new Scanner(System.in);
int n1 = in.nextInt();
int n2 = in.nextInt();
System.out.println("Enter the operator:");
char op = in.next().charAt(0);
switch (op) {
case ('+'): {
System.out.println(n1 + n2);
break;
}
case ('-'): {
System.out.println(n1 - n2);
break;
}
case ('*'): {
System.out.println(n1 * n2);
break;
}
case ('/'): {
System.out.println(n1 / n2);
break;
}
}
}
}
Program to find the GCD
package com.java.programs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class GCD {
public static ArrayList<Integer> getFactors(int num) {
ArrayList<Integer> factors = new ArrayList<Integer>();
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
factors.add(i);
}
}
return factors;
}
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
int num3 = 30;
ArrayList<Integer> f1 = getFactors(num1);
ArrayList<Integer> f2 = getFactors(num2);
ArrayList<Integer> f3 = getFactors(num3);
ArrayList<Integer> common = new ArrayList<Integer>();
for(int i:f1)
{
if(f2.contains(i)&&f3.contains(i))
{
common.add(i);
}
}
int gcd = Collections.max(common);
System.out.println(gcd);
/*
for (int i = 0; i <count; i++)
{
System.out.println("Enter the number:");
int num = in.nextInt();
nums.add(num);
}
// GCD gcd = new GCD();
for (int i = 0; i < nums.size(); i++)
{
ArrayList<Integer> factors = getFactors(nums.get(i));
for(int k=0;k<factors.size();k++)
{
System.out.println(factors.get(k));
}
}
*/
}
}
Program to find the LCM of 3 numbers
package com.java.programs;
import java.util.Scanner;
public class LCM {
// Method to find GCD using Euclidean algorithm
public static int findGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
// Method to find LCM of two numbers
public static int findLCM(int a, int b) {
return (a * b) / findGCD(a, b);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read three numbers
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter third number: ");
int num3 = scanner.nextInt();
// Find LCM of three numbers
int lcm12 = findLCM(num1, num2);
int finalLCM = findLCM(lcm12, num3);
// Display result
System.out.println("LCM of " + num1 + ", "
+ num2 + ", and " + num3 + " is: " + finalLCM);
scanner.close();
}
}
GCD of three numbers
import java.util.Scanner; public class GCDofThreeNumbers { // Method to find GCD of two numbers public static int findGCD(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Read three numbers System.out.print("Enter first number: "); int num1 = scanner.nextInt(); System.out.print("Enter second number: "); int num2 = scanner.nextInt(); System.out.print("Enter third number: "); int num3 = scanner.nextInt(); // Step 1: Find GCD of first two numbers int gcd12 = findGCD(num1, num2); // Step 2: Find GCD of the result and the third number int finalGCD = findGCD(gcd12, num3); // Display result System.out.println("GCD of " + num1 + ", " + num2 + ", and "
+ num3 + " is: " + finalGCD); scanner.close(); } }
LCM and GCD using array list
package com.java.programs; import java.util.ArrayList; import java.util.Scanner; public class GCD_LCM_ArrayList{ public static int findGCD(int x, int y) { while(y!=0) { // int temp = x%y; 10 int temp = y; // y=x; 10 y = x%y; x = temp; //10 } return x; } public static void main(String[] args) { System.out.println("Enter the number of inputs:"); Scanner in = new Scanner(System.in); int count = in.nextInt(); ArrayList<Integer> nums = new ArrayList<Integer>(); for(int i=1;i<=count;i++){ System.out.println("enter the number:"); int num = in.nextInt(); nums.add(num); } int gcd = nums.get(0); int lcm = 1; for(int k=0;k<nums.size()-1;k++) { gcd = findGCD(gcd,nums.get(k)); lcm = (gcd*nums.get(k))/gcd; } System.out.println("GCD: " +gcd); System.out.println("LCM: " +lcm); } }
Program to reverse the words of a string separately
package selenium3;
import java.util.Scanner;
public class ReverseStringWords {
public static String reverseword(String str)
{
String words[]=str.split("\\s");
String revWord = " ";
for(String w:words)
{
StringBuilder sb = new StringBuilder(w);
sb.reverse();
revWord=revWord+sb.toString()+" ";
}
return revWord.trim();
}
public static void main(String[] args) throws Exception{
Scanner in = new Scanner(System.in);
try
{
System.out.println("Enter the string");
String st = in.nextLine();
String rev = reverseword(st);
System.out.println(rev);
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
in.close();
}
}
}
Program to count the occurrence of each character in a string
package selenium3;
import java.util.HashMap;
import java.util.Scanner;
public class CharCount {
public static void main(String[] args) throws Exception{
Scanner in = new Scanner(System.in);
try{
System.out.println("Enter the string");
String str = in.nextLine();
HashMap<Character,Integer> map = new HashMap<>();
for(char ch:str.toCharArray())
{
if(map.containsKey(ch))
{
int val=map.get(ch);
map.put(ch,val+1);
}
else
{
map.put(ch,1);
}
}
System.out.println(map);
}
catch(Exception e){
System.out.println(e);
}
finally
{
in.close();
}
}
}
Program to find the duplicate characters in a string using HashMap
package com.java.programs;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Scanner;
public class FindDuplicates {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter the String:");
Scanner in = new Scanner(System.in);
String str = in.nextLine();
char[] chars = str.toCharArray();
LinkedHashMap<Character,Integer> map = new LinkedHashMap();
for(char ch:chars)
{
if(map.containsKey(ch))
{
int val = map.get(ch);
map.put(ch, val+1);
}
else
{
map.put(ch, 1);
}
}
for(Entry<Character,Integer> entry:map.entrySet())
{
if(entry.getValue()>=2)
{
System.out.println(entry.getKey());
}
}
}
}
Program to find the duplicate characters in a string without using HashMap
package com.java.programs;
import java.util.HashSet;
import java.util.Scanner;
public class FindDuplicate_String {
public static void main(String[] args) {
System.out.println("Enter the string:");
Scanner in = new Scanner(System.in);
String str = in.nextLine();
HashSet<Character> set = new HashSet<Character>();
for (int i = 0; i < str.length() - 1; i++) {
for (int j = i + 1; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
// System.out.println(str.charAt(i));
set.add(str.charAt(i));
}
}
}
System.out.println(set);
}
}
Program to find the adjacent duplicate characters in a string
package com.java.programs; import java.util.HashSet; import java.util.Scanner; public class AdjacentDuplicates {
public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter the value:"); String input = in.nextLine(); adjacentDuplicates(input); } public static void adjacentDuplicates(String str) { HashSet<Character> charset = new HashSet<Character>(); for(int i=0;i<str.length()-1;i++) { if (str.charAt(i)==str.charAt(i+1)) { charset.add(str.charAt(i)); // System.out.println(str.charAt(i)); } } System.out.println(charset); } }
Program to read a text file and print in console
package selenium3;
import java.io.FileReader;
public class ReadFile
{
public static void main(String[] args)throws Exception
{
FileReader fr = new FileReader("C:/Users/Pc/Desktop/ust.txt");
int i;
while((i=fr.read())!=-1)
{
System.out.print((char)i);
}
}
}
Program to read and print the string from console
package selenium3;
import java.io.*;
public class ReadingString
{
public static void main(String[] args) {
//String newLine = System.getProperty("line.separator");
System.out.println("Reading Strings from console");
//You use System.in to get the Strings entered in console by user
try
{
//You need to create BufferedReader which has System.in to get user input
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String userInput;
System.out.println("Enter text...");
System.out.println("Press Enter to quit.");
do {
//reader .readLine() would wait for the user to enter strings
//keep and entering text and when you press enter, all those would be
displayed
//so it is keeping it in buffer untill the user types 'quit' and presses
enter
userInput = (String)br.readLine();
System.out.println("You entered : " + userInput);
}
while(!userInput.equals("quit"));
}
catch(Exception e)
{
}
}
}
Program to read the string character by character
package selenium3;
import java.io.*;
public class ReadingCharacter {
public static void main(String[] args
//String newLine = System.getProperty("line.separator");
System.out.println("Reading characters from console");
//You use System.in to get the characters entered in console by user
try
{
//You need to create BufferedReader which has System.in to get user input
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
char userInput;
System.out.println("Enter characters...");
System.out.println("Enter 'q' and Press 'Enter' to quit");
do {
//reader .read() would wait for the user to enter character.
//keep and entering characters and when you press enter, all those would be
displayed
//so it is keeping it in buffer until the user types 'q' and presses enter
userInput = (char)br.read();
System.out.println("You entered : " + userInput);
}
while(userInput!= 'q');
}
catch(Exception e)
{
}
}
}
There is integer array. Ex - 122344565888
Print the digit if the immediate digit is also same. o/p- 2 4 8
Class AdjacentDuplicates
{
public static vpod main(String
Scanner in = new Scanner(System.in);
Systemo.out.println("Enter the value");
String input = in.nextLine();
adjacentduplicates(x);
}
public void adjacentDuplicates(int n)
{
LinkedHashMap<character,Integer> map = new LinkedHashMap<character,Integer>();
char[] digits = n.toCharArray();
for(char ch:map){
if(map.containKey(ch)
{
int val=map.get(ch);
val=val+1;
map.put(ch,val);
}
else
{
map.put(ch,1);
}
}
for(Map.Entry entry:map.EntrySet()
{
System.out.println(map.getKey());
}
Write a program to reverse a string word by word.
Ex - String s = this is book
O/p - book is this
Class ReverseWordbyWord
{
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.println("Enter the value");
String input =in.nextLine()
reverse(input);
}
public void reverse(String s)
{
String[] words = s.split("\\s");
for(int i=words.length-1; i<=0; i--)
{
System.out.print(words[i]+" ");
}