113 QUES NEW (Core Java Assesment)
113 QUES NEW (Core Java Assesment)
Remove 10's
Write a program to read an integer array and remove all 10s from the array, shift the
other elements towards left and fill the trailing empty positions by 0 so that the
modified array is of the same length of the given array.
Include a class UserMainCode with a static method removeTens which accepts the
number of elements and an integer array. The return type (Integer array) should return
the final array.
Create a Class Main which would be used to read the number of elements and the
input array, and call the static method present in UserMainCode.
Sample Input :
5
1
10
20
10
2
Sample Output :
1
20
2
o
o
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int []sr=new int[n];
Integer []sr1=new Integer[n];
for(int i=0;i<n;i++)
{
sr[i]=sc.nextInt();
}
sr1=UserMainCode.remove(sr);
for(int i=0;i<n;i++){
System.out.println(sr1[i]);
}
}
import java.util.ArrayList;
import java.util.Iterator;
public class UserMainCode {
public static Integer[] remove(int s[]){
ArrayList<Integer> a=new ArrayList<Integer>();
ArrayList<Integer> b=new ArrayList<Integer>();
for(int i=0;i<s.length;i++)
{
a.add(s[i]);
}
Iterator <Integer> it=a.iterator();
while(it.hasNext())
{
int x=it.next();
if(x!=10)
{
b.add(x);
}
}
if(b.size()<s.length)
{
int len=s.length-b.size();
for(int i=0;i<len;i++)
{
b.add(0);
}
}
Write a Program that accepts three integer values (a,b,c) and returns their sum.
However, if one of the values is 13 then it does not count towards the sum and the
next number also does not count. So for example, if b is 13, then both b and c do not
count.
Create a Class Main which would be used to accept the input integers and call the
static method present in UserMainCode.
Sample Input 1:
1
2
3
Sample Output 1:
6
Sample Input 2:
1
2
13
Sample Output 2:
3
Sample Input 3:
13
3
8
Sample Output 3:
8
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int n1=sc.nextInt();
int n2=sc.nextInt();
int res=UserMainCode.sum(n,n1,n2);
System.out.println(res);
}
}
Write a program to read a string and return a modified string based on the following
rules.
Return the String without the first 2 chars except when
1. keep the first char if it is 'j'
2. keep the second char if it is 'b'.
Include a class UserMainCode with a static method getString which accepts a string.
The return type (string) should be the modified string based on the above rules.
Consider all letters in the input to be small case.
Create a Class Main which would be used to accept Input string and call the static
method present in UserMainCode.
Input and Output Format:
Input consists of a string with maximum size of 100 characters.
Output consists of a string.
Refer sample output for formatting specifications.
Sample Input 1:
hello
Sample Output 1:
llo
Sample Input 2:
java
Sample Output 2:
jva
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
String n=sc.next();
String res=UserMainCode.stringManipulation(n);
System.out.println(res);
}
}
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
String n=sc.next();
boolean s=UserMainCode.colorCode(n);
if(s==true){
System.out.println("valid");
}
else
System.out.println("invalid");
}
}
Write a program to read a non-negative integer n, compute the sum of its digits. If sum
is greater than 9 repeat the process and calculate the sum once again until the final
sum comes to single digit.Return the single digit.
Include a class UserMainCode with a static method getDigitSum which accepts the
integer value. The return type is integer.
Create a Class Main which would be used to accept the string and call the static
method present in UserMainCode.
Sample Input 1:
9999
Sample Output 1:
9
Sample Input 2:
698
Sample Output 2:
5
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
int rem,sum=0,dsum=0,rem1;
Scanner sc=new Scanner(System.in);
int digit=sc.nextInt();
while(digit!=0)
{
rem=digit%10;
sum=sum+rem;
digit/=10;
}
if(sum<9)
{
System.out.println(sum);
}
else
{
while(sum!=0)
{
rem1=sum%10;
dsum+=rem1;
sum/=10;
}
System.out.println(dsum);
}
}
}
Example:
Input Array = {10,15,20,25,30,100}
Number = 15
sum = 20 + 25 + 30 + 100 = 175
output = 571
Input and Output Format:
The first line of the input consists of an integer that corresponds to the number of
elements in the array.
The next n lines of the input consists of integers that correspond to the elements in the
array.
The last line of the input consists of an integer that corresponds to the number.
Output consists of a single integer.
Sample Input
6
10
15
20
25
30
100
15
Sample Output
571
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
int num=sc.nextInt();
int res=UserMainCode.digits(a,num);
System.out.println(res);
}
}
Write a program to read a two strings and one int value(N). check if Nth character of
first String from start and Nth character of second String from end are same or not. If
both are same return true else return false.
Check need not be Case sensitive
Include a class UserMainCode with a static method isEqual which accepts the two
strings and a integer n. The return type is the TRUE / FALSE.
Create a Class Main which would be used to read the strings and integer and call the
static method present in UserMainCode.
Sample Input 1:
AAAA
abab
2
Sample Output 1:
TRUE
Sample Input 2:
MNOP
QRST
3
Sample Output 2:
FALSE
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String s2=sc.next();
int n=sc.nextInt();
boolean s=UserMainCode.digits(s1,s2,n);
if(s==true){
System.out.println("TRUE");
}
else
System.out.println("FALSE");
}
}
Given two inputs year and month (Month is coded as: Jan=0, Feb=1 ,Mar=2 ...), write
a program to find out total number of days in the given month for the given year.
Include a class UserMainCode with a static method getNumberOfDays that
accepts 2 integers as arguments and returns an integer. The first argument corresponds
to the year and the second argument corresponds to the month code. The method
returns an integer corresponding to the number of days in the month.
Create a class Main which would get 2 integers as input and call the static
method getNumberOfDays present in the UserMainCode.
Sample Input:
2000
1
Sample Output:
29
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
int y=sc.nextInt();
int m=sc.nextInt();
int d=UserMainCode.month(y,m);
System.out.println(d);
}
}
import java.util.GregorianCalendar;
return f;
}
}
9. SumOdd
Write a program to read an integer and find the sum of all odd numbers from 1 to the
given number. [inclusive of the given number]
if N = 9 [ 1,3,5,7,9]. Sum = 25
Create a Class Main which would be used to accept the integer and call the static
method present in UserMainCode.
Sample Input 1:
6
Sample Output 1:
9
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int d=UserMainCode.sumOdd(n);
System.out.println(d);
}
}
public class UserMainCode {
public static int sumOdd(int s1){
int sum=0;
for(int i=0;i<=s1;i++)
{
if(i%2!=0)
{
sum=sum+i;
}
}
return sum;
}
}
Write a program to read a integer array, Remove the duplicate elements and display
sum of even numbers in the output. If input array contain only odd number then return
-1.
Include a class UserMainCode with a static method sumElements which accepts the
integer array. The return type is integer.
Create a Class Main which would be used to accept the integer array and call the static
method present in UserMainCode.
Sample Input 1:
7
2
3
54
1
6
7
7
Sample Output 1:
62
Sample Input 2:
6
3
7
9
13
17
21
Sample Output 2:
-1
import java.util.Scanner;
int n=sc.nextInt();
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
int d=UserMainCode.sumEven(a);
System.out.println(d);
}
import java.util.HashSet;
import java.util.Iterator;
int sum=0;
for(int i=0;i<=s1.length-1;i++)
hs.add(s1[i]);
Iterator<Integer>it=hs.iterator();
while(it.hasNext())
int x=(int)it.next();
if(x%2==0)
sum=sum+x;
}
if(sum==0)
return -1;
return sum;
Create a Class Main which would be used to read n strings and call the static method present
in UserMainCode.
Input consists of n+1 integers. The first integer denotes the size of the arraylist, the next n
strings are values to the arraylist.
Output consists of an arrayas per step 4.
Refer sample output for formatting specifications.
Sample Input 1:
4
a
d
c
b
Sample Output 1:
a
b
c
d
import java.util.ArrayList;
import java.util.Scanner;
ArrayList<String>al=new ArrayList<String>();
int n=sc.nextInt();
for(int i=0;i<n;i++)
al.add(sc.next());
String a[]=UserMainCode.listToArray(al);
for(int i=0;i<a.length;i++){
System.out.println(a[i]);}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
al.toArray(s);
return s;
}}
Write a program to read a string from the user and remove all the alphabets and
spaces from the String, andonly store special characters and digit in the output
String. Print the output string.
Create a Class Main which would be used to accept a string and call the static method
present in UserMainCode.
Sample Input :
cogniz$#45Ant
Sample Output :
$#45
import java.util.ArrayList;
import java.util.Scanner;
String s=sc.next();
String a=UserMainCode.flushChar(s);
System.out.println(a);
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
return s1;
}}
Write a Program that accepts four int inputs(x1,y1,x2,y2) as the coordinates of two
points. Calculate the distance between the two points using the below formula.
Formula : square root of((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
Then, Round the result to return an int
Include a class UserMainCode with a static method findDistance which accepts four
integers. The return type is integer representing the formula.
Create a Class Main which would be used to accept the input integers and call the
static method present in UserMainCode.
Sample Input 1:
3
4
5
2
Sample Output 1:
3
Sample Input 2:
3
1
5
2
Sample Output 2:
2
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
int n1=sc.nextInt();
int n2=sc.nextInt();
int n3=sc.nextInt();
int n4=sc.nextInt();
int a=UserMainCode.distance(n1,n2,n3,n4);
System.out.println(a);
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class UserMainCode {
public static int distance(int n1,int n2,int n3,int n4){
int dis=0;
int x=Math.abs(n1-n3);
int y=Math.abs(n2-n4);
dis=(int)Math.round(Math.sqrt((x*x)+(y*y)));
return dis;
}}
Given a method with two strings as input. Write code to count the common and unique
letters in the two strings.
Note:
The return type of the output is the count of all common and unique characters in the
two strings.
Create a class Main which would get the inputs and call the static
method commonChars present in the UserMainCode.
Output is an integer.
Sample Input 1:
a black cow
battle ship
Sample Output 1:
[Explanation : b, l and a are the common letters between the 2 input strings. But 'a'
appears more than once in the 1st string. So 'a' should not be considered while
computing the count value.]
Sample Input 2:
australia
sri lanka
Sample Output 2:
import java.util.ArrayList;
import java.util.Scanner;
String n2=sc.nextLine();
int a=UserMainCode.common(n1,n2);
System.out.println(a);
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
for(int i=0;i<sb1.length();i++){
int c=0;
for(int j=i+1;j<sb1.length();j++){
if(sb1.charAt(i)==sb1.charAt(j)){
sb1.deleteCharAt(j);
c++;
if(c>=1){
sb1.deleteCharAt(i);
System.out.println(sb1);
for(int i=0;i<sb2.length();i++){
int c=0;
for(int j=i+1;j<sb2.length();j++){
if(sb2.charAt(i)==sb2.charAt(j)){
sb2.deleteCharAt(j);
c++;
if(c>=1){
sb2.deleteCharAt(i);
System.out.println(sb2);
int count=0;
for(int i=0;i<sb1.length();i++){
for(int j=0;j<sb2.length();j++){
if(sb1.charAt(i)==sb2.charAt(j)){
count++;
return count;
Given an array of Strings, write a program to take the last character of each string and
make a new String by concatenating it.
Create a class Main which would get the String array as input and call the static
method concatCharacterpresent in the UserMainCode.
The first line of the input consists of an integer n that corresponds to the number of
strings in the input string array.
The next n lines of the input consist of the strings in the input string array.
ab
abcd
Sample Output:
bad
import java.util.ArrayList;
import java.util.Scanner;
int n=sc.nextInt();
for(int i=0;i<n;i++)
a[i]=sc.next();
String res=UserMainCode.common(a);
System.out.println(res);
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
String s ="";
for(int i=0;i<n1.length;i++)
int x=n1[i].length()-1;
s=s+n1[i].charAt(x);
return s;}}
Create a Class Main which would be used to read n strings and call the static method
present in UserMainCode.
Input consists of an integer (m) denoting the size of first arraylist. The next m
elements would be the values of the first arraylist. The next input would be n denoting
the size of the second arraylist. The next n elements would be the values of the second
arraylist.
Output consists of an array as per step 6. Refer sample output for formatting
specifications.
Sample Input 1:
3
Apple
Cherry
Grapes
4
Orange
Mango
Melon
Apple
Sample Output 1:
Cherry
Grapes
Orange
import java.util.ArrayList;
import java.util.Scanner;
int n=sc.nextInt();
ArrayList<String>al=new ArrayList<String>();
for(int i=0;i<n;i++)
al.add(sc.next());
int n1=sc.nextInt();
ArrayList<String>al1=new ArrayList<String>();
for(int i=0;i<n1;i++)
al1.add(sc.next());
String res[]=UserMainCode.common(al,al1);
for(int i=0;i<res.length;i++){
System.out.println(res[i]);}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
ArrayList<String>a=new ArrayList<String>();
ArrayList<String>b=new ArrayList<String>();
ArrayList<String>c=new ArrayList<String>();
Iterator <String>it=al.iterator();
while(it.hasNext())
String s=it.next();
int x=s.length()-1;
if(s.charAt(x)!='a'&&s.charAt(x)!='e')
a.add(s);
Iterator <String>itr=al1.iterator();
while(itr.hasNext())
String s=itr.next();
if(s.charAt(0)!='m'&&s.charAt(0)!='a')
b.add(s);
}
int len=a.size()+b.size();
for(int i=0;i<a.size();i++)
c.add(a.get(i));
for(int i=0;i<b.size();i++)
c.add(b.get(i));
c.toArray(arr);
return arr;}}
Create a Class Main which would be used to read the inputs and call the static method
present in UserMainCode.
Input consists of an integer (m) denoting the size of first arraylist. The next m
elements would be the values of the first arraylist. The next input would be n denoting
the size of the second arraylist. The next n elements would be the values of the second
arraylist.
Output consists of an array. The elements in the output array need to be printed in
sorted order.
Sample Input 1:
4
1
8
3
5
2
3
5
Sample Output 1:
1
8
Sample Input 2:
4
9
1
3
5
4
1
3
5
6
Sample Output 2:
6
9
import java.util.ArrayList;
import java.util.Scanner;
int n=sc.nextInt();
ArrayList<Integer>al=new ArrayList<Integer>();
for(int i=0;i<n;i++)
al.add(sc.nextInt());
int n1=sc.nextInt();
ArrayList<Integer>al1=new ArrayList<Integer>();
for(int i=0;i<n1;i++)
al1.add(sc.nextInt());
Integer res[]=UserMainCode.common(al,al1);
for(int i=0;i<res.length;i++){
System.out.println(res[i]);}
import java.util.ArrayList;
import java.util.Collections;
ArrayList<Integer>a=new ArrayList<Integer>();
a.addAll(al);
a.removeAll(al1);
al1.removeAll(al);
a.addAll(al1);
Collections.sort(a);
a.toArray(arr);
return arr;
Write code to get the sum of all the digits present in the given string.
Return the sum as output. If there is no digit in the given string return -1 as output.
Create a class Main which would get the input and call the static
method sumOfDigits present in the UserMainCode.
Sample Input 1:
good23bad4
Sample Output 1:
Sample Input 2:
good
Sample Output 2:
-1
import java.util.ArrayList;
import java.util.Scanner;
String n=sc.next();
int res=UserMainCode.common(n);
System.out.println(res);
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
char arr[]=s.toCharArray();
int sum=0;
for(int i=0;i<arr.length;i++)
if(Character.isDigit(arr[i]))
String str=String.valueOf(arr[i]);
int n=Integer.parseInt(str);
sum=sum+n;
if(s.replaceAll("[a-zA-Z]", "").isEmpty()){
sum=-1;}
return sum;
Given a string array (s) and non negative integer (n) and return the number of
elements in the array which have same number of characters as the givent int N.
Include a class UserMainCode with a static method countWord which accepts the
string array and integer. The return type is the string formed based on rules.
Create a Class Main which would be used to accept the string and integer and call the
static method present in UserMainCode.
Sample Input 1:
4
a
bb
b
ccc
1
Sample Output 1:
2
Sample Input 2:
5
dog
cat
monkey
bear
fox
3
Sample Output 2:
3
import java.util.ArrayList;
import java.util.Scanner;
int n=sc.nextInt();
for(int i=0;i<n;i++)
a[i]=sc.next();
int num=sc.nextInt();
int res=UserMainCode.common(a,num);
System.out.println(res);
20. IP Validator
Write a program to read a string and validate the IP address. Print Valid if the IP
address is valid, else print Invalid.
Create a Class Main which would be used to accept Input String and call the static
method present in UserMainCode.
Note: An IP address has the format a.b.c.d where a,b,c,d are numbers between 0-255.
Sample Input 1:
132.145.184.210
Sample Output 1:
Valid
Sample Input 2:
132.145.184.290
Sample Output 2:
Invalid
import java.util.ArrayList;
import java.util.Scanner;
String n=sc.next();
boolean s=UserMainCode.common(n);
if(s==true){
System.out.println("Valid");
}
else
System.out.println("Invalid");
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
boolean c=false;
int cnt=0;
while(st.hasMoreTokens())
String s1=st.nextToken();
int num=Integer.parseInt(s1);
if(num>=0&&num<=255)
cnt++;
}
if(cnt==4)
c=true;
else
c=false;
return c;
21. Anagram
Write a program to check whether the two given strings are anagrams.
Note: Rearranging the letters of a word or phrase to produce a new word or phrase,
using all the original letters exactly once is called Anagram."
Create a class Main which would get 2 Strings as input and call the static
method getAnagram present in the UserMainCode.
Input consists of 2 strings. Assume that all characters in the string are lower case
letters.
Sample Input 1:
Anagrams
Sample Input 2:
orchestra
carthorse
Sample Output 2:
Anagrams
Sample Input 3:
cognizant
technologies
Sample Output 3:
Not Anagrams
import java.util.ArrayList;
import java.util.Scanner;
String n=sc.nextLine();
String n1=sc.nextLine();
boolean s=UserMainCode.common(n,n1);
if(s==true){
System.out.println("Anagrams");
else
System.out.println("Not Anagrams");
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
boolean c=false;
try{
for(int i=0;i<s.length();i++)
char ch=s.charAt(i);
a.add(ch);
}
for(int i=0;i<s1.length();i++)
char ch=s.charAt(i);
b.add(ch);
Collections.sort(a);
Collections.sort(b);
if(a.containsAll(b)||b.containsAll(a))
c=true;
catch(Exception e){
c=false;
return c;
Obtain two strings S1,S2 from user as input. Your program should form a string of
long+short+long, with the shorter string inside of the longer String.
Include a class UserMainCode with a static method getCombo which accepts two
string variables. The return type is the string.
Create a Class Main which would be used to accept two Input strings and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of two strings with maximum size of 100 characters.
Output consists of an string.
Refer sample output for formatting specifications.
Sample Input 1:
Hello
Hi
Sample Output 1:
HelloHiHello
import java.util.ArrayList;
import java.util.Scanner;
String n=sc.nextLine();
String n1=sc.nextLine();
String res=UserMainCode.common(n,n1);
System.out.println(res);
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
public class UserMainCode {
int x=s.length();
String str="";
int y=s1.length();
if(x>y)
str=s+s1+s;
else
str=s1+s+s1;
return str;
}}
Write a program to input a String array. The input may contain digits and alphabets
(de5g4G7R). Extract odd digits from each string and find the sum and print the
output.
For example, if the string is "AKj375A" then take 3+7+5=15 and not as 375 as digit.
Create a Class Main which would be used to accept Input Strings and call the static
method present in UserMainCode.
Sample Input :
cog2nizant1
al33k
d2t4H3r5
Sample Output :
15
(1+3+3+3+5)
import java.util.ArrayList;
import java.util.Scanner;
int n=sc.nextInt();
for(int i=0;i<n;i++)
n1[i]=sc.next();
}
int res=UserMainCode.common(n1);
System.out.println(res); }
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
int sum=0;
for(int i=0;i<s.length;i++)
String str=s[i];
int len=str.length();
char a[]=str.toCharArray();
for(int j=0;j<len;j++)
if(Character.isDigit(a[j]))
{
String num=String.valueOf(a[j]);
int no=Integer.parseInt(num);
if(no%2!=0)
System.out.println(no);
sum=sum+no;
return sum;
Write a program to read a string and a positive integer n as input and construct a string
with first n and last n characters in the given string.
The return type of the output should be a string (value) of first n character and last n
character.
Create a class Main which would get the input as a string and integer n and call the
static methodformNewWord present in the UserMainCode.
Sample Input 1:
California
Sample Output 1:
Calnia
Sample Input2:
this
Sample Output 2:
Ts
import java.util.ArrayList;
import java.util.Scanner;
String n1=sc.next();
int n=sc.nextInt();
String res=UserMainCode.common(n1,n);
System.out.println(res);
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
String str=s.substring(0,n);
sb.reverse();
String st=sb.substring(0,n);
sb1.reverse();
str=str+sb1.toString();
return str;
Write a Program that accepts a decimal number n, and converts the number to binary.
Sample Input 1:
5
Sample Output 1:
101
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
long res=UserMainCode.common(n);
System.out.println(res);
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
public class UserMainCode {
public static long common(int n){
int rem=0,base=1,decimal_val=0;
while(n>0)
{
rem=n%2;
decimal_val=decimal_val+rem*base;
n=n/2;
base=base*10;
}
return decimal_val;
}
}
Write a program to check if a given string is palindrome and contains at least two
different vowels.
Create a Class Main which would be used to accept Input string and call the static
method present in UserMainCode.
Note Case Insensitive while considering vowel, i.e a & A are same vowel, But Case
sensitive while considering palindrome i.e abc CbA are not palindromes.
abceecba
Sample Output 1:
valid
Sample Input 2:
abcd
Sample Output 2:
Invalid
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
String n=sc.next();
boolean s=UserMainCode.common(n);
if(s==true){
System.out.println("Valid");
}
else
System.out.println("Invalid"); }}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
str=String.valueOf(ar[i]);
hs.add(str);
}
}
String st[]=new String[hs.size()];
hs.toArray(st);
if(st.length>=2)
{
fg1=1;}
if(fg==1&&fg1==1)
{
f=true;}
else
f=false;
return f;
}}
Or
import java.util.Scanner;
public class Main {
System.out.println(UserMainCode.empdis(n));
}
}
return rs;
}
}
Write a program that construts a hashmap with state as key and capital as its
value. If the next input is a state, then it should return capital$state in lowercase.
Create a Class Main which would be used to accept Input string and call the static
method present in UserMainCode.
Input consists of 2n+2 values. The first value corresponds to size of the hashmap. The
next n pair of numbers contains the state and capital. The last value consists of the
state input.
Sample Input 1:
3
Karnataka
Bangaluru
Punjab
Chandigarh
Gujarat
Gandhinagar
Punjab
Sample Output 1:
chandigarh$punjab
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
int n=sc.nextInt();
HashMap<String,String>hm=new HashMap<String,String>();
for(int i=0;i<n;i++)
hm.put(sc.next(),sc.next());
String st=sc.next();
String s=UserMainCode.common(hm,st);
System.out.println(s);
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
Iterator<String>it=hm.keySet().iterator();
String st="";
String s="";
String val="";
while(it.hasNext())
s=it.next();
if(s.equalsIgnoreCase(state))
{
val=hm.get(s);
st=val.toLowerCase()+"$"+s.toLowerCase();
return st;
Or
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
Write a program that construts a hashmap with state as key and capital as its value. If the
next input is a state, then it should return capital$state in lowercase.
Include a class UserMainCode with a static method getCapital which accepts a hashmap.
The return type is the string as given in the above statement
Create a Class Main which would be used to accept Input string and call the static method
present in UserMainCode.
Input consists of 2n+2 values. The first value corresponds to size of the hashmap. The next n
pair of numbers contains the state and capital. The last value consists of the state input.
Sample Input 1:
Karnataka
Bangaluru
Punjab
Chandigarh
Gujarat
Gandhinagar
Punjab
Sample Output 1:
chandigarh$punjab
Same asQue26.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
String s=sc.next();
System.out.println(UserMainCode.empdis(mp,s));
}
}
import java.util.Map;
import java.util.Set;
{ String rs="";
Set<String> k=mp.keySet();
for(String key:k)
{
if(key.equals(s))
{
rs=(mp.get(key)).toLowerCase()
+"$"+key.toLowerCase();
}
}
return rs;
}
}
Write a program to read a string containing date in DD/MM/YYYY format and check
if its a leap year. If so, return true else return false.
Include a class UserMainCode with a static method isLeapYear which accepts the
string. The return type is the boolean indicating TRUE / FALSE.
Create a Class Main which would be used to accept the string and call the static
method present in UserMainCode.
Sample Input 1:
23/02/2012
Sample Output 1:
TRUE
Sample Input 2:
12/12/2011
Sample Output 2:
FALSE
import java.text.ParseException;
import java.util.*;
public class Main {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
String s = sc.next();
boolean b = false;
StringTokenizer st = new StringTokenizer(s, "/");
while (st.hasMoreTokens()) {
int day = Integer.parseInt(st.nextToken());
int month = Integer.parseInt(st.nextToken());
int year = Integer.parseInt(st.nextToken());
GregorianCalendar gc = new GregorianCalendar();
b = gc.isLeapYear(year);
System.out.println(b);
}
}
}
Or
import java.text.ParseException;
import java.util.Scanner;
public class Main {
{
String r="";
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
Date d=sdf.parse(s);
GregorianCalendar gc=new GregorianCalendar();
gc.setTime(d);
if(gc.isLeapYear(gc.get(Calendar.YEAR)))
r="TRUE";
else
r="FALSE";
return r;
}
}
Write a program to read a String and check if that String contains all the vowels. Print
yes if the string contains all vowels else print no.
Create a Class Main which would be used to accept Input String and call the static
method present in UserMainCode.
Sample Input 1:
abceiduosp
Sample Output 1:
yes
Sample Input 2:
bceiduosp
Sample Output 2:
no
import java.text.ParseException;
import java.util.*;
public class Main {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
String s = sc.next();
String s2 = s.replaceAll("[^aeiouAEIOU]", "");
System.out.println(s2);
HashSet<Character> hs = new HashSet<Character>();
for (int i = 0; i < s2.length(); i++) {
hs.add(s2.charAt(i));
}
if (hs.size() == 5) {
System.out.println("yes");
} else {
System.out.println("No");
}
}
}
0r
import java.text.ParseException;
import java.util.Scanner;
Or
import java.util.Scanner;
public class Main {
System.out.println(s);
}
}
{
int r;
if(s.contains("a") || s.contains("A") && s.contains("e") ||
s.contains("E") && s.contains("i") || s.contains("I") && s.contains("o") ||
s.contains("O") && s.contains("u") || s.contains("U") )
r=1;
else
r=-1;
return r;
}
}
Or
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
boolean s=UserMainCode.common(st);
if(s==true){
System.out.println("yes");
}
else
System.out.println("no");
}
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
return f;
}
}
Given a method with string input. Write code to remove vowels from even position in
the string.
Create a Main class which gets string as an input and call the static
method removeEvenVowels present in the UserMainCode.
Input is a string .
Output is a string .
Sample Input 1:
commitment
Sample Output 1:
cmmitmnt
Sample Input 2:
capacity
Sample Output 2:
cpcty
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
String st=sc.next();
String s=UserMainCode.common(st);
System.out.println(s);
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
char arr[]=sd.toCharArray();
boolean f=false;
String st="";
for(int i=0;i<sd.length();i++){
if(arr[i]!='a'&&arr[i]!='e'&&arr[i]!='i'&&arr[i]!='o'&&arr[i]!='u')
{
String s=String.valueOf(arr[i]);
st=st+s;
return st;
or
import java.io.*;
import java.util.*;
{
String r="";
int l=s.length();
StringBuffer sb=new StringBuffer();
for(int i=0;i<l;i++)
{
if(i%2==0)
sb.append(s.charAt(i));
else if(i%2!=0)
{
r=sb.toString();
return r;
}
}
Write a program to read an int array of odd length, compare the first, middle and the
last elements in the array and return the largest. If there is only one element in the
array return the same element.
Create a Class Main which would be used to accept Input array and call the static
method present in UserMainCode.
Input consists of n+1 integers. The first integer corresponds to n, the number of
elements in the array. The next 'n' integers correspond to the elements in the array.
Sample Input 1:
4
5
Sample Output 1:
import java.io.*;
import java.util.*;
int s = sc.nextInt();
a[i] = sc.nextInt();
first = a[0];
System.out.println(first);
System.out.println(mid);
Or
import java.util.Scanner;
public class Main {
{
Arrays.sort(a);
return a[a.length-1];
}
}
A Company wants to give away bonus to its employees. You have been assigned as the
programmer to automate this process. You would like to showcase your skills by creating a
quick prototype. The prototype consists of the following steps:
1. Read Employee details from the User. The details would include id, DOB (date of
birth) and salary in the given order. The datatype for id is integer, DOB is string and
salary is integer.
2. You decide to build two hashmaps. The first hashmap contains employee id as
key and DOB as value, and the second hashmap contains same employee ids as key
and salary as value.
3. If the age of the employee in the range of 25 to 30 years (inclusive), the employee
should get bonus of 20% of his salary and in the range of 31 to 60 years (inclusive)
should get 30% of his salary. store the result in TreeMap in which Employee ID as
key and revised salary as value. Assume the age is caculated based on the date 01-09-
2014. (Typecast the bonus to integer).
4. Other Rules:
c. a takes more priority than b i.e both if a and b are true then store -100.
5. You decide to write a function calculateRevisedSalary which takes the above
hashmaps as input and returns the treemap as output. Include this function in class
UserMainCode.
Create a Class Main which would be used to read employee details in step 1 and build the
two hashmaps. Call the static method present in UserMainCode.
Input consists of employee details. The first number indicates the size of the employees. The
next three values indicate the employee id, employee DOB and employee salary. The
Employee DOB format is dd-mm-yyyy
Sample Input 1:
1010
20-12-1987
10000
2020
01-01-1985
14400
Sample Output 1:
1010
12000
2020
17280
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
int n=sc.nextInt();
String ss="01-09-2014";
int ds=0,ms=0,ys=0;
while(st.hasMoreTokens()){
ds=Integer.parseInt(st.nextToken());
ms=Integer.parseInt(st.nextToken());
ys=Integer.parseInt(st.nextToken());
for(int i=0;i<n;i++){
int id=sc.nextInt();
ids[i]=id;
s[i]=sc.next();
int sal=sc.nextInt();
h1.put(id,s[i]);
h2.put(id,sal);
int d=0,y=0,m=0,sals=0;
for(int i=0;i<s.length;i++){
while(st1.hasMoreTokens()){
d=Integer.parseInt(st1.nextToken());
m=Integer.parseInt(st1.nextToken());
y=Integer.parseInt(st1.nextToken());
int age=0;
else{
age=ys-y;
System.out.println(age);
sals=h2.get(ids[i]);
sals=sals+sals/5;
sals=h2.get(ids[i]);
sals=sals+((sals*3)/10);
t1.put(ids[i],sals);
for(Map.Entry<Integer,Integer> e:t1.entrySet()){
System.out.println(e.getKey()+"\n"+e.getValue());
}
33. Password
Validation Rule:
Atleast 8 characters
Atleast 1 number(1,2,3...)
Atleast 1 special character(@,#,%...)
Atleast 1 alphabet(a,B...)
Sample Input 1:
cts@1010
Sample Output 1:
Valid
Sample Input 2:
punitha3
Sample Output 2:
Invalid
or
import java.text.ParseException;
import java.util.*;
public class Main {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
String s = sc.next();
if (s.matches("((?=.*[0-9])(?=.*[a-zA-Z])(?=.*[@#$!]).{8,})")) {
System.out.println("valid");
} else {
System.out.println("Not Valid");
}
}
}
Write a program to read a string containing multiple words find the first and last
words, if they are same, return the length and if not return the sum of length of the two
words.
Include a class UserMainCode with a static method compareLastWords which
accepts the string. The return type is the length as per problem.
Create a Class Main which would be used to accept the string and call the static
method present in UserMainCode.
Sample Input 1:
This is Cognizant Academy
Sample Output 1:
11
Sample Input 2:
Hello World Hello
Sample Output 2:
5
import java.text.ParseException;
import java.util.*;
}
}
import java.util.StringTokenizer;
}
}
Write a program to accept an int array as input, and calculate the median of the same.
The total number count is even, Median will be the average of two middle numbers,
After calculating the average, round the number to nearest integer.
Create a Class Main which would be used to accept the integer array and call the static
method present in UserMainCode.
Input and Output Format:
Input consists of a an integer which denotes the size of the array followed by the array
of integers.
Output consists of a integer.
Refer sample output for formatting specifications.
Sample Input 1:
7
1
2
1
4
7
1
2
Sample Output 1:
2
Sample Input 2:
6
52
51
81
84
60
88
Sample Output 2:
71
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
int a[] = new int[s];
int mid;
for (int i = 0; i < s; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a);
if (s % 2 != 0) {
mid = a[(s - 1) / 2];
} else {
mid = Math.round((a[s / 2] + a[(s / 2) - 1]) / 2);
}
System.out.println(mid);
}
}
Or
import java.util.Scanner;
public class Main {
import java.util.Arrays;
{
int n,r,n1,l;
Arrays.sort(a);
if(a.length%2!=0)
{
r=a[a.length/2];
}
else
{
l=a.length;
n=a[l/2];
n1=a[(l/2)-1];
r=(int)Math.ceil(((n+n1)/2.00));
}
return r;
}
}
Write a program to read a string that contains a sentence and read a word. Check the
number of occurances of that word in the sentence.
Include a class UserMainCode with a static method countWords which accepts the
two strings. The return type is the integer giving the count.
Create a Class Main which would be used to accept the two strings and call the static
method present in UserMainCode.
Sample Input 1:
Hello world Java is best programming language in the world
world
Sample Output 1:
2
Sample Input 2:
hello world
World
Sample Output 2:
0
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s3 = sc.next();
int count = 0;
StringTokenizer st = new StringTokenizer(s1, " ");
while (st.hasMoreElements()) {
String s2 = st.nextToken();
if (s2.equals(s3)) {
count++;
}
}
System.out.println(count);
}
}
import java.util.Scanner;
System.out.println(UserMainCode.empdis(s,f));
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
{
ArrayList<String> r=new ArrayList<String>();
int n;
return n;
}
}
Given a string, startIndex and length, write a program to extract the substring from
right to left. Assume the last character has index 0.
Create a class Main which would get a String and 2 integers as input and call the
static method reverseSubstring present in the UserMainCode.
Sample Input:
rajasthan
2
3
Sample Output:
hts
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
String st=sc.next();
int n1=sc.nextInt();
int n2=sc.nextInt();
}
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
String st="";
String st1="";
StringBuffer sb=new StringBuffer(sd);
StringBuffer sb1=new StringBuffer();
sb.reverse();
System.out.println(sb);
sb1.append(sb.substring(n1,n1+n2));
return sb1.toString();
}
}
or
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
Given a date as a string input in the format dd-mm-yy, write a program to extract the
month and to print the month name in upper case.
Create a class Main which would get the String as input and call the static
method getMonthName present in the UserMainCode.
The month names are {JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER}
Sample Input:
01-06-82
Sample Output:
JUNE
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String arg[]) throws ParseException
{
Scanner sc=new Scanner(System.in);
String st=sc.next();
String s=UserMainCode.common(st);
System.out.println(s);
}
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
String st="";
SimpleDateFormat sf=new SimpleDateFormat("dd-MM-yy");
Date d=sf.parse(sd);
SimpleDateFormat sf1=new SimpleDateFormat("MMMM");
st=sf1.format(d);
return st.toUpperCase();
}
}
or
package gokul.javarevsi.dates;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
The return type is an ArrayList with elements from 2,6 and 8th index position .Array
index starts from position 0.
Create a Main class which gets two array list of size 5 as input and call the static
methodsortMergedArrayList present in the UserMainCode.
Sample Input 1:
3
1
17
11
19
5
2
7
6
20
Sample Output 1:
3
11
19
Sample Input 2:
1
2
3
4
5
6
7
8
9
10
Sample Output 2:
3
7
9
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
ArrayList<Integer> al1 = new ArrayList<Integer>();
ArrayList<Integer> al2 = new ArrayList<Integer>();
ArrayList<Integer> al3 = new ArrayList<Integer>();
for (int i = 0; i < a; i++) {
al1.add(sc.nextInt());
}
for (int i = 0; i < a; i++) {
al2.add(sc.nextInt());
}
al1.addAll(al2);
System.out.println(al1);
Collections.sort(al1);
System.out.println(al1);
for (int i = 0; i < al1.size(); i++) {
if (i == 2 || i == 6 || i == 8) {
al3.add(al1.get(i));
}
}
System.out.println(al3);
}
}
Or
import java.util.ArrayList;
import java.util.Scanner;
}
}
import java.util.ArrayList;
import java.util.Collections;
{
ArrayList<Integer> r=new ArrayList<Integer>();
ArrayList<Integer> res=new ArrayList<Integer>();
r.addAll(a);
r.addAll(b);
Collections.sort(r);
res.add(r.get(2));
res.add(r.get(6));
res.add(r.get(8));
return res;
}
}
Include a class UserMainCode with a static method fetchUserName which accepts the
string. The return type is the modified string.
Create a Class Main which would be used to accept the string and call the static
method present in UserMainCode.
Sample Input 1:
[email protected]
Sample Output 1:
admin
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
StringTokenizer st = new StringTokenizer(s1, "@");
String name = st.nextToken();
System.out.println(name);
}
}
41. ID Validation
Write a program to get two string inputs and validate the ID as per the specified
format.
Create a class Main which would get the input and call the static
method validateIDLocations present in the UserMainCode.
Sample Input 1:
CTS-hyd-1234
hyderabad
Sample Output 1:
Valid id
Sample Input 2:
CTS-hyd-123
hyderabad
Sample Output 2:
Invalid id
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sc.next();
StringTokenizer st = new StringTokenizer(s1, "-");
while (st.hasMoreElements()) {
String id = st.nextToken();
String loc = st.nextToken();
String xxx = st.nextToken();
if (loc.matches(s2.substring(0, 3)) && xxx.length() == 4) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
}
}
}
42. Mastering Hashmap
You have recently learnt about hashmaps and in order to master it, you try and use it
in all of your programs.
Your trainer / teacher has given you the following exercise:
1. Read 2n numbers as input where the first number represents a key and second one
as value. Both the numbers are of type integers.
2. Write a function getAverageOfOdd to find out average of all values whose keys
are represented by odd numbers. Assume the average is an int and never a decimal
number. Return the average as output. Include this function in class UserMainCode.
Create a Class Main which would be used to read 2n numbers and build the hashmap.
Call the static method present in UserMainCode.
Input and Output Format:
Input consists of a 2n+ 1 integers. The first integer specifies the value of n (essentially
the hashmap size). The next pair of n numbers denote the key and value.
Output consists of an integer representing the average.
Refer sample output for formatting specifications.
Sample Input 1:
4
2
34
1
4
5
12
4
22
Sample Output 1:
8
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
int sum = 0, avg = 0, count = 0, total;
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i = 0; i < s; i++) {
hm.put(sc.nextInt(), sc.nextInt());
}
System.out.println(hm);
Iterator<Integer> itr = hm.keySet().iterator();
{
while (itr.hasNext()) {
int j = itr.next();
if (j % 2 != 0) {
sum += hm.get(j);
count++;
}
}
total = sum / count;
System.out.println(total);
}
}
}
43. Test Vowels
Write a program to read a string and check if given string contains exactly five vowels
in any order. Print Yes if the condition satisfies, else print No.
Assume there is no repetition of any vowel in the given string and all characters are
lowercase.
Include a class UserMainCode with a static method testVowels which accepts a
string. The return type (Integer) should return 1 if all vowels are present, else return 2.
Create a Class Main which would be used to accept a string and call the static method
present in UserMainCode.
Sample Input 2:
cbisouzze
Sample Output 2:
No
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String s2 = s.replaceAll("[^aeiouAEIOU]", "");
System.out.println(s2);
HashSet<Character> hs = new HashSet<Character>();
for (int i = 0; i < s2.length(); i++) {
hs.add(s2.charAt(i));
}
System.out.println(hs);
if (hs.size() == 5) {
System.out.println("yes");
} else {
System.out.println("No");
}
}
}
44. Regular Expression - III
Sample Input 1:
Technology$1213
Sample Output 1:
valid
import java.util.Iterator;
import java.util.Scanner;
import java.util.StringTokenizer;
{
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
}
}
45. Average of Prime Locations
Write a program to read an integer array and find the average of the numbers located
on the Prime location(indexes).
Round the avarage to two decimal places.
Assume that the array starts with index 0.
Include a class UserMainCode with a static method averageElements which accepts a
single integer array. The return type (double) should be the average.
Create a Class Main which would be used to accept Input array and call the static
method present in UserMainCode.
Input and Output Format:
Input consists of n+1 integers. The first integer corresponds to n, the number of
elements in the array. The next 'n' integers correspond to the elements in the array.
Output consists of a single Double value.
Refer sample output for formatting specifications.
Sample Input 1:
8
4
1
7
6
5
8
6
9
Sample Output 1:
7.5
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int flag = 0, sum = 0;
double tot = 0, count = 0.0;
int a[] = new int[8];
for (int i = 0; i < 8; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < 8; i++) {
flag = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) {
flag++;
}
}
if (flag == 2) {
sum = sum + a[i];
count++;
}
}
tot = (double) (sum / count);
System.out.println(tot);
}
}
Write a program to read an integer array and return the middle element in the array. The size
of the array would always be odd.
Create a Class Main which would be used to accept Input array and call the static method
present in UserMainCode.
Input consists of n+1 integers. The first integer corresponds to n, the number of elements in
the array. The next 'n' integers correspond to the elements in the array.
Output consists of a single Integer value.
Sample Input 1:
23
64
Sample Output 1:
23
import java.util.Scanner;
}
}
public class UserMainCode {
Given a string input, write a program to replace every appearance of the word "is" by
"is not".
If the word "is" is immediately preceeded or followed by a letter no change should be
made to the string .
Create a class Main which would get a String as input and call the static
method negativeString present in the UserMainCode.
Sample Input 1:
This is just a misconception
Sample Output 1:
This is not just a misconception
Sample Input 2:
Today is misty
Sample Output 2:
Today is not misty
Write a program to find out sum of common elements in given two arrays. If no common
elements are found print - No common elements.
Create a Class Main which would be used to accept 2 Input arrays and call the static method
present in UserMainCode.
Input consists of 2+m+n integers. The first integer corresponds to m (Size of the 1st array),
the second integer corresponds to n (Size of the 2nd array), followed by m+n integers
corresponding to the array elements.
Output consists of a single Integer corresponds to the sum of common elements or a string
No common elements.
Sample Input 1:
Sample Output 1:
4
Sample Input 2:
12
31
Sample Output 2:
No common elements
import java.util.Scanner;
int n=sc.nextInt();
int m=sc.nextInt();
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
for(int i=0;i<m;i++){
b[i]=sc.nextInt();
}
if(sum==0){
else{
System.out.println(sum);
int sum=0;
for(int i=0;i<a.length;i++){
for(int j=0;j<b.length;j++){
if(a[i]==b[j]){
sum=sum+b[j];
return sum;
Sample Input 1:
ab2
Sample Output 1:
TRUE
Sample Input 2:
72CAB
Sample Output 2:
FALSE
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
StringBuffer sb = new StringBuffer();
String s2 = sb.append(s1.substring(0, 1)).toString();
System.out.println(s2);
if (s2.matches("[a-z]{1}")) {
System.out.println("true");
} else {
System.out.println("False");
}
}
}
Write a program to read a string and return the length of the largest "chunk" in the string.
A chunk is a repetition of same character 2 or more number of times. If the given string doest
not contain any repeated chunk of characters return -1.
Include a class UserMainCode with a static method getLargestSpan which accepts the
string. The return type is the integer.
Create a Class Main which would be used to accept the string and call the static method
present in UserMainCode.
Sample Input 1:
This place is soooo good
Sample Output 1:
4
import java.util.Scanner;
String s=sc.nextLine();
if(UserMainCode.getLargestSpan(s)== -1)
System.out.println("No Chunks");
else{
System.out.println(UserMainCode.getLargestSpan(s));
import java.util.StringTokenizer;
int max=0;
while(st.hasMoreTokens()){
String s=st.nextToken();
for(int i=0;i<sb.length();i++){
int count=0;
for(int j=i+1;j<sb.length();j++){
if(sb.charAt(i)==sb.charAt(j)){
count++;
if(count>max){
max=count+1;
if(max==0){
return -1;
else{
return max;
}
}
Or
int r=UserMainCode.getstring(s);
System.out.println(r);
import java.util.StringTokenizer;
int c=0,max=0,lar=0;
if(c>max)
{
max=c+1;
lar=v.length();
}
}}
if(max>2)
return max;
else
return -1;
For a given double number with atleast one decimal value, Write a program to compute the
number of digits before and after the decimal point in the following format
noOfDigitsBeforeDecimal:noOfDigitsAfterDecimal.
Note: Ignore zeroes at the end of the decimal (Except if zero is the only digit after decimal.
Refer Example 2 and 3)
Include a class UserMainCode with a static method findNoDigits which accepts the decimal
value. The return type is string.
Create a Class Main which would be used to accept the string and call the static method
present in UserMainCode.
Sample Input 1:
843.21
Sample Output 1:
3:2
Sample Input 2:
20.130
Sample Output 2:
2:2
Sample Input 3:
20.130
Sample Output 3:
2:2
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
String b = String.valueOf(a);
StringBuffer sb = new StringBuffer();
StringTokenizer st = new StringTokenizer(b, ".");
String c = st.nextToken();
String d = st.nextToken();
System.out.println(c);
System.out.println(d);
int x = c.length();
int y = d.length();
sb.append(x).append(':').append(y);
System.out.println(sb);
}
}
Or
public class Main {
String r=UserMainCode.getstring(s);
System.out.println(r);
String s1,s2;
}
}
Write a program to read a string and an integer and return a string based on the below rules.
If input2 is equal or greater than 3 then repeat the first three character of the String by given
input2 times, separated by a space.
If input2 is 2 then repeat the first two character of String two times separated by a space,
Include a class UserMainCode with a static method repeatString which takes a string &
integer and returns a string based on the above rules.
Create a Class Main which would be used to accept Input string and call the static method
present in UserMainCode.
Sample Input 1:
COGNIZANT
Sample Output 1:
COGNIZANT
Sample Output 2:
CO CO
package Arrayy;
import java.util.Scanner;
Write a program to check whether the given input number is a Kaprekar number or not.
Note : A positive whole number n that has d number of digits is squared and split into two
pieces, a right-hand piece that has d digits and a left-hand piece that has remaining d or d-
1 digits. If the sum of the two pieces is equal to the number, then n is a Kaprekar number.
If its Kaprekar number assign to output variable 1 else -1.
Example 1:
Input1:9
Example 2:
Input1:45
Hint:
45^2 = 2025, right-hand piece of 2025 = 25 and left hand piece of 2025 = 20
Create a class Main which would get the an Integer as input and call the static
method getKaprekarNumber present in the UserMainCode.
Output consists of a single string that is either Kaprekar Number or Not A Kaprekar
Number
Sample Input 1:
Sample Output 1:
Kaprekar Number
Sample Input 2:
45
Sample Output 2:
Kaprekar Number
Sample Input 3:
Sample Output 3:
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int x = 0, y = 0, z = 0;
int b = a * a;
String c = String.valueOf(b);
int d = c.length();
if (d == 2) {
x = b % 10;
y = b / 10;
z = x + y;
}
else if (d == 4) {
x = b % 100;
y = b / 100;
z = x + y;
}
System.out.println(z);
if (z == a) {
System.out.println("Kaperakar number");
} else {
System.out.println("Not a Kaperakar Number");
}
}
}
54. Start Case
Write a program to read a sentence in string variable and convert the first letter of each word
to capital case. Print the final string.
Note: - Only the first letter in each word should be in capital case in final string.
Create a Class Main which would be used to accept a string and call the static method present
in UserMainCode.
Sample Input:
Sample Output:
import java.util.Scanner;
import java.util.StringTokenizer;
Write code to get two strings as input and If strings are of same length simply append them
together and return the final string. If given strings are of different length, remove starting
characters from the longer string so that both strings are of same length then append them
together and return the final string.
Include a class UserMainCode with a static method concatstring which accepts two string
input.
The return type of the output is a string which is the concatenated string.
Create a class Main which would get the input and call the static
method concatstring present in the UserMainCode.
Output is a string.
Sample Input 1:
Hello
hi
Sample Output 1:
lohi
Sample Input 2:
Hello
Delhi
Sample Output 2:
HelloDelhi
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sc.nextLine();
int a1 = s1.length();
int a2 = s2.length();
StringBuffer sb = new StringBuffer(s1);
if (a1 == a2) {
System.out.println(s1.concat(s2));
}
else if(a2<a1)
{
sb.reverse();
String s3 = sb.substring(0, a2);
StringBuffer sb1 = new StringBuffer(s3);
sb1.reverse().append(s2);
System.out.println(sb1.toString());
}
else
{
sb.reverse();
String s3 = sb.substring(0, a1);
StringBuffer sb1 = new StringBuffer(s3);
sb1.reverse().append(s2);
System.out.println(sb1.toString());
}
}
Write a program to read a string and count the number of words present in it.
Include a class UserMainCode with a static method countWord which accepts the string. The
return type is the integer giving out the count of words.
Create a Class Main which would be used to accept the string and call the static method
present in UserMainCode.
Sample Input 1:
Today is Sunday
Sample Output 1:
3
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
int count = 0;
StringTokenizer st = new StringTokenizer(s1, " ");
while (st.hasMoreElements()) {
String s2 = st.nextToken();
count++;
}
System.out.println(count);
}
}
Write a program to read a integer array, find the largest difference between adjacent elements
and display the index of largest difference.
EXAMPLE:
input1: {2,4,5,1,9,3,8}
output1: 4 (here largest difference 9-1=8 then return index of 9 ie,4)
Include a class UserMainCode with a static method checkDifference which accepts the
integer array. The return type is integer.
Create a Class Main which would be used to accept the integer array and call the static
method present in UserMainCode.
Sample Input 1:
7
2
4
5
1
9
3
8
Sample Output 1:
4
import java.util.Scanner;
int n=sc.nextInt();
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
System.out.println(UserMainCode.checkDifference(a));
}
import java.util.StringTokenizer;
public class UserMainCode {
public static int checkDifference(int[] a){
int max=0,p=0;
for(int i=0;i<a.length-1;i++){
int j=i+1;
int t=Math.abs(a[i]-a[j]);
if(t>max)
{
max=t;
p=j;
}
}
return p;
Write a program to validate the Date of Birth given as input in String format (MM/dd/yyyy)
as per the validation rules given below. Return true for valid dates else return false.
1. Value should not be null
2. month should be between 1-12, date should be between 1-31 and year should be a four
digit number.
Include a class UserMainCode with a static method ValidateDOB which accepts the string.
The return type is TRUE / FALSE.
Create a Class Main which would be used to accept the string and call the static method
present in UserMainCode.
Sample Input 1:
12/23/1985
Sample Output 1:
TRUE
Sample Input 2:
31/12/1985
Sample Output 2:
FALSE
import java.io.*;
import java.util.*;
59. Duplicates
GIven three integers (a,b,c) find the sum. However, if one of the values is the same as
another, both the numbers do not count towards the sum and the third number is returned as
the sum.
Include a class UserMainCode with a static method getDistinctSum which accepts three
integers and returns integer.
Create a Class Main which would be used to accept three integers and call the static method
present in UserMainCode.
Sample Input 1:
1
2
1
Sample Output 1:
2
Sample Input 2:
1
2
3
Sample Output 2:
6
import java.io.*;
import java.util.*;
Write a program to input a person's name in the format "FirstName LastName" and return the
person name in the following format - "LastName, InitialOfFirstName".
Include a class UserMainCode with a static method nameFormatter which accepts a string.
The return type (string) should return the expected format.
Create a Class Main which would be used to accept Input String and call the static method
present in UserMainCode.
Sample Input :
Jessica Miller
Sample Output:
Miller, J
import java.io.*;
import java.util.*;
Or
public class Main {
String r=UserMainCode.getstring(s);
System.out.println(r);
}}
String s1,s2;
StringTokenizer st=new StringTokenizer(s," ");
s1=st.nextToken();
s2=st.nextToken();
StringBuffer sb=new StringBuffer(s2);
String r=sb.append(",").append(s1.substring(0,1)).toString();
return r;
}
}
Write a program to remove all the elements of the given length and return the size of the final
array as output. If there is no element of the given length, return the size of the same array as
output.
Include a class UserMainCode with a static method removeElements which accepts a string
array, the number of elements in the array and an integer. The return type (integer) should
return the size of the final array as output.
Create a Class Main which would be used to accept Input String array and a number and call
the static method present in UserMainCode.
Input consists of a integers that corresponds to n, followed by n strings and finally m which
corresponds to the length value.
Sample Input 1:
bb
ccc
ddd
Sample Output 1:
4
import java.util.*;
public class ClassSet28 {
public static int StringsNotOfGivenLength(List<String> l1,String s1){
int n1=s1.length();
int c=0;
for(int i=0;i<l1.size();i++)
{
int n2=l1.get(i).length();
if(n1!=n2)
c++;
}
return c;
}
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter the no.of elements:");
int n=s.nextInt();
List<String> l1=new ArrayList<String>();
for(int i=0;i<n;i++)
l1.add(s.next());
System.out.println("enter the input string:");
String s1=s.next();
System.out.println(StringsNotOfGivenLength(l1,s1));
}
}
Or
public class Main {
int nt=sc.nextInt();
int r=UserMainCode.getstring(s,nt);
System.out.println(r);
}}
int r=0;
for(int i=0;i<s.length;i++)
{
if(s[i].length()!=nt)
r++;
}
return r;
}
}
Write a program to read a string and a character, and reverse the string and convert it in a
format such that each character is separated by the given character. Print the final string.
Include a class UserMainCode with a static method reshape which accepts a string and a
character. The return type (String) should return the final string.
Create a Class Main which would be used to accept a string and a character, and call the static
method present in UserMainCode.
Sample Input:
Rabbit
Sample Output:
t-i-b-b-a-R
public class Main {
Or
import java.util.Scanner;
String r=UserMainCode.getstring(s,sym);
System.out.println(r);
}}
import java.util.StringTokenizer;
public class UserMainCode {
public static String getstring(String s,String sym)
{
}
String r;
sb.reverse();
r=sb.substring(1,sb.length());
return r;
}
}
64. Largest Key in HashMap
Write a program that construts a hashmap and returns the value corresponding to the largest
key.
Include a class UserMainCode with a static method getMaxKeyValue which accepts a string.
The return type (String) should be the value corresponding to the largest key.
Create a Class Main which would be used to accept Input string and call the static method
present in UserMainCode.
Input consists of 2n+1 values. The first value corresponds to size of the hashmap. The next n
pair of numbers equals the integer key and value as string.
Sample Input 1:
12
amron
Exide
SF
Sample Output 1:
Amron
import java.util.HashMap;
import java.util.Iterator;
import java.util.*;
import java.lang.*;
System.out.println(getvalues(hm));
}
public static String getvalues(HashMap<Integer, String> hm) {
int b=0,max=0;
String s1=new String();
Iterator<Integer> i= hm.keySet().iterator();
while(i.hasNext())
{
b=i.next();
if(b>max)
{
max=b;
s1=hm.get(b);
}
}
return s1;
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
for(int i=0;i<n;i++)
re.put(sc.nextInt(), sc.next());
String r=UserMainCode.getstring(re);
System.out.println(r);
}}
import java.util.Map;
import java.util.Set;
int m=0;
String r="";
Set<Integer> key=re.keySet();
for(Integer l:key)
{
if(l>m)
{
m=l;
r=re.get(l);
}
}
return r;
}
65. Scores
Write a program to read a integer array of scores, if 100 appears at two consecutive locations
return true else return false.
Include a class UserMainCode with a static method checkScores which accepts the integer
array. The return type is boolean.
Create a Class Main which would be used to accept the integer array and call the static
method present in UserMainCode.
Sample Input 1:
3
1
100
100
Sample Output 1:
TRUE
Sample Input 2:
3
100
1
100
Sample Output 2:
FALSE
import java.io.*;
import java.util.*;
int s = sc.nextInt();
a[i] = sc.nextInt();
System.out.println("true");
return;
System.out.println("True");
return;
else {
System.out.println("False");
return;
}
}
Or
import java.util.Scanner;
}}
String r;
int c=0;
for(int i=0;i<a.length-1;i++)
{
if(a[i]==100 && a[i+1]==100)
c++;
}
if(c==1)
r="TRUE";
else
r="FALSE";
return r;
}
}
Write a program to read a string of even length and to fetch two middle most characters from
the input string and return it as string output.
Include a class UserMainCode with a static method getMiddleChars which accepts a string
of even length as input . The return type is a string which should be the middle characters of
the string.
Create a class Main which would get the input as a string and call the static
method getMiddleChars present in the UserMainCode.
Output is a string .
Sample Input 1:
this
Sample Output 1:
hi
Sample Input 1:
Hell
Sample Output 1:
el
import java.io.*;
import java.util.*;
String s1 = sc.next();
if (s1.length() % 2 == 0) {
if (s1.length() > 2) {
System.out.println(s1.substring(s1.length() / 2 - 1,
s1.length() / 2 + 1));
Or
import java.util.Scanner;
String r=UserMainCode.getstring(n);
System.out.println(r);
}}
String r;
if(s.length()%2==0)
r=s.substring((s.length()/2)-1,(s.length()/2)+1);
else
r="Please enter even no. of. characters";
return r;
}
}
Given a method with a password in string format as input. Write code to validate the
password using following rules:
If the password is as per the given rules return 1 else return -1.If the return value is 1 then
print valid password else print as invalid password.
Create a Main class which gets string as an input and call the static
method validatePassword present in theUserMainCode.
Input is a string .
Output is a string .
Sample Input 1:
%Dhoom%
Sample Output 1:
Invalid password
Sample Input 2:
#@6Don
Sample Output 2:
Valid password
import java.io.*;
import java.util.*;
String s1 = sc.next();
if (s1.matches("((?=.*[0-9])(?=.*[#@$])(?=.*[a-z]).{6,20})")) {
System.out.println("Valid Password");
} else {
Or
public class Main {
Integer r=UserMainCode.getstring(n);
if(r==1)
System.out.println("Valid");
else
System.out.println("Not Valid");
}}
return -1;
}
}
68. Anagrams
Write a program to read two strings and checks if one is an anagram of the other.
An anagram is a word or a phrase that can be created by rearranging the letters of another
given word or phrase. We ignore white spaces and letter case. All letters of 'Desperation' can
be rearranged to the phrase 'A Rope Ends It'.
Include a class UserMainCode with a static method checkAnagram which accepts the two
strings. The return type is boolean which is TRUE / FALSE.
Create a Class Main which would be used to accept the two strings and call the static method
present in UserMainCode.
Sample Input 2:
Desperation
A Rope Ends It
Sample Output 2:
TRUE
import java.util.Scanner;
public class Main {
}}
import java.util.Set;
import java.util.TreeSet;
public class UserMainCode {
public static Boolean getstring(String s1,String s2)
{
s1=s1.replace(" ", "");
s2=s2.replace(" ", "");
for(int i=0;i<s1.length();i++)
al.add(String.valueOf(s1.charAt(i)));
for(int i=0;i<s2.length();i++)
al1.add(String.valueOf(s2.charAt(i)));
if(al.equals(al1))
return true;
else
return false;
}
}
Write a program to read a string and check if it complies to the pattern 'CPT-XXXXXX'
where XXXXXX is a 6 digit number. If the pattern is followed, then print TRUE else print
FALSE.
Include a class UserMainCode with a static method CheckID which accepts the string. The
return type is a boolean value.
Create a Class Main which would be used to accept the string and call the static method
present in UserMainCode.
Sample Input 1:
CPT-302020
Sample Output 1:
TRUE
Sample Input 2:
CPT123412
Sample Output 2:
FALSE
import java.io.*;
import java.util.*;
String s1 = sc.next();
if (s1.matches("[CPT-]{4}[0-9]{6}"))
System.out.println("True");
else
System.out.println("False");
Or
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println(UserMainCode.getstring(s1));
}}
Write a program that reads details about number of admissions per year of a particular
college, return the year which had maximum admissions. The details are stored in an arraylist
with the first index being year and next being admissions count.
Include a class UserMainCode with a static method getYear which accepts a arraylist. The
return type is an integer indicating the year of max admissions.
Create a Class Main which would be used to accept Input string and call the static method
present in UserMainCode.
Input consists of 2n+1 values. The first value corresponds to size of the data (year &
admissions). The next n pair of numbers contains the year and admissions count.
Sample Input 1:
2010
200000
2011
300000
2012
45000
2013
25000
Sample Output 1:
2011
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
System.out.println(getvalues(hm));
}
public static int getvalues(HashMap<Integer,Integer> hm) {
int b=0,max=0,c=0,d=0;
Iterator<Integer> i=hm.keySet().iterator();
while(i.hasNext())
{
b=i.next();
c=hm.get(b);
if(c>max)
{
max=c;
d=b;
}
}
return d;
}
}
Or
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
System.out.println(UserMainCode.getstring(stud));
}}
import java.util.Map;
import java.util.Set;
public class UserMainCode {
public static String getstring(Map<String, Integer> stud)
{ int m=0;
String s="";
Set<String> key=stud.keySet();
for(String l:key)
{
if(stud.get(l)>m)
{
m=stud.get(l);
s=l;
}
}
return s;
}
A School wants to give assign grades to its students based on their marks. You have been
assigned as the programmer to automate this process. You would like to showcase your skills
by creating a quick prototype. The prototype consists of the following steps:
Read student details from the User. The details would include name, mark in the given order.
The datatype for name is string, mark is float.
You decide to build a hashmap. The hashmap contains name as key and mark as value.
BUSINESS RULE:
1. If Mark is less than 60, then grade is FAIL.
2. If Mark is greater than or equal to 60, then grade is PASS.
Note: FAIL/PASS should be in uppercase.
Store the result in a new Hashmap with name as Key and grade as value.
4. You decide to write a function calculateGrade which takes the above hashmap as input
and returns the hashmap as output. Include this function in class UserMainCode.
Create a Class Main which would be used to read student details in step 1 and build the
hashmap. Call the static method present in UserMainCode.
Input consists of student details. The first number indicates the size of the students. The next
two values indicate the name, mark.
Sample Input 1:
3
Avi
76.36
Sunil
68.42
Raja
36.25
Sample Output 1:
Avi
PASS
Sunil
PASS
Raja
FAIL
import java.util.*;
public class ClassSeT23 {
public static void main(String[] args) {
Map<String, Integer> m1=new HashMap<String, Integer>();
m1.put("abc", 90);
m1.put("efg", 50);
m1.put("mno", 60);
m1.put("rst", 75);
m1.put("xyz", 35);
System.out.println(examResult(m1));
}
public static Map<String,String> examResult(Map<String, Integer> m1) {
Map<String,String> m2=new HashMap<String, String>();
String s1=new String();
String s2=new String();
int n=0;
Iterator<String> i=m1.keySet().iterator();
while(i.hasNext()){
s1=(String) i.next();
n=m1.get(s1);
if(n>=60)
s2="PASS";
else
s2="FAIL";
m2.put(s1, s2); }
return m2;
}
}
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
System.out.println(UserMainCode.getstring(stud));
}}
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class UserMainCode {
public static Map<String, String> getstring(Map<String, Float> stud)
{
Map<String, String> s=new HashMap<String, String>();
Iterator<String> it=stud.keySet().iterator();
while(it.hasNext())
{
String key=it.next();
if(stud.get(key)>=60)
{
s.put(key, "PASS");
}
else
s.put(key, "FAIL");
}
/*Set<String> key=stud.keySet();
for(String l:key)
{
if(stud.get(l)>=60)
{
s.put(l, "PASS");
}
else
s.put(l, "FAIL");
}*/
return s;
}
}
Given a string input, write a program to find the total number of vowels in the given string.
Include a class UserMainCode with a static method countVowels that accepts a String
argument and returns an int that corresponds to the total number of vowels in the given string.
Create a class Main which would get the String as input and call the static
method countVowels present in the UserMainCode.
Sample Input:
avinash
Sample Output:
import java.io.*;
import java.util.*;
String s1 = sc.next();
System.out.println(s1.length() - s2.length());
Or
import java.util.Scanner;
public class Main {
System.out.println(UserMainCode.getstring(s));
}}
public class UserMainCode {
public static Integer getstring(String s)
{
String s1;
s1=s.replaceAll("[aeiouAEIOU]", "");
int r=s.length()-s1.length();
return r;
}
}
Given a negative number as string input, write a program to validate the number and to print
the corresponding positive number.
Include a class UserMainCode with a static method validateNumber that accepts a string
argument and returns a string. If the argument string contains a valid negative number, the
method returns the corresponding positive number as a string. Else the method returns -1.
Create a class Main which would get a String as input and call the static
method validateNumber present in the UserMainCode.
Sample Input 1:
-94923
Sample Output 1:
94923
Sample Input 2:
-6t
Sample Output 2:
-1
import java.io.*;
import java.util.*;
String s1 = sc.next();
if (s1.matches("[-0-9]{1,}")) {
int s2 = Math.abs(Integer.parseInt(s1));
String s3 = String.valueOf(s2);
System.out.println(s3);
} else {
System.out.println("-1");
Or
import java.util.Scanner;
public class Main {
}}
String s1;
if(s.matches("[-0-9]{1,}"))
s1=s.replaceAll("-", "");
else
s1="-1";
return s1;
}
}
Write a program to read Date of Joining and current date as Strings and Experience as integer
and validate whether the given experience and calculated experience are the same. Print
true if same, else false.
Create a Class Main which would be used to accept 2 string (dates) and an integer and call
the static method present in UserMainCode.
Input consists of 2 strings and an integer, where the 2 strings corresponds to the date of
joining and current date, and the integer is the experience.
Sample Input 1:
11/01/2010
01/09/2014
Sample Output 1:
true
Sample Input 2:
11/06/2009
01/09/2014
Sample Output 2:
false
package gokul.javarevsi.dates;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class gkdate {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
String s2 = sc.next();
int val = sc.nextInt();
// first String Date
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
Date d1 = sdf.parse(s1);
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
Date d2 = cal.getTime();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
int y1 = Integer.parseInt(sdf1.format(d2));
// Second String date
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
sdf2.setLenient(false);
Date d3 = sdf.parse(s2);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(d3);
Date d4 = cal1.getTime();
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy");
int y2 = Integer.parseInt(sdf3.format(d4));
------------ OR------------------
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.io.*;
}
catch(Exception e){}
long difff=d2.getYear()-d1.getYear();
System.out.println(difff);
//int exp =2;
// boolean b=false;
if (difff == val) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
import java.text.ParseException;
import java.util.Scanner;
String s=sc.next();
String s1=sc.next();
int n=sc.nextInt();
System.out.println(UserMainCode.empdis(s,s1,n));
}
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
if(b2-b1==diff)
{
res=true;
}
else
res=false;
return res;
}
}
75. Retirement
Given an input as HashMap which contains key as the ID and dob as value of employees,
write a program to find out employees eligible for retirement. A person is eligible for
retirement if his age is greater than or equal to 60.
Create a class Main which would get the HashMap as input and call the static
method retirementEmployeeList present in the UserMainCode.
The first line of the input consists of an integer n, that corresponds to the number of
employees.
The next 2 lines of the input consists of strings that correspond to the id and dob of employee
1.
The next 2 lines of the input consists of strings that correspond to the id and dob of employee
2.
and so on...
Output consists of the list of employee ids eligible for retirement in sorted order.
Sample Input :
4
C1010
02/11/1987
C2020
15/02/1980
C3030
14/12/1952
T4040
20/02/1950
Sample Output :
[C3030, T4040]
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
for(int i=0;i<n;i++)
{
String s=sc.next();
String s1=sc.next();
mid.put(s, s1);
}
System.out.println(UserMainCode.empdis(mid));
}
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
Set<String> s1=m1.keySet();
for(String k1:s1)
{
String d=m1.get(k1);
SimpleDateFormat sdf=new
SimpleDateFormat("dd/MM/yyyy");
GregorianCalendar gc1=new GregorianCalendar();
Date dt=sdf.parse(d);
gc1.setTime(dt);
gc1.add(Calendar.YEAR, 60);
if(gc.after(gc1) || gc.equals(gc1))
{
res.add(k1);
}
}
return res;
}
}
Get a string and a positive integer n as input .The last n characters should repeat the number
of times given as second input.Write code to repeat the set of character from the given string.
Include a class UserMainCode with a static method getString which accepts a string and an
integer n as input.
Create a class Main which would get the input and call the static method getString present in
the UserMainCode.
Sample Input 1:
Cognizant
Sample Output 1:
Cognizantantantant
Sample Input 2:
myacademy
Sample Output 2:
myacademymymy
import java.io.*;
import java.util.*;
String s1 = sc.next();
int s2 = sc.nextInt();
int s3 = s1.length();
System.out.println(s4);
sb.append(s4);
System.out.println(sb);
}
Or
import java.util.Scanner;
public class Main {
}}
Write a program to read a number , calculate the sum of squares of even digits (values)
present in the given number.
Create a class Main which would get the input as a positive integer and call the static method
sumOfSquaresOfEvenDigits present in the UserMainCode.
Sample Input 1:
56895
Sample Output 1:
100
import java.io.*;
import java.util.*;
int a = sc.nextInt();
while (a != 0) {
rem = a % 10;
if (rem % 2 == 0) {
sum += square;
a /= 10;
System.out.println(sum);
Or
import java.util.Scanner;
public class Main {
int n=sc.nextInt();
System.out.println(UserMainCode.getstring(n));
}}
int p=n,r,s=0;
while(p>0)
{
r=p%10;
if(r%2==0)
s=s+(r*r);
p=p/10;
}
return s;
}
If all the conditions are satisifed then print TRUE else print FALSE.
Include a class UserMainCode with a static method validate which accepts the string. The
return type is the boolean formed based on rules.
Create a Class Main which would be used to accept the string and call the static method
present in UserMainCode.
Sample Input 1:
vR4u
Sample Output 1:
TRUE
Sample Input 2:
vRau
Sample Output 2:
FALSE
Sample Input 3:
vrau
Sample Output 3:
FALSE
import java.io.*;
import java.util.*;
String s1 = sc.next();
if (s1.matches("[a-zA-Z0-9]{1}[R]{1}[0-9]{1}[a-zA-Z]{1}")) {
System.out.println("True");
} else {
System.out.println("False");
Or
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String s=sc.next();
System.out.println(UserMainCode.getstring(s));
}}
}
if(s.matches("([a-zA-Z0-9]{1})(R){1}([0-9]{1})([a-zA-Z]{1})"))
s="TRUE";
else
s="FALSE";
return s;
}
Write a program to read a positive number as input and to get the reverse of the given number
and return it as output.
The return type is an integer value which is the reverse of the given number.
Create a Main class which gets the input as a integer and call the static
method reverseNumber present in the UserMainCode
Output is an integer .
Sample Input 1:
543
Sample Output 1:
345
Sample Input 1:
1111
Sample Output 1:
1111
import java.io.*;
import java.util.*;
int a = sc.nextInt();
while (a != 0) {
rem = a % 10;
a /= 10;
System.out.println(rev);
}
import java.util.Scanner;
public class Main {
return sb.toString();
}
Or
import java.util.Scanner;
public class Main {
Integer s=sc.nextInt();
System.out.println(UserMainCode.getstring(s));
}}
int n=0,r;
while(s>0)
{
r=s%10;
n=n*10+r;
s=s/10;
}
return n;
}
Given an int array as input, write a program to compute the average of the maximum and
minimum element in the array.
Create a class Main which would get the input array and call the static
method getBoundaryAverage present in the UserMainCode.
Input and Output Format:
The first line of the input consists of an integer n, that corresponds to the size of the array.
The next n lines consist of integers that correspond to the elements in the array.
Assume that the maximum number of elements in the array is 10.
Output consists of a single float value that corresponds to the average of the max and min
element in the array.
Sample Input :
Sample Output:
5.5
import java.util.*;
import java.util.Arrays;
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.println(UserMainCode.getstring(a));
}}
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;
int d=a[0]+a[a.length-1];
float a1=(float)d/2;
return a1;
}
}
Write a program to calculate discount of the acccount holders based on the transaction
amount and registration date using below mentioned prototype:
1. Read account details from the User. The details would include id, DOR (date of
registration) and transaction amount in the given order. The datatype for id is string, DOR is
string and transaction amount is integer.
2. You decide to build two hashmaps. The first hashmap contains employee id as key and
DOR as value, and the second hashmap contains same employee ids as key and amount as
value.
3. Discount Amount as on 01/01/2015:
a. If the transaction amount greater than or equal to 20000 and registration greater than or
equal to 5 year then discount rate is 20% of transaction amount.
b. If the transaction amount greater than or equal to 20000 and registration less then to 5
year then discount rate is 10% of transaction amount.
c. If the transaction amount less than to 20000 and registration greater than or equal to 5
year then discount rate is 15% of transaction amount.
d. If the transaction amount less than to 20000 and registration less then to 5 year then
discount rate is 5% of transaction amount.
4. You decide to write a function calculateDiscount which takes the above hashmaps as input
and returns the treemap as output. Include this function in class UserMainCode.
Create a Class Main which would be used to read employee details in step 1 and build the
two hashmaps. Call the static method present in UserMainCode.
Input and Output Format:
Input consists of transaction details. The first number indicates the size of the employees. The
next three values indicate the user id, user DOR and transaction amount. The DOR (Date of
Registration) format is dd-mm-yyyy
Output consists of a string which has the user id and discount amount one in a line for each
user.
Refer sample output for formatting specifications.
Sample Input 1:
4
A-1010
20-11-2007
25000
B-1011
04-12-2010
30000
C-1012
11-11-2005
15000
D-1013
02-12-2012
10000
Sample Output 1:
A-1010:5000
B-1011:3000
C-1012:2250
D-1013:500
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
Set<String> s1=m1.keySet();
Set<String> s2=m2.keySet();
SimpleDateFormat sdf1=new SimpleDateFormat("dd-MM-yyyy");
String ss="01-01-2015";
Date dr=sdf1.parse(ss);
GregorianCalendar gc1=new GregorianCalendar();
gc1.setTime(dr);
Date dt=sdf.parse(d);
gc.setTime(dt);
gc.add(Calendar.YEAR, 5);
}
else if(sal>=20000 && gc.after(gc1))
{
cal=.1f*sal;
}
else if(sal<20000 && gc1.after(gc) ||
gc.equals(gc1))
{
cal=.15f*sal;
}
else if(sal<20000 && gc.after(gc1))
{
cal=.05f*sal;
}
rm.put(k1, (int)cal);
}
}
}
return rm;
}
}
Write a program to read a integer array, find the largest span in the array.
Span is the count of all the elements between two repeating elements including the repeated
elements.
Include a class UserMainCode with a static method getLargestSpan which accepts the
integer array. The return type is integer.
Create a Class Main which would be used to accept the integer array and call the static
method present in UserMainCode.
Sample Input 1:
6
4
2
1
4
5
7
Sample Output 1:
4
import java.util.*;
import java.util.Arrays;
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.println(UserMainCode.getstring(a));
}}
public class UserMainCode {
public static int getstring(int a[])
{
int c,m=0,l;
l=a.length;
for(int i=0;i<l;i++)
{
for(int j=i+1;j<l;j++)
{
if(a[i]==a[j])
{ c=j-i+1;
if(c>m)
m=c;
}
}
}
return m;
}
}
Write a program that accepts a positive number as input and calculates the sum of squares of
individual digits of the given number.
Create a class Main which would get an integer as input and call the static
method getSumOfSquaresOfDigits present in the UserMainCode.
Sample Input:
321
Sample Output:
14
import java.util.*;
import java.util.Arrays;
int n=sc.nextInt();
System.out.println(UserMainCode.getstring(n));
}}
102.Write a code get a password as string input and validate using the rules specified below.
Apply following validations:
Create a class Main which would get the input and call the static
method validatePassword present in the UserMainCode.
ashok_23
Sample Output 1:
Valid
Sample Input 2:
1980_200
Sample Output 2:
Invalid
import java.util.*;
public class ClassSeT40 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String s1=s.next();
boolean b=passwordValidation(s1);
if(b==true)
System.out.println("valid password");
else
System.out.println("not a valid password");
}
public static boolean passwordValidation(String s1) {
boolean b=false,b1=false,b2=false;
if(s1.length()>=8)
if(!Character.isDigit(s1.charAt(0)))
if(s1.charAt(0)!='@' && s1.charAt(0)!='_' && s1.charAt(0)!='#')
if(s1.charAt(s1.length()-1)!='@' && s1.charAt(s1.length()-1)!='_' &&
s1.charAt(s1.length()-1)!='#')
b1=true;
if(b1==true)
for(int i=0;i<s1.length();i++)
if(Character.isAlphabetic(s1.charAt(i)) || Character.isDigit(s1.charAt(i)) ||
s1.charAt(i)=='#' || s1.charAt(i)=='@' || s1.charAt(i)=='_')
b2=true;
if(b2==true)
if(s1.contains("#") || s1.contains("@") || s1.contains("_"))
b=true;
return b;
}
}
import java.util.Scanner;
System.out.println(UserMainCode.usermethod(pw));
String r="";
if(pw.length()>=8)
{
if(pw.matches("([a-zA-z]{1})([a-zA-z0-9@#_]{6,})([a-zA-
Z0-9]{1})"))
{
r="Valid";
}
else
r="Invalid";
}
else
r="Invalid";
return r;
}
85.Sum of cubes and squares of elements in an array
Write a program to get an int array as input and identify even and odd numbers. If number is
odd get cube of it, if number is even get square of it. Finally add all cubes and squares
together and return it as output.
Include a class UserMainCode with a static method addEvenOdd which accepts integer
array as input.
The return type of the output is an integer which is the sum of cubes and squares of elements
in the array.
Create a class Main which would get the input and call the static
method addEvenOdd present in the UserMainCode.
Sample Input 1:
Sample Output 1:
208
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
int squaresum = 0, cubesum = 0;
int a[] = new int[s];
for (int i = 0; i < s; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 != 0) {
cubesum += a[i] * a[i] * a[i];
} else {
squaresum += a[i] * a[i];
}
}
int cs = cubesum + squaresum;
System.out.println(cs);
}
}
86.Interest Calculation
Write a program to calculate amount of the acccount holders based on the below mentioned
prototype:
1. Read account details from the User. The details would include id, DOB (date of birth) and
amount in the given order. The datatype for id is string, DOB is string and amount is integer.
2. You decide to build two hashmaps. The first hashmap contains employee id as key and
DOB as value, and the second hashmap contains same employee ids as key and amount as
value.
3. Rate of interest as on 01/01/2015:
a. If the age greater than or equal to 60 then interest rate is 10% of Amount.
b.If the age less then to 60 and greater than or equal to 30 then interest rate is 7% of
Amount.
v. If the age less then to 30 interest rate is 4% of Amount.
4. Revised Amount= principle Amount + interest rate.
5. You decide to write a function calculateInterestRate which takes the above hashmaps as
input and returns the treemap as output. Include this function in class UserMainCode.
Create a Class Main which would be used to read employee details in step 1 and build the
two hashmaps. Call the static method present in UserMainCode.
Sample Input 1:
4
SBI-1010
20-01-1987
10000
SBI-1011
03-08-1980
15000
SBI-1012
05-11-1975
20000
SBI-1013
02-12-1950
30000
Sample Output 1:
SBI-1010:10400
SBI-1011:16050
SBI-1012:21400
SBI-1013:33000
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
Set<String> s1=m1.keySet();
Set<String> s2=m2.keySet();
SimpleDateFormat sdf1=new SimpleDateFormat("dd-MM-yyyy");
String ss="01-01-2015";
Date dr=sdf1.parse(ss);
GregorianCalendar gc=new GregorianCalendar();
gc.setTime(dr);
if(gc.after(gc1) || gc.equals(gc1))
{
cal=sal+.1f*sal;
}
if(gc.before(gc1)|| gc.equals(gc1))
{
if(gc.after(gc2)||gc.equals(gc2))
cal=sal+.07f*sal;
}
if(gc2.after(gc) )
{
cal=sal+.04f*sal;
rm.put(k1, (int)cal);
}
}
}
return rm;
}
}
87.String Processing - V
Write a program to read a string and also a number N. Form a new string made up of n
repetitions of the last n characters of the String. You may assume that n is between 1 and the
length of the string.
Create a Class Main which would be used to accept the string and integer and call the static
method present in UserMainCode.
Sample Input 1:
Hello
2
Sample Output 1:
lolo
Sample Input 2:
Hello
3
Sample Output 2:
llollollo
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
int a = sc.nextInt();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < a; i++) {
sb.append(s.substring(s.length() - a));
}
System.out.println(sb);
}
}
Or
import java.util.Scanner;
System.out.println(UserMainCode.usermethod(pw,n));
String r="";
int c=n;
StringBuffer sb=new StringBuffer();
while(c>0)
{sb.append(pw.substring(pw.length()-n));
c--;
}
r=sb.toString();
return r;
}
88.String Processing - III
Write a program to read a string where all the lowercase 'x' chars have been moved to the end
of the string.
Include a class UserMainCode with a static method moveX which accepts the string. The
return type is the modified string.
Create a Class Main which would be used to accept the string and call the static method
present in UserMainCode.
Sample Input 1:
xxhixx
Sample Output 1:
hixxxx
Sample Input 2:
XXxxtest
Sample Output 2:
XXtestxx
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
String s1 = s.replaceAll("[x]", "");
String s2 = s.replaceAll("[^x]", "");
System.out.println(s1);
System.out.println(s2);
System.out.println(s1 + s2);
}
}
89.Duplicate Characters
Write a Program which removes duplicate characters from the string. Your program should
read a sentence (string) as input from user and return a string removing duplicate characters.
Retain the first occurance of the duplicate character. Assume the characters are case
sensitive.
Create a Class Main which would be used to accept the input string and call the static method
present in UserMainCode.
Sample Input 1:
Sample Output 1:
hi tsample
Sample Input 2:
ABC DEF
Sample Output 2:
ABC DEF
89.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word = sc.nextLine();
String result = new String("");
for (int i = 0; i < word.length(); i++) {
if (!result.contains("" + word.charAt(i))) {
result += "" + word.charAt(i);
}
}
System.out.println(result);
}
}
import java.util.Scanner;
String r="";
for(int i=0;i<pw.length();i++)
{
if(!r.contains(String.valueOf(pw.charAt(i))))
r=r+String.valueOf(pw.charAt(i));
}
return r;
90.Dash Check
Write a program to read two strings and check whether or not they have dashes in the same
places. Print Yes if the condition satisfies, else print No.
Include a class UserMainCode with a static method compareDashes which accepts two
strings. The return type (Integer) should return 1 if all dashes are placed correctly, else return
2.
Create a Class Main which would be used to accept two strings and call the static method
present in UserMainCode.
Note: The strings must have exactly the same number of dashes in exactly the same
positions. The strings might be of different length.
Sample Input 1:
hithere-you.
12--(134)-7539
Sample Output 1:
Yes
Sample Input 2:
-15-389
-xyw-zzy
Sample Output 2:
No
package gokul.javarevsi.dates;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class gkdate {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
int i = 0, j = 0, count = 0;
String s1 = sc.next();
String s2 = sc.next();
int a = s1.length();
int b = s2.length();
int l1[] = new int[a];
int l2[] = new int[b];
StringTokenizer st1 = new StringTokenizer(s1, "-");
StringTokenizer st2 = new StringTokenizer(s2, "-");
while (st1.hasMoreElements()) {
String x = st1.nextToken();
l1[i] = x.length();
i++;
}
while (st2.hasMoreElements()) {
String x2 = st2.nextToken();
l2[j] = x2.length();
j++;
}
for (int c = 0; c < i; c++) {
if (l1[c] == l2[c]) {
count = 1;
} else {
count = 0;
break;
}
}
if (count == 1)
System.out.println("yes");
else if (count == 0)
System.out.println("no");
}
}
91.Maximum Difference
Write a program to read an integer array and find the index of larger number of the two
adjacent numbers with largest difference. Print the index.
Input consists of n+1 integers, where n corresponds the size of the array followed by n
integers.
Sample Input :
Sample Output :
[In the sequence 4 8 6 1 9 4 the maximum distance is 8 (between 1 and 9). The function
should return the index of the greatest of two. In this case it is 9 (which is at index 4). output
= 4.]
import java.util.Scanner;
for(int i=0;i<a.length-1;i++)
{
int b=Math.abs(a[i+1]-a[i]);
if(b>m)
{
m=b;
if(a[i]>a[i+1])
c=i;
else
c=i+1;
}
}
return c;
}
}
Write a program that takes a string and returns the number of unique characters in the string.
If the given string doest not contain any unique characters return -1
Include a class UserMainCode with a static method uniqueCounter which accepts a string
as input.
The return type of the output is the count of all unique characters in the strings.
Create a class Main which would get the input and call the static
method uniqueCounter present in the UserMainCode.
Output is an integer.
Sample Input 1:
HelloWorld
Sample Output 1:
5
Sample Input 2:
coco
Sample Output 2:
-1
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
String r="";
int c=0;
StringBuffer sb=new StringBuffer(pw);
for(int i=0;i<sb.length();i++)
{
c=0;
for(int j=i+1;j<sb.length();j++)
{
if(sb.charAt(i)==sb.charAt(j))
{
sb.deleteCharAt(j);
c++;
j--;
}
}
if(c>=1){
sb.deleteCharAt(i);
i--;
}
}
System.out.println(sb);
return sb.length();
Write a program that accepts a positive number as input and calculates the sum of digits at
even indexes (say evenSum) and sum of digits at odd indexes (say oddSum) in the given
number. If both the sums are equal , print 'yes', else print no.
Example:
input = 23050
evenSum = 2 + 0 + 0 = 2
oddSum = 3 + 5 = 8
output = no
Include a class UserMainCode with a static method sumOfOddEvenPositioned that
accepts an integer and returns an integer. The method returns 1 if the 2 sums are equal. Else
the method returns -1.
Create a class Main which would get an integer as input and call the static
method sumOfOddEvenPositioned present in the UserMainCode.
Sample Input 1:
23050
Sample Output 1:
no
Sample Input 2:
231
Sample Output 2:
yes
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
Write a program to accept a string array as input, convert all the elements into lowercase and
sort the string array. Display the sorted array.
Include a class UserMainCode with a static method sortArray which accepts the string array.
The return type is the string array formed based on requirement.
Create a Class Main which would be used to accept the string array and call the static method
present in UserMainCode.
Input consists of a an integer which denotes the size of the array followed by the array of
strings,
Output consists of a string array.
Refer sample output for formatting specifications.
Sample Input 1:
5
AAA
BB
CCCC
A
ABCDE
Sample Output 1:
a
aaa
abcde
bb
cccc
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
s3[i] = al.get(i).toLowerCase();
System.out.println(s3[i]);
}
}
}
----------------0r----------------------
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
import java.util.Scanner;
for(int i=0;i<a.length;i++)
{
a[i]=a[i].toLowerCase();
}
Arrays.sort(a);
}
}
Given a method with two date strings in yyyy-mm-dd format as input. Write code to find the
difference between two dates in months.
Include a class UserMainCode with a static method getMonthDifference which accepts two
date strings as input.
The return type of the output is an integer which returns the diffenece between two dates in
months.
Create a class Main which would get the input and call the static
method getMonthDifference present in the UserMainCode.
Output is an integer.
Sample Input 1:
2012-03-01
2012-04-16
Sample Output 1:
Sample Input 2:
2011-03-01
2012-04-16
Sample Output 2:
13
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
96.String Encryption
Given an input as string and write code to encrypt the given string using following rules and
return the encrypted string:
Note:
Include a class UserMainCode with a static method encrypt which accepts a string.
Create a Main class which gets string as an input and call the static method encrypt present
in theUserMainCode.
Input is a string .
Output is a string.
Sample Input 1:
curiosity
Sample Output 1:
dusipsjtz
Sample Input 2:
zzzz
Sample Output 2:
azaz
import java.util.Scanner;
Or
import java.util.Scanner;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
for(int i=0;i<a.length();i++)
if(i%2!=0)
sb.append(a.charAt(i));
else
char c=a.charAt(i);
if(c=='z')
c='a';
else
c++;
sb.append(c);
return sb.toString();
97.ArrayFront
Write a program to read a integer array and return true if one of the first 4 elements in the
array is 9 else return false.
Note: The array length may be less than 4.
Include a class UserMainCode with a static method scanArray which accepts the integer
array. The return type is true / false.
Create a Class Main which would be used to accept the integer array and call the static
method present in UserMainCode.
Sample Input 1:
6
1
2
3
4
5
6
Sample Output 1:
FALSE
Sample Input 2:
3
1
2
9
Sample Output 2:
TRUE
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
System.out.println("False");
}
}
}
98.Max Vowels
Write a Program which fetches the word with maximum number of vowels. Your program
should read a sentence as input from user and return the word with max number of vowels. In
case there are two words of maximum length return the word which comes first in the
sentence.
Create a Class Main which would be used to accept two Input strings and call the static
method present in UserMainCode.
Sample Input 1:
Sample Output 1:
Appreciation
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
String s=sc.nextLine();
System.out.println(UserMainCode.getstring(s));
}}
public class UserMainCode {
public static String getstring(String s)
{
int m=0;
String op="";
StringTokenizer st=new StringTokenizer(s," ");
while(st.hasMoreTokens())
{
String v=st.nextToken();
String r=v;
r=r.replaceAll("[aeiouAEIOU]", "");
if(m<(v.length()-r.length()))
{
m=v.length()-r.length();
op=v;
}
}
return op;
}
}
99.Date Validation
Write a program to read a string representing a date. The date can be in any of the three
formats
Include a class UserMainCode with a static method getValidDate which accepts a string. The
return type (integer) should be based on the validity of the date.
Create a Class Main which would be used to accept Input string and call the static method
present in UserMainCode.
Sample Input 1:
03.12.2013
Sample Output 1:
valid
Sample Input 2:
03$12$2013
Sample Output 3:
Invalid
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
Given a phone number as a string input, write a program to verify whether the phone number
is valid using the following business rules:
Create a class Main which would get a String as input and call the static
method validatePhoneNumber present in the UserMainCode.
Sample Input 1:
265-265-7777
Sample Output 1:
Valid
Sample Input 2:
265-65-7777
Sample Output 1:
Invalid
import java.util.Scanner;
import java.util.StringTokenizer;
101.Average of Primes
Write a program to read an array and find average of all elements located at index i, where i is
a prime number. Type cast the average to an int and return as output. The index starts from 0.
Include a class UserMainCode with a static method addPrimeIndex which accepts a single
integer array. The return type (integer) should be the average of all elements located at index i
where i is a prime number.
Create a Class Main which would be used to accept Input array and call the static method
present in UserMainCode.
Input consists of n+1 integers. The first integer corresponds to n, the number of elements in
the array. The next 'n' integers correspond to the elements in the array.
Assume that the maximum number of elements in the array is 20 and minimum number of
elements is 3.
Sample Input 1:
Sample Output 1:
3
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
102.Palindrome - In Range
Write a program to input two integers, which corresponds to the lower limit and upper limit
respectively, and find the sum of all palindrome numbers present in the range including the
two numbers. Print the sum.
Include a class UserMainCode with a static method addPalindromes which accepts two
integers. The return type (Integer) should return the sum if the palindromes are present, else
return 0.
Create a Class Main which would be used to accept two integer and call the static method
present in UserMainCode.
Note1 : A palindrome number is a number which remains same after reversing its digits.
Input consists of 2 integers, which corresponds to the lower limit and upper limit respectively.
Sample Input :
130
150
Sample Output :
272
(131+141 = 272)
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
int ll = sc.nextInt();
int ul = sc.nextInt();
rev = 0;
temp = i;
while (temp != 0) {
temp /= 10;
if (rev == i) {
sum += rev;
System.out.println(sum);
103.Math Calculator
Write a program that accepts three inputs, first two inputs are operands in int form and third
one being one of the following five operators: +, -, *, /, %. Implement calculator logic and
return the result of the given inputs as per the operator provided. In case of division, Assume
the result would be integer.
Include a class UserMainCode with a static method calculator which accepts two integers,
one operand and returns the integer.
Create a Class Main which would be used to accept three integers and call the static method
present in UserMainCode.
Sample Input 1:
23
2
*
Sample Output 1:
46
import java.io.*;
import java.util.*;
104.Shift Left
Write a program to read a integer array of scores, and return a version of the given array
where all the 5's have been removed. The remaining elements should shift left towards the
start of the array as needed,
and the empty spaces at the end of the array should be filled with 0.
Include a class UserMainCode with a static method shiftLeft which accepts the integer array.
The return type is modified array.
Create a Class Main which would be used to accept the integer array and call the static
method present in UserMainCode.
Input consists of an integer n which is the number of elements followed by n integer values.
Sample Input 1:
7
1
5
2
4
5
3
5
Sample Output 1:
1
2
4
3
0
0
0
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i, k = 0;
int a[] = new int[n];
ArrayList<Integer> al = new ArrayList<Integer>();
for (i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (i = 0; i < n; i++) {
if (a[i] != 5) {
al.add(a[i]);
}
}
if (al.size() < n) {
k = n - al.size();
for (i = 0; i < k; i++) {
al.add(0);
}
}
int b[] = new int[al.size()];
for (i = 0; i < al.size(); i++) {
b[i] = al.get(i);
System.out.println(b[i]);
}
}
105.Repeat Front
Given a string (s) and non negative integer (n) apply the following rules.
2. If the length of the string is less than 3, then consider the entire string as front
and repeat it n times.
Create a Class Main which would be used to accept the string and integer and call the static
method present in UserMainCode.
Input and Output Format:
Sample Input 1:
Coward
2
Sample Output 1:
CowCow
Sample Input 2:
So
3
Sample Output 2:
SoSoSo
import java.io.*;
import java.util.*;
sb.append(s1.substring(0, s1.length()));
}
}
System.out.println(sb);
}
If all the conditions are satisifed then print TRUE else print FALSE.
Include a class UserMainCode with a static method validatePhone which accepts the string.
The return type is the boolean formed based on rules.
Create a Class Main which would be used to accept the string and call the static method
present in UserMainCode.
Sample Input 1:
9987684321
Sample Output 1:
TRUE
Sample Input 2:
0014623452
Sample Output 2:
FALSE
import java.io.*;
import java.util.*;
Given input as HashMap, value consists of marks and rollno as key.Find the sum of the
lowest three subject marks from the HashMap.
Include a class UserMainCode with a static method getLowest which accepts a Hashmap
with marks and rollno.
The return type of the output is the sum of lowest three subject marks.
Create a class Main which would get the input and call the static method getLowest present
in the UserMainCode.
Sample Input 1:
54
85
74
59
57
Sample Output 1:
170
Sample Input 2:
10
56
20
58
30
87
40
54
Sample Output 2:
168
import java.io.*;
import java.util.*;
Write a program to read a string and check if it starts with '_ix' where '_' is any one char(a-z,
A-Z, 0-9).
Include a class UserMainCode with a static method checkPattern which accepts the string.
The return type is TRUE / FALSE.
Create a Class Main which would be used to accept the string and call the static method
present in UserMainCode.
Sample Input 1:
Mix Mania
Sample Output 1:
TRUE
import java.util.*;
} else {
System.out.println("invalid");
}
}
}
109.Perfect Number
Write a program to that takes a positive integer and returns true if the number is perfect
number.
A positive integer is called a perfect number if the sum of all its factors (excluding the
number itself, i.e., proper divisor) is equal to its value.
For example, the number 6 is perfect because its proper divisors are 1, 2, and 3, and
6=1+2+3; but the number 10 is not perfect because its proper divisors are 1, 2, and 5, and
1+2+5 is not equal to 10
Include a class UserMainCode with a static method getPerfection which accepts the number.
The return type is boolean (true / false).
Create a Class Main which would be used to accept the string and call the static method
present in UserMainCode.
Sample Input 1:
28
Sample Output 1:
TRUE
import java.io.*;
import java.util.*;
Write a program to read a string and to test whether first and last character are same. The
string is said to be be valid if the 1st and last character are the same. Else the string is said to
be invalid.
Include a class UserMainCode with a static method checkCharacters which accepts a string
as input .
The return type of this method is an int. Output should be 1 if the first character and last
character are same . If they are different then return -1 as output.
Create a class Main which would get the input as a string and call the static
method checkCharacterspresent in the UserMainCode.
Sample Input 1:
Sample Output 1:
Valid
Sample Input 1:
this
Sample Output 1:
Invalid
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
StringBuffer sb = new StringBuffer(s);
sb.reverse();
String s1 = sb.toString();
if (s.charAt(0) == s1.charAt(0)) {
System.out.println("valid");
} else {
System.out.println("invalid");
}
}
111.Max Scorer
Include a class UserMainCode with the static method highestScorer which accepts the
arraylist and returns the name (string) of max scorer.
Create a Class Main which would be used to read n strings into arraylist and call the static
method present in UserMainCode.
Input consists of 1 integer and n strings. The first integer denotes the size of the arraylist, the
next n strings are score pattern described above.
Sample Input 1:
3
sunil-56-88-23
bindul-88-70-10
john-70-49-65
Sample Output 1:
john
import java.io.*;
import java.util.*;
while (st.hasMoreTokens()) {
String s = st.nextToken();
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
sum = a + b + c;
if (sum > max) {
max = sum;
s1 = s;
}
}
}
System.out.println(s1);
}
}
112.Valid Date
Given a date string as input, write a program to validate if the given date is in any of the
following formats:
dd.mm.yyyy
dd/mm/yy
dd-mm-yyyy
Include a class UserMainCode with a static method validateDate that accepts a String and
returns an integer. This method returns 1 if the date is valid, else return -1.
Create a class Main which would get a String as input and call the static
method validateDate present in the UserMainCode.
Sample Input 1:
12.03.2012
Sample Output 1:
Valid
Sample Input 2:
27#01#1977
Sample Output 2:
Invalid
import java.io.*;
import java.util.*;
A Company wants to obtain employees of a particular designation. You have been assigned as
the programmer to build this package. You would like to showcase your skills by creating a
quick prototype. The prototype consists of the following steps:
Read Employee details from the User. The details would include name and designaton in
the given order. The datatype for name and designation is string.
Build a hashmap which contains the name as key and designation as value.
You decide to write a function obtainDesignation which takes the hashmap and
designation as input and returns a string array of employee names who belong to that
designation as output. Include this function in class UserMainCode.
Create a Class Main which would be used to read employee details in step 1 and build the
hashmap. Call the static method present in UserMainCode.
Sample Input 1:
4
Manish
MGR
Babu
CLK
Rohit
MGR
Viru
PGR
MGR
Sample Output 1:
Manish
Rohit
import java.io.*;
import java.util.*;
if (e.getValue().equals(s)) {
s1[k] = (String) e.getKey();
k++;
}
}
for (i = 0; i < s1.length - 1; i++)
System.out.println(s1[i]);
}
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
int i,j,n;
System.out.println("Enter no of student");
n=sc.nextInt();
String name;
name=sc.next();
for(j=0;j<3;j++)
num.add(sc.nextInt());
record.put(name,num);
Set<String> keys=record.keySet();
for(String nam:keys)
{ int sum=0;
System.out.println(nam);
List<Integer> bb=record.get(nam);
for(int marks:bb)
{ sum=sum+marks;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.text.ParseException;
import java.text.SimpleDateFormat;
Date dat=sdf.parse(d);
Date dat1=sdf.parse(da1);
int dr,mr,yr;
gc.setTime(dat);
int d1=gc.get(Calendar.DATE);
int m1=gc.get(Calendar.MONTH);
int y1=gc.get(Calendar.YEAR);
gc.setTime(dat1);
int d2=gc.get(Calendar.DATE);
int m2=gc.get(Calendar.MONTH);
int y2=gc.get(Calendar.YEAR);
if(d2>d1)
dr=(d1+30)-d2;
m1-=1;
else
dr=d1-d2;
if(m2>m1)
mr=(m1+12)-m2;
y1-=1;
else
mr=m1-m2;
yr=y2-y1;
return res;