0% found this document useful (0 votes)
23 views

JavaPrograms

Uploaded by

Arun kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

JavaPrograms

Uploaded by

Arun kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

1. Sorting program and second highest number.

Integer s[] = {7,12,34,66,3,88,77,676};

int temp;

int size = s.length;

for(int i=0;i<s.length;i++){

for(int j=0;j<s.length;j++){

if(s[i]<s[j]){

temp = s[i];

s[i] = s[j];

s[j] = temp;

}}}

System.out.println("Second largest number "+s[size-2]);

for(int i=0;i<s.length;i++){

System.out.println(s[i]);

Output:
Second largest number 88

12

34

66

77

88

676
2. Reverse word:

3. String text
4. = "i like this program very much";
5. String str[] = text.split(" ");
6. Collections.reverse(Arrays.asList(str));
7. System.out.println(String.join(" ", str));

String ar="arun kumar love";


String arr[] = ar.split(" ");

for(int i=arr.length-1;i>=0;i--){
System.out.println(arr[i]);
}

Output: much very program this like i

Missing numbers in array


Integer[] arr1 = {56,56, 10, 11, 11,23,24,30,34};

Set<Integer> arr2 = new HashSet<>();

Collections.addAll(arr2, arr1);

int n = arr2.size();

Integer arr[] = new Integer[n];

arr = arr2.toArray(arr);

// int arr[] = {56, 10, 11 , 23,24,30,56,34};

Arrays.sort(arr);

int N = arr.length;

// Function Call

// printMissingElements(arr, N);

int cnt = 0;

for (int i = arr[0]; i <= arr[N - 1]; i++)


{

// Check if number is equal to the first element in

// given array if array element match skip it increment for next element

if (arr[cnt] == i)

// Increment the count to check next element

cnt++;

else

// Print missing number

System.out.print(i + " ");

Ouput: 12 13 14 15 16 17 18 19 20 21 22 25 26 27 28 29 31 32 33 35 36 37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55

Find all Pairs of elements in an array whose


sum is equal to a specified number
int inputNumber = 15;

Integer inputArray[] ={2, 7, 4, -5, 11, 5, 20};

for (int i = 0; i < inputArray.length; i++) {

for (int j = i + 1; j < inputArray.length; j++) {

if (inputArray[i] + inputArray[j] == inputNumber) {

System.out.println(inputArray[i] + " + " + inputArray[j] + " = " + inputNumber);

Output:

4 + 11 = 15

-5 + 20 = 15
Comparator Sorting by salary using Array list object:

/******************************************************************************

Online Java Compiler.

Code, Compile, Run and Debug java program online.

Write your code in this editor and press "Run" button to execute it.

*******************************************************************************/

import java.util.*;

import java.util.ArrayList;

import java.util.Comparator;

import java.util.List;

import java.util.stream.Collectors;

public class Main

private String name;

private double salary;

public Main(String name, double salary) {

this.name = name;

this.salary = salary;

public String getName() {

return name;

public double getSalary() {


return salary;

@Override

public String toString() {

return "Employee{name='" + name + "', salary=" + salary + '}';

public static void main(String[] args) {

List<Main> employees = new ArrayList<>();

employees.add(new Main("John", 50000));

employees.add(new Main("Jane", 60000));

employees.add(new Main("Jack", 40000));

// Sort by salary in descending order

List<Main> sortedBySalaryDesc = employees.stream()

.sorted(Comparator.comparingDouble(Main::getSalary).reversed())

.collect(Collectors.toList());

System.out.println("Sorted by Salary (Descending):");

sortedBySalaryDesc.forEach(System.out::println);

// List<Main> sortedBySalaryAsc = employees.stream()

// .sorted(Comparator.comparingDouble(Main::getSalary))

// .collect(Collectors.toList());

// System.out.println("Sorted by Salary (Ascending):");

// sortedBySalaryAsc.forEach(System.out::println);

}
ODD or Even in each string word:

String s = "ar abc abcd abcde arunkk";

for (String word : s.split(" "))

// if length is even
if (word.length() % 2 == 0)

// Print the word


System.out.println(word);

Output: example:

ar ar - even
abcd abcd - even
arunkk

Array ODD Position String change lower to upper:

String str = "raja" ;


String s[] = str.split("");

for(int i=0;i<s.length;i=i+2) {

System.out.println(s[i].toUpperCase());
}

Output: RJ

Lower to Upper and Upper to Lower:

String str1="GreAt oWer";

StringBuffer newStr=new StringBuffer(str1);


for(int i = 0; i < str1.length(); i++) {

if(Character.isLowerCase(str1.charAt(i))) {

newStr.setCharAt(i, Character.toUpperCase(str1.charAt(i)));

else if(Character.isUpperCase(str1.charAt(i))) {

newStr.setCharAt(i, Character.toLowerCase(str1.charAt(i)));

System.out.println("String after case conversion : " + newStr);

output: String after case conversion : gREaT OwER

Print No of platform required based on the arrival and departure


time of train

int arr[] = { 400, 200, 800 };

int dep[] = { 500, 300, 900 };

int n = arr.length;
int plat_needed = 1, result = 1;

// run a nested loop to find overlap

for (int i = 0; i < n; i++) {

// minimum platform

for (int j = 0; j < n; j++) {

if (i != j)

// check for overlap

if (arr[i] >= arr[j]

&& dep[j] >= arr[i])

plat_needed++;

// update result

result = Math.max(result, plat_needed);

System.out.println(plat_needed);

Output: 1

Print word in which is upper case of starting letter :

String s ="I love India Arun kumar a B name te UB N ARUN ibm";

String s1[] = s.split(" ");

for(String s3:s1){

char c[] = s3.toCharArray();


if(Character.isUpperCase(c[0])){

System.out.println(s3);

Output:

India

Arun

UB

ARUN

Swap String and integer without using third variable;

int a = 10, b =20;


a = a + b;
b = a- b;
a = a - b;

System.out.println("a = " + a + " b = "+b);

//Swap String
String a1 = "arun", b1 = "kumar";
a1 = a1 + b1;
b1 = a1.substring(0,a1.length()-b1.length());
a1 = a1.substring(b1.length());

System.out.println("a1= "+a1+ " b1= "+b1);

Output:
a = 20 b = 10
a1= kumar b1= arun

Find repeated character present first in a


string
String str = "geeksforgeeks";

HashMap<Character, Integer> freq

= new HashMap<Character, Integer>();

for (int i = 0; i < str.length(); i++) {

char c = str.charAt(i);

freq.put(c, freq.getOrDefault(c, 0) + 1);

// Traverse the string

for (int i = 0; i < str.length(); i++) {

char c = str.charAt(i);

if (freq.get(c) > 1) {

System.out.println(c);

break;

Output: g
Integer Reverse:

int num=54321;

String str = Integer.toString(num);

String reverse = "";

for (int i = str.length() - 1; i >= 0; i--) {

reverse += str.charAt(i);

System.out.println(reverse);
First_And_last_char_remove

String str = "arun";


StringBuilder sb = new StringBuilder(str);

// Removing the last character


// of a string
sb.deleteCharAt(str.length() - 1);

// Removing the first character


// of a string
sb.deleteCharAt(0);

System.out.println(sb);

Output: 12345

HashMap_Iteration_comparing_getkey_and_value
Map<String,String> map = new HashMap<String,String>();
map.put("arun","sec1");
map.put("a","sec1");
map.put("b","sec2");

for(Map.Entry m :map.entrySet()) {

// System.out.println(m.getKey()+" "+m.getValue());

if(m.getValue()=="sec1") {

System.out.println(m.getKey()+" "+m.getValue());
}
Output:

a sec1
arun sec1

Pattern program:
int num = 5;
for (int i = 1; i < num; i++) {

for (int j = 1; j <= i; j++) {


System.out.print(j);

System.out.println();

System.out.println("###########################
#####");

int num1 = 5;
for (int i = 1; i <= num; i++) {

for (int j = i; j <= num; j++) {


System.out.print(j);

System.out.println();

Output:
12
123
1234
################################
12345
2345
345
45
5

String_Duplicate_Remove_Unique_Count:

Set<String> s1 = new HashSet<String>();


Set<String> s2 = new HashSet<String>();
String s3 ="arunkumar";
String s[] = s3.split("");
int wrt=1;
for(int i=0;i<s.length;i++) {
for(int j=i+1;j<s.length;j++) {
if(s[i].equals(s[j])) {

s1.add(s[i]);

// s[j]="0";
// wrt = wrt + 1;
}
else {
s2.add(s[i]);
}

// if(s[i]!="0")
// System.out.println(s[i]+" = "+wrt);
// wrt =1;
//
}
System.out.println("Duplicated character = "+s1);
System.out.println("Duplicated Removed = "+s2);
s2.removeAll(s1);
System.out.println("Unique Character = "+s2);
Output
Duplicated character = [a, r, u]
Duplicated Removed = [a, r, u, k, m, n]
Unique Character = [k, m, n]

String_Split_Char_Numeric_SpecialChar:

String s = "ar5un^&^!@5ku#%*)";
StringBuilder str1 = new StringBuilder(), str2 = new
StringBuilder(), str3 = new StringBuilder();
for (int i = 0; i < s.length(); i++) {

if (Character.isAlphabetic(s.charAt(i))) {

str1.append(s.charAt(i));

else if (Character.isDigit(s.charAt(i))) {
str2.append(s.charAt(i));

else {
str3.append(s.charAt(i));
}
}
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);

Output

arunku
55
^&^!@#%*)

Duplicate_Count_Consecutive

String str = "WWEAERRWE";


char[] ch = str.toCharArray();
for(int i =0;i<ch.length;i++){
int count = 1;
while(i+1<ch.length && ch[i] == ch[i+1]){
i++;
count++;
}
System.out.println(ch[i]+" : "+count);
}
Output:

W:2
E:1
A:1
E:1
R:2
W:1
E:1

Reverse_Each_Word_String_Not_Affect_the_Index
String s = "arun kumar";

String str[] = s.split(" ");


String revstring = "";
for (int i = 0; i < str.length; i++) {
String revword = "";
String word = str[i];

for (int j = word.length()-1; j >= 0; j--) {

revword = revword + word.charAt(j);


}
revstring = revstring + revword + " ";
}
System.out.println(revstring);
Output:

nura ramuk

Reverse_String_And_Integer_wihout_Inbuilt_Fun;

String s = "arun";
for (int i = s.length() - 1; i >= 0; i--) {
System.out.print(s.charAt(i));
}
System.out.println();

// Integer reverse
Integer s1[] = { 2, 3, 4, 4549 };

for (int i = s1.length - 1; i >= 0; i--) {


System.out.print(s1[i]);
}
System.out.println();

// Integer reverse using string


String s2 = "985029";

for (int i = s2.length() - 1; i >= 0; i--) {


System.out.print(s2.charAt(i));
}

System.out.println();

// Integer to string conversion


int num=54321;
String str = Integer.toString(num);

for (int i = str.length() - 1; i >= 0; i--) {


System.out.print(str.charAt(i));
}

Output:
nura
4549432
920589
12345

Missing char in String lower and upper:

String str = "AZab";


HashSet<Character> presentChars = new HashSet<>();
// add each character to the set
for(int i = 0; i < str.length(); i++){
char c = str.charAt(i);
if (c >= 'a' && c <= 'z'){
presentChars.add(c);
}
else if (c >= 'A' && c <= 'Z'){
presentChars.add(Character.toUpperCase(c));
}
}
// check which characters are missing
StringBuilder missingChars = new StringBuilder();
for(char c = 'a'; c <= 'z'; c++){
if(!presentChars.contains(c)){
missingChars.append(c);
}

for(char c = 'A'; c <= 'Z'; c++){


if(!presentChars.contains(c)){
missingChars.append(c);
}

}
// print the missing characters
if(missingChars.length() == 0){
System.out.println("The string is a pangram.");
}
else{
System.out.println(missingChars);
}
Output:
cdefghijklmnopqrstuvwxyzBCDEFGHIJKLMNOPQRSTUVWXY
Missing char in string upper and lower print separate:
String str = "AZab";
HashSet<Character> presentChars = new HashSet<>();
// add each character to the set
for(int i = 0; i < str.length(); i++){
char c = str.charAt(i);
if (c >= 'a' && c <= 'z'){
presentChars.add(c);
}
else if (c >= 'A' && c <= 'Z'){
presentChars.add(Character.toUpperCase(c));
}
}
// check which characters are missing
StringBuilder missingChars = new StringBuilder();
StringBuilder missingChars1 = new StringBuilder();
for(char c = 'a'; c <= 'z'; c++){
if(!presentChars.contains(c)){
missingChars.append(c);
}

for(char c = 'A'; c <= 'Z'; c++){


if(!presentChars.contains(c)){
// missingChars.append(c);
missingChars1.append(c);
}

}
// print the missing characters
if(missingChars.length() == 0){
System.out.println("The string is a pangram.");
}
else{
System.out.println(missingChars);
System.out.println(missingChars1);
}
Output: cdefghijklmnopqrstuvwxyz
BCDEFGHIJKLMNOPQRSTUVWXY

You might also like