All 17 PDF Free
All 17 PDF Free
All 17 PDF Free
WHILE i<=number
SET Fact=Fact*i
SET i=i+1
ENDWHILE
PRINT Fact
END
NumberOfDigits(number):
SET count=0
ENDWHILE
PRINT count
END
NumberOfDigits(number):
SET count=0
ENDWHILE
PRINT count
END
1) Find the sum of the numbers in the given input string array
Input{“2AA”,”12”,”ABC”,”c1a”)
Output:6 (2+1+2+1)
String[] s1={"2AA","12","A2C","C5a"};
getSum(s1); }
int sum=0;
for(int i=0;i<s1.length;i++)
for(int j=0;j<s1[i].length();j++){
char c=s1[i].charAt(j);
if(Character.isDigit(c)){
String t=String.valueOf(c);
int n=Integer.parseInt(t);
sum=sum+n; } }
System.out.println(sum); }
----------------------------------------------------------------------------------------------------||
2) Create a program to get the hashmap from the given input string array where the key for the hashmap
is first three letters of array element in uppercase and the value of hashmap is the element itself
Output:{{GOA,goa},{KER,kerala},{GUJ,Gujarat}} [hashmap]
package Set3;
import java.util.*;
String[] s1={"goa","kerala","gujarat"};
putvalues(s1);
for(String s:s1)
l1.add(s.toUpperCase().substring(0, 3));
for(String s:s1)
l2.add(s);
for(int i=0;i<l1.size();i++)
m1.put(l1.get(i),l2.get(i));
System.out.println(m1);
----------------------------------------------------------------------------------------------------||
3) String[] input1=["Vikas","Lokesh",Ashok]
package Set3;
String[] ip={"Vikas","Lokesh","Ashok"};
System.out.println(getTheNamesinGivenFormat(ip));
for(int i=0;i<ip.length;i++)
sb.append(ip[i]).append(',');
sb.deleteCharAt(sb.length()-1);
return sb.toString();
----------------------------------------------------------------------------------------------------||
4) Email Validation
String input1="[email protected]"
1)@ & . should be present;
package Set3;
import java.util.*;
String ip="[email protected]";
boolean b=emailIdValidation(ip);
if(b==true)
else
int i=0;
boolean b=false;
String s1=t.nextToken();
String s2=t.nextToken();
String s3=t1.nextToken();
String s4=t1.nextToken();
i++;
if(i==1)
if(s3.length()==5)
if(s1.length()>=3)
if(s4.equals("com"))
b=true;
return b;
----------------------------------------------------------------------------------------------------||
((x1+x2)*(x1+x2))+((y1+y2)*(y1+y2))
package Set3;
int x1=4,x2=8;
int y1=3,y2=5;
sqrt(x1,x2,y1,y2);
public static void sqrt(int x1, int x2, int y1, int y2) {
int op;
op=(int) (Math.sqrt((x1+x2)*(x1+x2))+((y1+y2)*(y1+y2)));
System.out.println(op);
----------------------------------------------------------------------------------------------------||
i/p 2="hari";
o/p string[]={"ram","cts"};
package Set3;
import java.util.*;
import java.util.Map.Entry;
m1.put("ram","hari");
m1.put("cisco","barfi");
m1.put("honeywell","cs");
m1.put("cts","hari");
String s2="hari";
getvalues(m1,s2);
ArrayList<String>l1=new ArrayList<String>();
m.getKey();
m.getValue();
if(m.getValue().equals(s2))
l1.add(m.getKey()); }
for(int i=0;i<l1.size();i++){
op[i]=l1.get(i) ;
System.out.println(op[i]); }
----------------------------------------------------------------------------------------------------||
7) Input1={“ABX”,”ac”,”acd”};
Input2=3;
Output1=X$d
package Set3;
import java.util.*;
String[] s1={"abc","da","ram","cat"};
int ip=3;
getStr(s1,ip);
for(String s:s1)
if(s.length()==ip)
l1.add(s);
for(String l:l1){
s2=l.substring(l.length()-1);
buff.append(s2).append("$"); }
op=buff.deleteCharAt(buff.length()-1).toString();
System.out.println(op);
----------------------------------------------------------------------------------------------------||
8) INPUT1= helloworld
if occurs more than twice,leave the first occurence and delete the duplicate
O/P= helwrd;
package Set3;
String input1="HelloWorld";
int input2=2;
System.out.println(deletingtheCharOccuringTwice(input1,input2));
int c=1;
for(int i=0;i<sb.length();i++){
c=1;
for(int j=i+1;j<sb.length();j++)
if(sb.charAt(i)==sb.charAt(j))
c++;
if(c>=input2){
for(int j=i+1;j<sb.length();j++)
if(sb.charAt(i)==sb.charAt(j))
sb.deleteCharAt(j);
sb.deleteCharAt(i);
i--; } }
return sb.toString();
----------------------------------------------------------------------------------------------------||
operation-- for how many strings input2 matches the prefix of each string in input1
String[] input={"01","01010","1000","10","011"}
output=3; count the strings having prefix"10","01" but "10","01" not included
package Set3;
import java.util.*;
String[] ip={"100","111","10100","10","1111"};
gteCount(ip);
for(String s:ip)
l1.add(s);
op=l1.size();
System.out.println(op);
----------------------------------------------------------------------------------------------------||
if value equal to 13,escape the value '13', as well as the next value to 13.
package Set3;
import java.util.*;
int ip1=13,ip2=2,ip3=8;
System.out.println(thirteenLapse(ip1,ip2,ip3));
l.add(ip1);
l.add(ip2);
l.add(ip3);
int s=0;
for(int i=0;i<l.size();i++){
if(l.get(i)!=13)
s+=l.get(i);
if(l.get(i)==13)
i=i+1;}
return s;
----------------------------------------------------------------------------------------------------||
11) input="hello"
package Set3;
String s="Hello";
System.out.println(alternatingChar(s));
for(int i=0;i<s.length();i++)
if(i%2==0)
sb.append(s.charAt(i));
return sb.toString();
----------------------------------------------------------------------------------------------------||
package Set3;
System.out.println(reArrangingWord(s));
}
public static String reArrangingWord(String s) {
sb.append(s.substring(s.length()-1));
sb.append(s.substring(1, s.length()-1));
sb.append(s.substring(0, 1));
return sb.toString();
----------------------------------------------------------------------------------------------------||
package Set3;
import java.util.*;
l1.add(1);
l1.add(2);
l1.add(3);
l1.add(4);
l2.add(1);
l2.add(2);
l2.add(3);
l2.add(5);
int o[]=commonSet(l1,l2);
for(int i:o)
System.out.println(i);
}
public static int[] commonSet(List<Integer> l1, List<Integer> l2) {
l3.addAll(l1);l4.addAll(l2);
l1.removeAll(l2);l4.removeAll(l3);
l1.addAll(l4);
for(int j=0;j<o.length;j++)
o[j]=l1.get(j);
return o;
----------------------------------------------------------------------------------------------------||
14) String array will be given.if a string is Prefix of an any other string in that array means count.
package Set3;
String[] a={"pinky","preethi","puppy","preeth","puppypreethi"};
System.out.println(namesWithPreFixes(a));
int n=0;
for(int i=0;i<a.length;i++)
for(int j=i+1;j<a.length;j++){
String s1=a[i];
String s2=a[j];
if(s2.startsWith(s1)||s1.startsWith(s2))
n++; }
return n;
}
----------------------------------------------------------------------------------------------------||
output=4;
package Set3;
import java.util.StringTokenizer;
System.out.println(noOfWordsInString(s));
return t.countTokens();
----------------------------------------------------------------------------------------------------||
output=true;
int[] input={1,2,1,3,4,5,8};
output=false
package Set3;
//int[] a={2,1,4,1,2,3,6};
int[] a={1,2,1,3,4,5,8};
System.out.println(sequenceInArray(a));
}
boolean b=false;
int n=0;
for(int i=0;i<a.length-1;i++)
if((a[i+1]-a[i])==1)
n++;
if(n==2)
b=true;
return b;
----------------------------------------------------------------------------------------------------||
char input2='/'
output1[]={"aaa","bba","ccc"};
package Set3;
import java.util.*;
String ip1="AAA/abb/CCC";
char ip2='/';
String op[]=loweringCasenReverseofaString(ip1,ip2);
for(String s:op)
System.out.println(s);
}
while(t.hasMoreTokens()){
l.add(sb.reverse().toString()); }
for(int i=0;i<op.length;i++)
op[i]=l.get(i);
return op;
----------------------------------------------------------------------------------------------------||
Input1=”so”;output1=”sososo”;
package Set3;
String ip1="cowboy";
String ip2="cow";
System.out.println(printingStringDependingOncharCount(ip1,ip2));
int n1=ip2.length();
if(n1==3)
for(int i=0;i<n1-1;i++)
sb.append(ip1.substring(0, n1));
else if(n1==2)
for(int i=0;i<n1+1;i++)
sb.append(ip1.substring(0, n1));
return sb.toString();
----------------------------------------------------------------------------------------------------||
19) input---input1=1;
input2=4;
input3=1;
output1=4;
input---input1=1;
input2=2;
input3=3;
output1=6;
package Set3;
int ip1=1,ip2=4,ip3=1;
//int ip1=1,ip2=2,ip3=3;
//int ip1=1,ip2=1,ip3=1;
System.out.println(sumOfNonRepeatedChars(ip1,ip2,ip3));
int n=0;
n=ip1+ip2+ip3;
n=0;
else{
if(ip1==ip2)
n=ip3;
else if(ip1==ip3)
n=ip2;
else if(ip2==ip3)
n=ip1; }
return n;
----------------------------------------------------------------------------------------------------||
20) input1-List1-{apple,orange,grapes}
input2-List2-{melon,apple,mango}
output={mango,orange}
package Set3;
import java.util.*;
l1.add("apple");
l1.add("orange");
l1.add("grapes");
l2.add("melon");
l2.add("apple");
l2.add("mango");
String[] s2=fruitsList(l1,l2);
for(String s3:s2)
System.out.println(s3);
for(int i=0;i<l1.size();i++){
String s1=l1.get(i);
l3.add(s1); }
for(int i=0;i<l2.size();i++){
String s1=l2.get(i);
l3.add(s1); }
Collections.sort(l3);
for(int i=0;i<s2.length;i++)
s2[i]=l3.get(i);
return s2;
----------------------------------------------------------------------------------------------------||
operation-- if the character before and after * are same return true else false
package Set3;
import java.util.*;
String input="Hello*world";
System.out.println(characterCheck(input));
}
public static boolean characterCheck(String input) {
boolean b=false;
String s1=t.nextToken();
String s2=t.nextToken();
String s3=s1.substring(s1.length()-1);
String s4=s2.substring(0,1);
if(s3.equalsIgnoreCase(s4))
b=true;
return b;
----------------------------------------------------------------------------------------------------||
output--String output1="aXafsdxx"
operation-- remove the character "x"(only lower case) from string and place at the end
package Set3;
String input="xaXafxsd";
System.out.println(removalOfx(input));
int j=0;
for(int i=0;i<sb.length();i++)
if(sb.charAt(i)=='x'){
sb.deleteCharAt(i);
j++;}
for(int i=0;i<j;i++)
sb.append('x');
return sb.toString();
----------------------------------------------------------------------------------------------------||
HashMap<String,String> h2={“abc”:”fail”,”efg”:”pass”}
package Set3;
import java.util.*;
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));
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;
----------------------------------------------------------------------------------------------------||
sTRING i/p2=5
package Set3;
import java.text.*;
import java.util.*;
String ip1="2012";
String ip2="5";
System.out.println(experienceCalc(ip1,ip2));
boolean b=false;
Date d1=sdf.parse(ip1);
int n1=d1.getYear();
int n2=d2.getYear();
int n3=Integer.parseInt(ip2);
if((n2-n1)>n3)
b=true;
return b;
}
----------------------------------------------------------------------------------------------------||
output: lolo
package Set3;
String s1="hello";
int n1=2;
System.out.println(formattingOfString(s1,n1));
for(int i=0;i<n1;i++)
sb.append(s2);
return sb.toString();
----------------------------------------------------------------------------------------------------||
input="0201103311"
ISBN number: sum=0*10 +2*9+ 0*8 +1*7+ 1*6 +0*5+ 3*4 +3*3+ 1*2 +1*1
package Set3;
String ip="0201103311";
boolean b=ISBNnumber(ip);
if(b==true)
System.out.println("check ur data");
boolean b=false;
int sum=0;
for(int i=0,j=ip.length();i<ip.length();i++,j--){
String s=String.valueOf(ip.charAt(i));
int n=Integer.parseInt(s);
sum+=(n*j); }
//System.out.println(sum);
if(sum%11==0)
b=true;
return b;
----------------------------------------------------------------------------------------------------||
package Set3;
import java.util.*;
String s1=s.next();
boolean b=passwordValidation(s1);
if(b==true)
System.out.println("valid password");
else
boolean b=false,b1=false,b2=false;
if(s1.length()>=8)
if(!Character.isDigit(s1.charAt(0)))
b1=true;
if(b1==true)
for(int i=0;i<s1.length();i++)
b2=true;
if(b2==true)
b=true;
return b;
----------------------------------------------------------------------------------------------------||
package Set3;
import java.util.*;
String pan=s.next();
boolean b=panNumberValidation(pan);
if(b==true)
else
boolean b=false,b1=false,b2=false;
if(pan.length()==8)
if(Character.isAlphabetic(pan.charAt(pan.length()-1)) &&
Character.isUpperCase(pan.charAt(pan.length()-1)))
b1=true;
if(b1==true)
for(int i=0;i<s1.length();i++)
b2=true;
else
{b2=false;break;}
if(b2==true)
for(int i=0;i<s2.length();i++)
if(Character.isDigit(s2.charAt(i)))
b=true;
else
{b=false;break;}
return b;
}
----------------------------------------------------------------------------------------------------||
ex: h1={1:4,2:6,4:7,5:9}
output=(4+9)/2
package Set3;
import java.util.*;
m1.put(1, 4);
m1.put(2, 6);
m1.put(4, 7);
m1.put(5, 9);
System.out.println(avgValuesOfOddKeys(m1));
int l=0,m=0;
Iterator<Integer> i=m1.keySet().iterator();
while(i.hasNext()){
if(n%2!=0){
m+=m1.get(n);
l++;} }
return m/l;
----------------------------------------------------------------------------------------------------||
30) Return 1 if the last & first characters of a string are equal else
Output= 1
package Set3;
System.out.println(checkForFirstAndLastChar(input));
int n=0;
if(input.charAt(0)==input.charAt(input.length()-1))
n=1;
else n=-1;
return n;
----------------------------------------------------------------------------------------------------||
largest string and then add. The number of characters removed from
input 2="helloworld";
output="worldhello";
package Set3;
String ip1="hello";
String ip2="helloworld";
System.out.println(removalOfCharFromLargestString(ip1,ip2));
int n1=ip1.length();
int n2=ip2.length();
if(n1<n2)
sb.append(ip2.substring(n1, n2)).append(ip1);
return sb.toString();
----------------------------------------------------------------------------------------------------||
o/p: Honesty
package Set3;
import java.util.*;
System.out.println(lengthiestString(s1));
int max=0;
loop:
while(t.hasMoreTokens()){
String s3=t.nextToken();
int n=s3.length();
if(n>max){
max=n;
s2=s3;}
if(n==max)
for(int i=0;i<s3.length();i++){
char c1=s2.charAt(i);
char c2=s3.charAt(i);
if(c1!=c2){
if(c2<c1)
s2=s3;
continue loop;} }
return s2;
----------------------------------------------------------------------------------------------------||
output=1.
package Set3;
String s1="education";
System.out.println(vowelsCheck(s1));
boolean b=false;
int n1=0,n2=0,n3=0,n4=0,n5=0;
for(int i=0;i<s1.length();i++){
char c=s1.charAt(i);
if(c=='a' || c=='A')
n1++;
if(c=='e' || c=='E')
n2++;
if(c=='i' || c=='I')
n3++;
if(c=='o' || c=='O')
n4++;
if(c=='u' || c=='U')
n5++;}
b=true;
return b;
----------------------------------------------------------------------------------------------------||
output: ofgrte
output : eNYwrok
package Set3;
String s1="newyork";
System.out.println(formattingGivenString(s1));
int j=0;
if(s1.length()%2==0)
j=s1.length();
else
j=s1.length()-1;
for(int i=0;i<j;i=i+2){
sb.append(sb1.reverse());}
if(s1.length()%2==0)
s3=sb.toString();
else
s3=sb.append(s1.charAt(s1.length()-1)).toString();
return s3;
----------------------------------------------------------------------------------------------------||
o/p: ceogbl
package Set3;
String s1="bengal";
System.out.println(stringFormatting(s1));
for(int i=0;i<s1.length();i++){
char c=s1.charAt(i);
if(i%2==0){
if(c==122)
c=(char) (c-25);
else{
c=(char) (c+1);}
sb.append(c);}
else
sb.append(c);}
return sb.toString();
----------------------------------------------------------------------------------------------------||
o/p=5
package Set3;
import java.util.*;
System.out.println(maxChunk(s1));
int max=0;
while(t.hasMoreTokens()){
String s2=t.nextToken();
int n=0;
for(int i=0;i<s2.length()-1;i++)
if(s2.charAt(i)==s2.charAt(i+1))
n++;
if(n>max)
max=n;
return (max+1);
----------------------------------------------------------------------------------------------------||
solution:
package Set3;
System.out.println(commonCharsinAstring(s1,s2));
int f;
for(int i=0;i<s1.length();i++){
f=0;
char c1=s1.charAt(i);
for(int j=0;j<s2.length();j++)
if(c1==s2.charAt(j))
f=1;
if(f!=0)
sb.append(c1);
else
sb.append('+');}
return sb.toString();
}
----------------------------------------------------------------------------------------------------||
38) input1={2,4,3,5,6};
finally add it
output1=208(4+16+27+125+36)
package Set3;
int a[]={2,4,3,5,6};
System.out.println(summationPattern(a));
int n1=0,n2=0;
for(int i=0;i<a.length;i++)
if(a[i]%2==0)
n1+=(a[i]*a[i]);
else
n2+=(a[i]*a[i]*a[i]);
return n1+n2;
----------------------------------------------------------------------------------------------------||
output1=raises;
count no vowels in each word and print the word which has max
no of vowels if two word has max no of vowel print the first one
package Set3;
import java.util.*;
System.out.println(wordWithMaxVowelCount(s1));
int max=0;
String s2="aeiouAEIOU";
while(t.hasMoreTokens()){
String s4=t.nextToken();
int c=0;
for(int i=0;i<s4.length();i++)
for(int j=0;j<s2.length();j++)
if(s4.charAt(i)==s2.charAt(j))
c++;
if(c>max){
max=c;
s3=s4;} }
return s3;
----------------------------------------------------------------------------------------------------||
ip1: CTS-hyd-1234
ip2: hyderabad
package Set3;
import java.util.*;
String s1="CTS-hyd-1234";
String s2="hyderabad";
boolean b=formattingString(s1,s2);
if(b==true)
System.out.println("String format:CTS-LLL-XXXX");
else
boolean b=false;
String s4=t.nextToken();
String s5=t.nextToken();
String s6=t.nextToken();
for(int i=0;i<s6.length();i++){
if(Character.isDigit(s6.charAt(i)))
b=true;
else{
b=false;}}
return b;
----------------------------------------------------------------------------------------------------||
import java.util.*;
System.out.println(removeDuplicates(s1));
for(int i=0;i<s1.length();i++)
c1.add(s1.charAt(i));
for(char c2:c1)
sb.append(c2);
return sb.toString();
----------------------------------------------------------------------------------------------------||
{1:2.3,2:5.6,3:7.7,4:8.4}
get the even number from keys and find the avg of values of these keys.
package Set3;
import java.util.*;
System.out.println(avgOfEvenKeyValues(m1));
int n1=0,n3=0;
float n2=0;
Iterator<Integer> i=m1.keySet().iterator();
while(i.hasNext()){
n1=(Integer) i.next();
if(n1%2==0){
n2+=m1.get(n1);
n3++;} }
float n=Math.round((n2/n3)*100)/100f;
return n;
----------------------------------------------------------------------------------------------------||
Length of String is 7.
else Output1=-1;
package Set3;
import java.util.*;
String s1=s.next();
boolean b=colorCodeValidation(s1);
if(b==true)
else
boolean b=false,b1=false;
String s2=s1.substring(1,s1.length());
if(s1.length()==7)
if(s1.charAt(0)=='#')
b1=true;
if(b1==true)
for(int i=0;i<s2.length();i++){
char c=s2.charAt(i);
if(c!='#'){
b=true;
else{
b=false;
break;}}}
return b;
----------------------------------------------------------------------------------------------------||
input[]={1,2,1,1,3}
output1=4
input[]={1,2,3,4,1,1,5}
output1=6
package Set3;
int[]a={1,2,1,1,3};
System.out.println(maxSpan(a));
String s2 = null;
int n=0;
for(int i=0;i<a.length;i++)
sb.append(String.valueOf(a[i]));
String s1=sb.toString();
for(int i=0;i<s1.length();i++)
for(int j=i+1;j<s1.length();j++)
if(s1.charAt(i)==s1.charAt(j))
s2=String.valueOf(s1.charAt(j));
int n1=s1.indexOf(s2);
int n2=s1.lastIndexOf(s2);
for(int i=n1+1;i<n2;i++)
n++;
return (n+2);
----------------------------------------------------------------------------------------------------||
45) Getting the first and last n letters from a word where wordlength > 2n.
output: calnia.
package Set3;
public class ClassSeT46 {
String s1="california";
int n1=3;
System.out.println(subStringOfgivenString(s1,n1));
sb.append(s1.substring(0, n1)).append(s1.substring(s1.length()-n1,s1.length()));
return sb.toString();
----------------------------------------------------------------------------------------------------||
46) input1="aBrd";
input2="aqrbA";
input3=2;
output1=boolean true;
2nd char of ip1 and last 2nd char of ip2 show be equal
package Set3;
String ip1="aBrd";
String ip2="aqrbA";
int ip3=2;
System.out.println(charCheck(ip1,ip2,ip3));
boolean b=false;
String s1=String.valueOf(ip1.charAt(ip3-1));
String s2=String.valueOf(ip2.charAt(ip2.length()-ip3));
if(s1.equalsIgnoreCase(s2))
b=true;
return b;
----------------------------------------------------------------------------------------------------||
output:9+9+9+9=3+6=9;
package Set3;
int n=9999;
System.out.println(conversiontoaSingleDigit(n));
loop:
while(n>10){
int l=0,m=0;
while(n!=0){
m=n%10;
l=l+m;
n=n/10; }
n=l;
continue loop; }
return n;
----------------------------------------------------------------------------------------------------||
package Set3;
import java.util.*;
public class ClassSeT48 {
String s="2013";
System.out.println(leapYear(s));
int n=Integer.parseInt(s);
boolean b=c.isLeapYear(n);
return b;
----------------------------------------------------------------------------------------------------||
package Set3;
int n=28;
System.out.println(perfectNumber(n));
int n1=0;
boolean b=false;
for(int i=1;i<n;i++)
if(n%i==0)
n1+=i;
//System.out.println(n1);
if(n1==n)
b=true;
return b;
}
}
----------------------------------------------------------------------------------------------------||
String[] input2={“speaker”,”mouse”};
Float output=600.80(500.6+100.2);
package Set3;
import java.util.*;
m1.put("mouse", "100.2");
m1.put("speaker","500.6");
m1.put("monitor", "2000.23");
String[] s={"speaker","mouse"};
System.out.println(getTheTotalCostOfPheripherals(m1,s));
String[] s) {
Float f=(float) 0;
Iterator<String> i=m1.keySet().iterator();
while(i.hasNext()){
Float f1=Float.parseFloat(m1.get(s1));
for(int j=0;j<s.length;j++)
if(s[j].equals(s1))
f+=f1; }
return f;
----------------------------------------------------------------------------------------------------||
Input1=20.0; output=2:1;
package Set3;
import java.util.*;
double d=845.69;
System.out.println(noOfDigits(d));
int n1=0,n2=0;
String s=String.valueOf(d);
String s1=t.nextToken();
String s2=t.nextToken();
n1=s1.length();
n2=s2.length();
if(s1.charAt(0)=='0')
n1=s1.length()-1;
if(n2!=1)
if(s2.charAt(s2.length()-1)=='0')
n2=s2.length()-1;
String s3=String.valueOf(n1)+":"+String.valueOf(n2);
return s3;
1. A number is given as input. Find the odd digits in the number, add them and find if the sum is odd or not.if even
return -1, if odd return 1
input:52315
logic:5+3+1+5=14(even)
output:-1
input:1112
logic:1+1+1=3(odd)
output:1
package Set1;
int n1,n2=0,n3;
while(n!=0)
n1=n%10;
if((n1%2)!=0)
n2+=n1;
n/=10;
if(n2%2==0)
n3=-1;
else
n3=1;
return n3;
int n=12346;
System.out.println(SumOfOddsAndEvens(n));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
2.Find the day(Friday) of a date input given as MM-dd-yyyy (format)
input:12-27-2012
output:Thursday
package Set1;
import java.util.*;
import java.text.*;
String s1;
s1=sdf.format(d1);
return s1;
System.out.println("day is:"+getDay(d1));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
3.A integer array is given as input. find the difference between each element. Return the index of the largest element
which has the largest difference gap.
input: {2,3,4,2,3}
logic: 2-3=1,3-4=1,4-2=2,2-3=1
output:2
package Set1;
int n2,n3=0,n4=0,i;
for(i=0;i<n1.length-1;i++){
n2=Math.abs(n1[i]-n1[i+1]);
if(n2>n3){
n3=n2;
n4=i+1; }}
return n4;
int[] n1={2,9,4,7,6};
System.out.println(getDiffArray(n1));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------
4.Given two integer arrays. merge the common elements into a new array. find the sum of the elements
input1:{1,2,3,4}
input2:{3,4,5,6}
logic:{3,4}
output:7
package Set1;
import java.util.*;
int i,d=0;
for(i=0;i<a.length;i++)
l1.add(a[i]);
for(i=0;i<b.length;i++)
l2.add(b[i]);
l1.retainAll(l2);
for(i=0;i<l1.size();i++)
d+=(Integer) l1.get(i);
return d;
int[] a={1,2,3,4};
int[] b={3,4,5,6};
System.out.println(mergeArray(a,b));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------
5.Given two arrayslist. retrieve the odd position elements form first input and even position elemetns from second list.
put it into the new arraylist at the same positions from where they are retrieved from.
(consider 0th position as even position, and two lists are of same size)
input1:{12,1,32,3}
input2:{0,12,2,23}
output:{0,1,2,3}
package Set1;
public class ClassSet5 {
int i;
for(i=0;i<a.length;i++){
if(i%2==0)
c[i]=b[i];
if(i%2!=0)
c[i]=a[i]; }
return c;
int[] a={12,1,32,3};
int[] b={0,12,2,23};
int[] c=retrievePosition(a,b);
for(int d:c)
System.out.println(d);
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------
input:3
logic:1+1+2
output:4
package Set1;
import java.util.*;
public class ClassSet6 {
int a=-1,b=1,c=0,d=0;
for(int i=0;i<=n;i++){
c=a+b;
a=b; b=c;
d+=c;
return d;
int n=s.nextInt();
System.out.println(sumOfFibonacci(n));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
7. Retrieve the odd numbers till given input number. add and subtract it consecutively and return the result.
Input:9
Output:1+3-5+7-9=-3
package Set1;
import java.util.*;
for(int i=1;i<=n;i++)
if(i%2!=0)
l1.add(i);
int n1=l1.get(0);
for(int i=1;i<l1.size();i++)
if(i%2!=0)
n1=n1+l1.get(i);
else
n1=n1-l1.get(i);
return n1;
int n=s.nextInt();
System.out.println(consecutiveSumSubofOddNos(n));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
input:"23-01-2012"
output:January
package Set1;
import java.text.SimpleDateFormat;
import java.util.*;
String s=(sdf.format(d1));
return s;
System.out.println(monthDiff(d1));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------
9. Two dates are given as input in "yyyy-MM-dd" format. Find the number of months between the two dates
input1:"2012-12-01"
input2:"2012-01-03"
output:11
package Set1;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
Calendar c=Calendar.getInstance();
Date d1=sdf.parse(s1);
Date d2=sdf.parse(s2);
c.setTime(d1);
int m1=c.get(Calendar.MONTH);
int y1=c.get(Calendar.YEAR);
c.setTime(d2);
int m2=c.get(Calendar.MONTH);
int y2=c.get(Calendar.YEAR);
int n=(y1-y2)*12+(m1-m2);
return n;
System.out.println(monthDiff(s1,s2));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
10. arraylist of string type which has name#mark1#mark2#mark3 format. retrieve the name of the student who has
scored max marks(total of three)
input:{"arun#12#12#12","deepak#13#12#12"}
output:deepak
package Set1;
import java.util.*;
for(int i=0;i<s1.length;i++){
String s2=s1[i];
String s3=t.nextToken();
int n1=Integer.parseInt(t.nextToken());
int n2=Integer.parseInt(t.nextToken());
int n3=Integer.parseInt(t.nextToken());
int n=n1+n2+n3;
m1.put(s3, n);
}
//System.out.println(m1);
int max=0;
Iterator<String> i=m1.keySet().iterator();
while(i.hasNext()){
String s4=i.next();
int j=m1.get(s4);
if(j>max){
max=j;
m=s4; }
return m;
String[] s1={"arun#12#12#12","deepak#13#12#12","puppy#12#11#12"};
System.out.println(retrieveMaxScoredStudent(s1));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------
11.Two inputs of a string array and a string is received. The array shld be sorted in descending order. The index of
second input in a array shld be retrieved.
input1:{"ga","yb","awe"}
input2:awe
output:2
package Set1;
import java.util.*;
String[] s1={"good","yMe","awe"};
String s2="awe";
System.out.println(stringRetrieval(s1,s2));
for(int i=0;i<s1.length;i++)
l1.add(s1[i]);
Collections.sort(l1,Collections.reverseOrder()) ;
System.out.println(l1);
int n=l1.indexOf(s2);
return n;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
12.A time input is received as stirng. Find if the hour format is in 12 hour format. the suffix am/pm is case insensitive.
input:"09:36 am"
output:true
package Set1;
import java.text.*;
import java.util.*;
boolean b=false;
String s1=st.nextToken();
String s2=st.nextToken();
int n1=Integer.parseInt(st1.nextToken());
int n2=Integer.parseInt(st1.nextToken());
if((s2.equalsIgnoreCase("am"))|| (s2.equalsIgnoreCase("pm")))
if((n1<=12)&&(n2<=59))
b=true;
return b;
boolean b=hourFormat(s);
if(b==true)
else
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------
13.Retrieve the palindorme-true number set from given number limit and return the sum
input1:90 input2:120
logic:99+101+111
output:311
package Set1;
import java.util.*;
for(int i=n1;i<=n2;i++){
int r=0,n3=i;
while(n3!=0){
r=(r*10)+(n3%10);
n3=n3/10; }
if(r==i)
l1.add(i); }
System.out.println(l1);
int s=0;
for(int i=0;i<l1.size();i++)
s+=l1.get(i);
return s;
int n1=s.nextInt();
int n2=s.nextInt();
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------
14.find the max length-word in a given string and return the max-length word. if two words are of same length return
the first occuring word of max-length
output:hello(length-5)
package Set1;
import java.util.*;
int max=0;
String s2=null;
StringTokenizer t=new StringTokenizer(s1," ");
while(t.hasMoreTokens()){
s1=t.nextToken();
int n=s1.length();
if(n>max){
max=n;
s2=s1; }
return s2;
String s1=s.nextLine();
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------
input:computer
output:r-e-t-u-p-m-o-c
package Set1;
import java.util.Scanner;
sb.reverse();
if(i%2!=0)
sb1=sb.insert(i, '-');
return sb1.toString();
String s1=s.next();
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------
16. HashMap with regnum as key and mark as value. find the avg of marks whose key is odd.
input:{12:90,35:90,33:90,56:88}
package Set1;
import java.util.*;
int n=0,c=0;
Iterator<Integer> i=m1.keySet().iterator();
while(i.hasNext()){
Integer b=i.next();
if(b%2!=0){
c++;
n+=m1.get(b);} }
return (n/c);
}
public static void main(String[] args) {
m1.put(367, 89);
m1.put(368, 98);
m1.put(369, 92);
m1.put(366, 74);
m1.put(365, 67);
System.out.println(averageOfMarks(m1));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------
17. A integer input is accepted. find the square of individual digits and find their sum.
input:125
output:1*1+2*2+5*5
package Set1;
import java.util.*;
int n=0,c=0;
Iterator<Integer> i=m1.keySet().iterator();
while(i.hasNext()){
Integer b=i.next();
if(b%2!=0){
c++;
n+=m1.get(b);} }
return (n/c);
m1.put(367, 89);
m1.put(368, 98);
m1.put(369, 92);
m1.put(366, 74);
m1.put(365, 67);
System.out.println(averageOfMarks(m1));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------
18.Two input strings are accepted. If the two strings are of same length concat them and return, if they are not of same
length, reduce the longer string to size of smaller one, and concat them
input1:"hello"
input2:"hi"
output:"lohi"
input1:"aaa"
input2:"bbb"
output:"aaabbb"
package Set1;
import java.util.*;
if(s1.length()==s2.length())
sb.append(s1).append(s2);
else if(s1.length()>s2.length()){
s1=s1.substring(s1.length()/2, s1.length());
sb.append(s1).append(s2);
}
else if(s1.length()<s2.length()){
s2=s2.substring(s2.length()/2, s2.length());
sb.append(s1).append(s2);
return sb.toString();
String s1=s.next();
String s2=s.next();
System.out.println(concatStrings(s1,s2));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
input:01/13/2012
output:false
package Set1;
import java.util.StringTokenizer;
boolean b1=false;
int n1=Integer.parseInt(t.nextToken());
int n2=Integer.parseInt(t.nextToken());
String s2=t.nextToken();
int n3=Integer.parseInt(s2);
int n4=s2.length();
if(n4==4)
if(n3%4==0)
if((n2==2)&&(n1<=29))
b1=true;
else if((n2==4)||(n2==6)||(n2==9)||(n2==11)&&(n1<=30))
b1=true;
else if((n2==1)||(n2==3)||(n2==5)||(n2==7)||(n2==8)||(n2==10)||
(n2==12)&&(n1<=31))
b1=true;
else
if((n2==2)&&(n1<=28))
b1=true;
else if((n2==4)||(n2==6)||(n2==9)||(n2==11)&&(n1<=30))
b1=true;
else if((n2==1)||(n2==3)||(n2==5)||(n2==7)||(n2==8)||(n2==10)||
(n2==12)&&(n1<=31))
b1=true;
return b1;
String s="31/5/2012";
boolean b=formattingDate(s);
if(b==true)
else
System.out.println("date is not in dd/MM/yyyy format");
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
20. Get a integer array as input. Find the average of the elements which are in the position of prime index
input:{1,2,3,4,5,6,7,8,9,10}
output:21
package Set1;
import java.util.*;
int n1=0;
for(int i=2;i<n;i++){
int k=0;
for(int j=2;j<i;j++)
if(i%j==0)
k++;
if(k==0)
n1+=a[i]; }
return n1;
int n=s.nextInt();
a[i]=s.nextInt();
System.out.println(sumOfPrimeIndices(a,n));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
input: "hello.jpeg"
output: "jpeg"
package Set1;
import java.util.*;
t.nextToken();
String s2=t.nextToken();
return s2;
String s1="hello.jpeg";
System.out.println(extensionString(s1));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
22.Get two integer arrays as input. Find if there are common elements in the arrays. find the number of common
elements.
input1: {1,2,3,4}
input2: {3,4,5,6}
output: 4(3,4,3,4)
package Set1;
int c=0;
for(int i=0;i<a.length;i++)
for(int j=0;j<b.length;j++)
if(a[i]==b[j])
c++;
return (2*c);
int a[]={1,2,3,4,5};
int b[]={3,4,5,6,7};
System.out.println(commonElements(a,b));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
23.Find if a given pattern appears in both the input strings at same postions.
input1: "hh--ww--"
input2: "rt--er--"
String st1=s1.length()<s2.length()?s1:s2;
String st2=s1.length()>s2.length()?s1:s2;
boolean b=true;
String s=st2.substring(st1.length());
if(s.contains("-"))
b=false;
else{
loop:
for(int i=0;i<st1.length();i++)
if((st1.charAt(i)=='-') || (st2.charAt(i)=='-'))
if(st1.charAt(i)!=st2.charAt(i)){
b=false;
break loop; }
return b;
String s1="he--ll--";
String s2="we--ll--";
boolean b=stringPattern(s1,s2);
if(b==true)
System.out.println("same pattern");
else
System.out.println("different pattern");
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
24. Input a int array. Square the elements in even position and cube the elements in odd position and add them as
result.
input: {1,2,3,4}
output: 1^3+2^2+3^3+4^2
package Set1;
int n1=0,n2=0;
for(int i=0;i<a.length;i++)
if(i%2==0)
n1+=(a[i]*a[i]*a[i]);
else
n2+=(a[i]*a[i]);
return (n1+n2);
int a[]={1,2,3,4,5,6};
System.out.println(squaringAndCubingOfElements(a));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
25. Check whether a given string is palindrome also check whether it has atleast 2 different vowels
input: "madam"
package Set1;
boolean b=true;
int c=0;
String s1="aeiou";
String s2=sb.reverse().toString();
if(!s2.equals(s))
b=false;
else{
loop:
for(int i=0;i<s1.length();i++)
for(int j=0;j<s.length();j++)
if(s1.charAt(i)==s.charAt(j)){
c++;
continue loop; }
if(c<2)
b=false;
return b;
String s="deed";
System.out.println(palindromeAndVowelCheck(s));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
input: "hello"
output: 3
package Set1;
for(int i=0;i<sb.length();i++){
int n=0;
for(int j=i+1;j<sb.length();j++)
if(sb.charAt(i)==sb.charAt(j)){
sb.deleteCharAt(j);
n++; }
if(n>0){
sb.deleteCharAt(i);
i--;} }
return sb.length();
String s1="preethi";
System.out.println(noOfnonRepeatedCharacters(s1));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------
27. Get a input string. Find if it is a negative number, if true return the absolute value, in other cases return -1.
input: "-123"
output: 123
input: "@123"
output: -1
package Set1;
import java.util.*;
int n1=0;
if(s1.startsWith("-")){
int n=Integer.parseInt(s1);
if(n<0)
n1=Math.abs(n);}
else
n1=-1;
return n1;
String s1=s.next();
System.out.println(negativeString(s1));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------
28.An arraylist of Strings is given as input. The count of the String elements that are not of size input2 string is to be
returned.
input1: {"aaa","bb","cccc","d"}
input2: "bb"
output: 3("bb"-length:2)
package Set1;
import java.util.*;
public class ClassSet28 {
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;
int n=s.nextInt();
for(int i=0;i<n;i++)
l1.add(s.next());
String s1=s.next();
System.out.println(StringsNotOfGivenLength(l1,s1));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
29.An array of integers is given.The given element is removed new array is returned.
input1:{10,10,20,30,76}
import java.util.*;
for(int i=0;i<a.length;i++)
if(a[i]!=c)
l1.add(a[i]);
for(int i=0;i<b.length;i++)
b[i]=l1.get(i);
return b;
int a[]={10,10,20,30,40,50};
int c=10;
int[] b=removalOfGivenElementFromArray(a,c);
for(int d:b)
System.out.println(d);
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
package Set1;
import java.text.*;
import java.util.*;
Date d=sd.parse(s1);
Calendar c=Calendar.getInstance();
c.setTime(d);
long d1=c.getTimeInMillis();
d=sd.parse(s2);
c.setTime(d);
long d2=c.getTimeInMillis();
return n;
String s1="27/12/2009";
String s2="15/09/2012";
System.out.println(dateDifference(s1,s2));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
31.Enter yout name and return a string "print the title first and then comma and then first letter of initial name.
package Set1;
import java.util.*;
String s2=t.nextToken();
String s3=t.nextToken();
sb.append(',').append(s3.charAt(0));
return sb.toString();
System.out.println(retrieveName(s1));
}
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
32.Write a Program that accepts a string and removes the duplicate characters.
package Set1;
for(int i=0;i<s1.length();i++)
for(int j=i+1;j<s1.length();j++)
if(s1.charAt(i)==s1.charAt(j))
sb.deleteCharAt(j);
return sb.toString();
String s1="bhavane";
System.out.println(removalOfDuplicateCharacters(s1));
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
33.validate a password
v) should start with an upper case and end with lower case
package Set1;
import java.util.*;
String st=s.next();
boolean b=validatingPassword(st);
if(b==true)
System.out.println("valid password");
else
System.out.println("Invalid Password");
boolean b1=false,b2=false;
if(Character.isUpperCase(st.charAt(0)))
if(Character.isLowerCase(st.charAt(st.length()-1)))
{ char c = st.charAt(i);
if(Character.isDigit(c)){
b1=true; break; } }
int x=0,y=0;
if(Character.isUpperCase(st.charAt(i)))
x++;
else if(Character.isLowerCase(st.charAt(i)))
y++;
if(b1==true)
if(x>y)
{ char c = st.charAt(i);
if(c=='#' || c=='@' || c=='$'){
b2=true; break; } }
return b2;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------
34. find the average of the maximum and minimum number in an integer array
package Set1;
import java.util.*;
int[] a={10,54,23,14,32,45};
System.out.println(avgOfMaxandMinNoinArray(a));
Arrays.sort(a);
int b=a[0];
int c=a[a.length-1];
return (b+c)/2;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
import java.util.*;
String ipAddress="010.230.110.160";
boolean b=validateIpAddress(ipAddress);
if(b==true)
System.out.println("valid ipAddress");
else
boolean b1=false;
int a=Integer.parseInt(t.nextToken());
int b=Integer.parseInt(t.nextToken());
int c=Integer.parseInt(t.nextToken());
int d=Integer.parseInt(t.nextToken());
b1=true;
return b1;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
36. find the three consecutive characters in a string. if the string consists any three
String s1="aaaaxyzAAA";
boolean b=consecutiveCharactersCheck(s1);
if(b==true)
else
boolean b=false;
int c=0;
for(int i=0;i<s1.length()-1;i++)
if((s1.charAt(i+1)-s1.charAt(i))==1)
c++;
if(c>=2)
b=true;
return b;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
37.String encrption. replace the odd-index character with next character(if it is 'z' replace with 'a'..if 'a' with 'b' as such),
String s="preethi";
System.out.println(oddEncryptionOfString(s));
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(c%2!=0){
c=(char)(c+1);
sb.append(c); }
else
sb.append(c); }
return sb.toString();
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
package Set1;
import java.util.*;
int[] a={10,23,45,54,32,14,55,65,56};
System.out.println(retrieveMaxFromOddIndex(a));
for(int i=0;i<a.length;i++)
if(i%2!=0)
l.add(a[i]);
int b=0;
for(int i=0;i<l.size();i++){
if(c>b)
b=c; }
return b;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
DISPLAY AS 55-56-661-234?
package Set1;
import java.util.StringTokenizer;
String s="555-666-1234";
System.out.println(display(s));
String s1=t.nextToken();
String s2=t.nextToken();
String s3=t.nextToken();
sb.append(s1.substring(0, s1.length()-1)).append('-');
sb.append(s1.charAt(s1.length()-1)).append(s2.charAt(0)).append('-');
sb.append(s2.substring(1, s2.length())).append(s3.charAt(0)).append('-');
sb.append(s3.substring(1, s3.length()));
return sb.toString();
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
40.input1="Rajasthan";
input2=2;
input3=5;
output=hts;
package Set1;
String input1="Rajasthan";
System.out.println(retrieveString(input1,input2,input3));
sb.reverse();
return output;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
41.input1={1,2,3}
input2={3,4,5}
input3;+(union)
output:inp1+inp2
input1:{1,2,3,4,5}
input 2:{2,3,4,5}
input3=*(intersection)
output:inp1*inp2
INPUT1:{1,2,3,4,5}
INPUT2:{3,6,7,8,9}
INPUT3:-(MINUS)
output:inp1-inp2
package Set1;
import java.util.*;
int[] a={1,2,3,4,5};
int[] b={0,2,4,6,8};
int c=s.nextInt();
int d[]=arrayFunctions(a,b,c);
for(int e:d)
System.out.println(e);
for(int i=0;i<a.length;i++)
l1.add(a[i]);
for(int i=0;i<b.length;i++)
l2.add(b[i]);
switch(c){
case 1:
l1.removeAll(l2);
l1.addAll(l2);
Collections.sort(l1);
l3=l1;
break;
case 2:
l1.retainAll(l2);
Collections.sort(l1);
l3=l1;
break;
case 3:
if(l1.size()==l2.size())
for(int i=0;i<l1.size();i++)
l3.add(Math.abs(l2.get(i)-l1.get(i)));
break;
for(int i=0;i<d.length;i++)
d[i]=l3.get(i);
return d;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
42. input1=commitment;
output=cmmitmnt;
package Set1;
String s1="cOmmitment";
System.out.println(removeEvenElements(s1));
for(int i=0;i<s1.length();i++)
if((i%2)==0)
sb1.append(s1.charAt(i));
else if((i%2)!=0)
sb1.append(s1.charAt(i));
return sb1.toString();
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
43. Retrieve the odd-position digits from input integer array. Multiply them with their index and return their sum.
package Set1;
int[] a={5,1,6,2,9,4,3,7,8};
System.out.println(retrievalOfOddPositionElements(a));
int s=0;
for(int i=0;i<a.length;i++)
if(i%2!=0)
s+=a[i]*i;
return s;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
44. Return the number of days in a month, where month and year are given as input.
package Set1;
import java.util.*;
String s1="02/2011";
System.out.println(noOfDaysInAmonth(s1));
int n=0;
int n1=Integer.parseInt(r.nextToken());
int n2=Integer.parseInt(r.nextToken());
n=31;
else if(n1==4 || n1==6 || n1==9 || n1==11)
n=30;
else if(n1==2){
if(n2%4==0)
n=29;
else
n=28; }
return n;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------
45. Retrieve the non-prime numbers within the range of a given input. Add-up the non-prime numbers and return the
result.
package Set1;
import java.util.*;
int i=20,j=40;
int k=0;
for(int a=i;a<=j;a++){
int c=0;
for(int b=2;b<a;b++)
if(a%b==0)
c++;
if(c==0)
l1.add(a); }
for(int e=i;e<=j;e++)
l2.add(e);
l2.removeAll(l1);
for(int d=0;d<l2.size();d++)
k+=l2.get(d);
return k;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------
46. Retrieve the elements in a array, which is an input, which are greater than a specific input number. Add them and
find the reverse of the sum.
package Set1;
int[] a={23,35,11,66,14,32,65,56,55,99};
int b=37;
System.out.println(additionOfRetrievedElements(a,b));
int n=0;
for(int i=0;i<a.length;i++)
if(a[i]>b)
n+=a[i];
return n;
---------------------------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------
47.Input a hashmap. Count the keys which are not divisible by 4 and return.
package Set1;
import java.util.*;
m1.put(24, "preethi");
m1.put(32, "bhanu");
m1.put(25, "menu");
m1.put(31, "priya");
System.out.println(fetchingKeysDivisibleByFour(m1));
int k=0;
Iterator<Integer> i=m1.keySet().iterator();
loop:
while(i.hasNext()){
int j=i.next();
if(j%4!=0)
k++;
continue loop; }
return k;
input 2:"NWYR"
output:N+w+Y+r+
package Set2;
String s2="NWYR";
System.out.println(StringFormatting(s1,s2));
String s3=s1.toUpperCase();
for(int i=0;i<s2.length();i++)
for(int j=0;j<s3.length();j++)
if(s2.charAt(i)==s3.charAt(j))
s4.append(s1.charAt(j)).append('+');
return s4.toString();
----------------------------------------------------------------------------------------------------------||
2) input:
Searchstring s1="GeniusRajkumarDev";
String s2="Raj";
String s3="Dev";
output:
String srch="MaanVeerSinghKhurana";
String s1="Veer";
String s2="Singh";
int n=searchString(srch,s1,s2);
if(n==1)
else
int n=0;
int n1=srch.indexOf(s1);
int n2=srch.indexOf(s2);
if(n1<n2)
n=1;
else
n=2;
return n;
----------------------------------------------------------------------------------------------------------||
package Set2;
import java.text.*;
import java.util.*;
String s1="30/05/2013";
String s2="01/06/2013";
System.out.println(monthsBetweenDates(s1,s2));
Date d1=sdf.parse(s1);
Date d2=sdf.parse(s2);
Calendar cal=Calendar.getInstance();
cal.setTime(d1);
int months1=cal.get(Calendar.MONTH);
int year1=cal.get(Calendar.YEAR);
cal.setTime(d2);
int months2=cal.get(Calendar.MONTH);
int year2=cal.get(Calendar.YEAR);
int n=((year2-year1)*12)+(months2-months1);
return n;
---------------------------------------------------------------------------------------------------------||
4) intput="xyzwabcd"
intput2=2;
input3=4;
output=bawz
package Set2;
String s1="xyzwabcd";
int n1=2,n2=4;
System.out.println(retrievalOfString(s1,n1,n2));
sb.reverse();
return s2;
--------------------------------------------------------------------------------------------------------||
Remove the duplicate elements and print sum of even numbers in the array..
package Set2;
import java.util.*;
System.out.println(sumOfEvenNos(a));
for(int i=0;i<a.length;i++)
l1.add(a[i]);
for(int i=0;i<a.length;i++)
for(int j=i+1;j<a.length;j++)
if(a[i]==a[j])
l2.add(a[j]);
l1.removeAll(l2);
l1.addAll(l2);
int n=0,n1;
for(int i=0;i<l1.size();i++)
if(l1.get(i)%2==0)
n+=l1.get(i);
if(n==0)
n1=-1;
else
n1=n;
return n1;
-------------------------------------------------------------------------------------------------------||
6) input1="abc2012345"
input2="abc2112660"
input 3=4
12345 refers to last month eb reading and 12660 refers to this month eb reading
package Set2;
String input1="abc2012345";
String input2="abc2112660";
int input3=4;
System.out.println(meterReading(input1,input2,input3));
int n=Math.abs((n2-n1)*input3);
return n;
-------------------------------------------------------------------------------------------------------||
7)Given array of intergers,print the sum of elements sqaring/cubing as per the power of their indices.
//answer= sum=sum+a[i]^i;
eg:input:{2,3,5}
Output:29
package Set2;
int a[]={2,3,5};
System.out.println(sumOfElementsWrtIndices(a));
int s=0;
for(int i=0;i<a.length;i++)
s+=(Math.pow(a[i], i));
return s;
--------------------------------------------------------------------------------------------------------||
8)Given array of string check whether all the elements contains only digits not any alaphabets.
Input:{"123","23.14","522"}
output:1
Input1:{"asd","123","42.20"}
output:-1
package Set2;
String[] input1={"123","23.14","522"};
//String[] input1={"asd","123","42.20"};
System.out.println(stringOfDigits(input1));
}
int n=0;
for(int i=0;i<input1.length;i++){
String s1=input1[i];
for(int j=0;j<s1.length();j++){
char c1=s1.charAt(j);
if(Character.isDigit(c1))
n=1;
else {n=-1;break;} }}
return n;
--------------------------------------------------------------------------------------------------------||
9) int[] a={12,14,2,26,35}
output:35-2=33.
package Set2;
import java.util.Arrays;
int a[]={12,14,2,26,35};
System.out.println(diffBwMaxAndMin(a));
Arrays.sort(a);
int n=a[a.length-1]-a[0];
return n;
---------------------------------------------------------------------------------------------------------||
10) Given an array find the largest 'span'(span is the number of elements between two same digits)
a[]={1,4,2,1,4,1,5}
Largest span=5
package Set2;
int a[]={1,4,2,1,4,1,5};
int max=0;
int p1=0;
int p2=0;
int n=0;
int sum=0;
for(int i=0;i<a.length-1;i++){
for(int j=i+1;j<a.length;j++)
if(a[i]==a[j])
n=j;
if(n-i>max){
max=n-i;
p1=i;
p2=n; }
System.out.println("largest span:"+(p2-p1));
for(int i=p1;i<=p2;i++)
sum=sum+a[i];
return (sum);
----------------------------------------------------------------------------------------------------------||
11) input={"1","2","3","4"}
output=10
input={"a","b"}
output=-1;
package Set2;
String s[]={"1","2","3","4"};
//String s[]={"a","b","3","4"};
System.out.println(checkForStringElements(s));
int n=0;
boolean b=false;
for(int i=0;i<s.length;i++){
String s1=s[i];
for(int j=0;j<s1.length();j++){
char c=s1.charAt(j);
if(Character.isDigit(c))
b=true;
else{
b=false;
break;} }
if(b==true)
n+=Integer.parseInt(s1);
else{
n=-1;
break;} }
return n;
-----------------------------------------------------------------------------------------------------------||
arraylist2={ 6,7,8,9,10}
output={6,2,8,4,10}
package Set2;
int a[]={1,2,3,4,5};
int b[]={6,7,8,9,10};
int c[]=alternativeIndicesElements(a,b);
for(int d:c)
System.out.println(d);
}
if(a.length==b.length)
for(int i=0;i<a.length;i++)
if(i%2==0)
c[i]=b[i];
else
c[i]=a[i];
return c;
-------------------------------------------------------------------------------------------------------------||
13) count the number of times the second word in second string occurs in first string-case sensitive
input2=what hai
output=3;
package Set2;
import java.util.StringTokenizer;
System.out.println(stringOccurance(input1,input2));
}
public static int stringOccurance(String input1, String input2){
int count=0;
String s1=t1.nextToken();
String s2=t1.nextToken();
while(t2.hasMoreTokens()){
if(t2.nextToken().equals(s2))
count++; }
return count;
------------------------------------------------------------------------------------------------------------||
input1:"aaabbccc"
ouput1=2;
package Set2;
String input1="aaabbccc";
System.out.println(consecutiveRepeatitionOfChar(input1));
int c=0;
int n=0;
for(int i=0;i<input1.length()-1;i++){
if(input1.charAt(i)==input1.charAt(i+1))
n++;
else
n=0;
if(n==2)
c++; }
return c;
-----------------------------------------------------------------------------------------------------------||
package Set2;
import java.text.SimpleDateFormat;
import java.util.*;
System.out.println(sameDayOnUpcomingYear(d));
d1.setYear(d.getYear()+1);
String s=sdf.format(d1);
return s;
}
----------------------------------------------------------------------------------------------------------||
16)Get all the numbers alone from the string and return the sum.
Input"123gif"
Output:6
package Set2;
String s="1234gif";
System.out.println(summationOfNosInaString(s));
int n=0;
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(Character.isDigit(c)){
String s1=String.valueOf(c);
n+=Integer.parseInt(s1);} }
return n;
---------------------------------------------------------------------------------------------------------||
17)input array={red,green,blue,ivory}
import java.util.*;
String[] s={"red","green","blue","ivory","yellow"};
int n=1;
System.out.println(retrievingRequiredColor(s,n));
for(int i=0;i<s.length;i++)
l.add(s[i]);
Collections.sort(l,Collections.reverseOrder());
for(int i=0;i<l.size();i++)
if(i==(n-1))
s1=l.get(i);
return s1;
--------------------------------------------------------------------------------------------------------||
import java.util.StringTokenizer;
System.out.println(capsStart(s1));
while(t.hasMoreTokens()){
String s2=t.nextToken();
String s3=s2.substring(0,1);
s5.append(s3.toUpperCase()).append(s4).append(" "); }
return s5.toString();
--------------------------------------------------------------------------------------------------------||
Output =3
Output =4
package Set2;
import java.util.StringTokenizer;
public class ClassSET19 {
System.out.println(countVowelsInMaxLengthString(s1));
String s4="AEIOUaeiou";
while(t.hasMoreTokens()){
String s2=t.nextToken();
int n2=s2.length();
if(n2>max){
max=n2;
s3=s2;} }
for(int i=0;i<s3.length();i++)
for(int j=0;j<s4.length();j++)
if(s3.charAt(i)==s4.charAt(j))
n1++;
return n1;
--------------------------------------------------------------------------------------------------------||
20) for the given string display the middle 2 value, case satisfies only if string is of even length
ip - java
op - av
package Set2;
String s1="sumithra";
System.out.println(printingSubstringOfMiddleChars(s1));
return s2;
--------------------------------------------------------------------------------------------------------||
21) Given an array int a[]. Add the sum at even indexes.do the same with odd indexes.
package Set2;
int a[]={9,8,5,3,2,6,4,7,5,1};
System.out.println(oddEvenIndicesCount(a));
int n1=0,n2=0,n3=0;
for(int i=0;i<a.length;i++)
if(i%2==0)
n1+=a[i];
else
n2+=a[i];
if(n1==n2)
n3=1;
else
n3=-1;
return n3;
-------------------------------------------------------------------------------------------------------||
package Set2;
import java.util.*;
System.out.println(noOfDaysInaMonth(ca));
int n=ca.getActualMaximum(Calendar.DAY_OF_MONTH);
return n;
1) Find the sum of the numbers in the given input string array
Input{“2AA”,”12”,”ABC”,”c1a”)
Output:6 (2+1+2+1)
String[] s1={"2AA","12","A2C","C5a"};
getSum(s1); }
int sum=0;
for(int i=0;i<s1.length;i++)
for(int j=0;j<s1[i].length();j++){
char c=s1[i].charAt(j);
if(Character.isDigit(c)){
String t=String.valueOf(c);
int n=Integer.parseInt(t);
sum=sum+n; } }
System.out.println(sum); }
----------------------------------------------------------------------------------------------------||
2) Create a program to get the hashmap from the given input string array where the key for the hashmap
is first three letters of array element in uppercase and the value of hashmap is the element itself
Output:{{GOA,goa},{KER,kerala},{GUJ,Gujarat}} [hashmap]
package Set3;
import java.util.*;
String[] s1={"goa","kerala","gujarat"};
putvalues(s1);
for(String s:s1)
l1.add(s.toUpperCase().substring(0, 3));
for(String s:s1)
l2.add(s);
for(int i=0;i<l1.size();i++)
m1.put(l1.get(i),l2.get(i));
System.out.println(m1);
----------------------------------------------------------------------------------------------------||
3) String[] input1=["Vikas","Lokesh",Ashok]
package Set3;
String[] ip={"Vikas","Lokesh","Ashok"};
System.out.println(getTheNamesinGivenFormat(ip));
for(int i=0;i<ip.length;i++)
sb.append(ip[i]).append(',');
sb.deleteCharAt(sb.length()-1);
return sb.toString();
----------------------------------------------------------------------------------------------------||
4) Email Validation
String input1="[email protected]"
1)@ & . should be present;
package Set3;
import java.util.*;
String ip="[email protected]";
boolean b=emailIdValidation(ip);
if(b==true)
else
int i=0;
boolean b=false;
String s1=t.nextToken();
String s2=t.nextToken();
String s3=t1.nextToken();
String s4=t1.nextToken();
i++;
if(i==1)
if(s3.length()==5)
if(s1.length()>=3)
if(s4.equals("com"))
b=true;
return b;
----------------------------------------------------------------------------------------------------||
((x1+x2)*(x1+x2))+((y1+y2)*(y1+y2))
package Set3;
int x1=4,x2=8;
int y1=3,y2=5;
sqrt(x1,x2,y1,y2);
public static void sqrt(int x1, int x2, int y1, int y2) {
int op;
op=(int) (Math.sqrt((x1+x2)*(x1+x2))+((y1+y2)*(y1+y2)));
System.out.println(op);
----------------------------------------------------------------------------------------------------||
i/p 2="hari";
o/p string[]={"ram","cts"};
package Set3;
import java.util.*;
import java.util.Map.Entry;
m1.put("ram","hari");
m1.put("cisco","barfi");
m1.put("honeywell","cs");
m1.put("cts","hari");
String s2="hari";
getvalues(m1,s2);
ArrayList<String>l1=new ArrayList<String>();
m.getKey();
m.getValue();
if(m.getValue().equals(s2))
l1.add(m.getKey()); }
for(int i=0;i<l1.size();i++){
op[i]=l1.get(i) ;
System.out.println(op[i]); }
----------------------------------------------------------------------------------------------------||
7) Input1={“ABX”,”ac”,”acd”};
Input2=3;
Output1=X$d
package Set3;
import java.util.*;
String[] s1={"abc","da","ram","cat"};
int ip=3;
getStr(s1,ip);
for(String s:s1)
if(s.length()==ip)
l1.add(s);
for(String l:l1){
s2=l.substring(l.length()-1);
buff.append(s2).append("$"); }
op=buff.deleteCharAt(buff.length()-1).toString();
System.out.println(op);
----------------------------------------------------------------------------------------------------||
8) INPUT1= helloworld
if occurs more than twice,leave the first occurence and delete the duplicate
O/P= helwrd;
package Set3;
String input1="HelloWorld";
int input2=2;
System.out.println(deletingtheCharOccuringTwice(input1,input2));
int c=1;
for(int i=0;i<sb.length();i++){
c=1;
for(int j=i+1;j<sb.length();j++)
if(sb.charAt(i)==sb.charAt(j))
c++;
if(c>=input2){
for(int j=i+1;j<sb.length();j++)
if(sb.charAt(i)==sb.charAt(j))
sb.deleteCharAt(j);
sb.deleteCharAt(i);
i--; } }
return sb.toString();
----------------------------------------------------------------------------------------------------||
operation-- for how many strings input2 matches the prefix of each string in input1
String[] input={"01","01010","1000","10","011"}
output=3; count the strings having prefix"10","01" but "10","01" not included
package Set3;
import java.util.*;
String[] ip={"100","111","10100","10","1111"};
gteCount(ip);
for(String s:ip)
l1.add(s);
op=l1.size();
System.out.println(op);
----------------------------------------------------------------------------------------------------||
if value equal to 13,escape the value '13', as well as the next value to 13.
package Set3;
import java.util.*;
int ip1=13,ip2=2,ip3=8;
System.out.println(thirteenLapse(ip1,ip2,ip3));
l.add(ip1);
l.add(ip2);
l.add(ip3);
int s=0;
for(int i=0;i<l.size();i++){
if(l.get(i)!=13)
s+=l.get(i);
if(l.get(i)==13)
i=i+1;}
return s;
----------------------------------------------------------------------------------------------------||
11) input="hello"
package Set3;
String s="Hello";
System.out.println(alternatingChar(s));
for(int i=0;i<s.length();i++)
if(i%2==0)
sb.append(s.charAt(i));
return sb.toString();
----------------------------------------------------------------------------------------------------||
package Set3;
System.out.println(reArrangingWord(s));
}
public static String reArrangingWord(String s) {
sb.append(s.substring(s.length()-1));
sb.append(s.substring(1, s.length()-1));
sb.append(s.substring(0, 1));
return sb.toString();
----------------------------------------------------------------------------------------------------||
package Set3;
import java.util.*;
l1.add(1);
l1.add(2);
l1.add(3);
l1.add(4);
l2.add(1);
l2.add(2);
l2.add(3);
l2.add(5);
int o[]=commonSet(l1,l2);
for(int i:o)
System.out.println(i);
}
public static int[] commonSet(List<Integer> l1, List<Integer> l2) {
l3.addAll(l1);l4.addAll(l2);
l1.removeAll(l2);l4.removeAll(l3);
l1.addAll(l4);
for(int j=0;j<o.length;j++)
o[j]=l1.get(j);
return o;
----------------------------------------------------------------------------------------------------||
14) String array will be given.if a string is Prefix of an any other string in that array means count.
package Set3;
String[] a={"pinky","preethi","puppy","preeth","puppypreethi"};
System.out.println(namesWithPreFixes(a));
int n=0;
for(int i=0;i<a.length;i++)
for(int j=i+1;j<a.length;j++){
String s1=a[i];
String s2=a[j];
if(s2.startsWith(s1)||s1.startsWith(s2))
n++; }
return n;
}
----------------------------------------------------------------------------------------------------||
output=4;
package Set3;
import java.util.StringTokenizer;
System.out.println(noOfWordsInString(s));
return t.countTokens();
----------------------------------------------------------------------------------------------------||
output=true;
int[] input={1,2,1,3,4,5,8};
output=false
package Set3;
//int[] a={2,1,4,1,2,3,6};
int[] a={1,2,1,3,4,5,8};
System.out.println(sequenceInArray(a));
}
boolean b=false;
int n=0;
for(int i=0;i<a.length-1;i++)
if((a[i+1]-a[i])==1)
n++;
if(n==2)
b=true;
return b;
----------------------------------------------------------------------------------------------------||
char input2='/'
output1[]={"aaa","bba","ccc"};
package Set3;
import java.util.*;
String ip1="AAA/abb/CCC";
char ip2='/';
String op[]=loweringCasenReverseofaString(ip1,ip2);
for(String s:op)
System.out.println(s);
}
while(t.hasMoreTokens()){
l.add(sb.reverse().toString()); }
for(int i=0;i<op.length;i++)
op[i]=l.get(i);
return op;
----------------------------------------------------------------------------------------------------||
Input1=”so”;output1=”sososo”;
package Set3;
String ip1="cowboy";
String ip2="cow";
System.out.println(printingStringDependingOncharCount(ip1,ip2));
int n1=ip2.length();
if(n1==3)
for(int i=0;i<n1-1;i++)
sb.append(ip1.substring(0, n1));
else if(n1==2)
for(int i=0;i<n1+1;i++)
sb.append(ip1.substring(0, n1));
return sb.toString();
----------------------------------------------------------------------------------------------------||
19) input---input1=1;
input2=4;
input3=1;
output1=4;
input---input1=1;
input2=2;
input3=3;
output1=6;
package Set3;
int ip1=1,ip2=4,ip3=1;
//int ip1=1,ip2=2,ip3=3;
//int ip1=1,ip2=1,ip3=1;
System.out.println(sumOfNonRepeatedChars(ip1,ip2,ip3));
int n=0;
n=ip1+ip2+ip3;
n=0;
else{
if(ip1==ip2)
n=ip3;
else if(ip1==ip3)
n=ip2;
else if(ip2==ip3)
n=ip1; }
return n;
----------------------------------------------------------------------------------------------------||
20) input1-List1-{apple,orange,grapes}
input2-List2-{melon,apple,mango}
output={mango,orange}
package Set3;
import java.util.*;
l1.add("apple");
l1.add("orange");
l1.add("grapes");
l2.add("melon");
l2.add("apple");
l2.add("mango");
String[] s2=fruitsList(l1,l2);
for(String s3:s2)
System.out.println(s3);
for(int i=0;i<l1.size();i++){
String s1=l1.get(i);
l3.add(s1); }
for(int i=0;i<l2.size();i++){
String s1=l2.get(i);
l3.add(s1); }
Collections.sort(l3);
for(int i=0;i<s2.length;i++)
s2[i]=l3.get(i);
return s2;
----------------------------------------------------------------------------------------------------||
operation-- if the character before and after * are same return true else false
package Set3;
import java.util.*;
String input="Hello*world";
System.out.println(characterCheck(input));
}
public static boolean characterCheck(String input) {
boolean b=false;
String s1=t.nextToken();
String s2=t.nextToken();
String s3=s1.substring(s1.length()-1);
String s4=s2.substring(0,1);
if(s3.equalsIgnoreCase(s4))
b=true;
return b;
----------------------------------------------------------------------------------------------------||
output--String output1="aXafsdxx"
operation-- remove the character "x"(only lower case) from string and place at the end
package Set3;
String input="xaXafxsd";
System.out.println(removalOfx(input));
int j=0;
for(int i=0;i<sb.length();i++)
if(sb.charAt(i)=='x'){
sb.deleteCharAt(i);
j++;}
for(int i=0;i<j;i++)
sb.append('x');
return sb.toString();
----------------------------------------------------------------------------------------------------||
HashMap<String,String> h2={“abc”:”fail”,”efg”:”pass”}
package Set3;
import java.util.*;
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));
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;
----------------------------------------------------------------------------------------------------||
sTRING i/p2=5
package Set3;
import java.text.*;
import java.util.*;
String ip1="2012";
String ip2="5";
System.out.println(experienceCalc(ip1,ip2));
boolean b=false;
Date d1=sdf.parse(ip1);
int n1=d1.getYear();
int n2=d2.getYear();
int n3=Integer.parseInt(ip2);
if((n2-n1)>n3)
b=true;
return b;
}
----------------------------------------------------------------------------------------------------||
output: lolo
package Set3;
String s1="hello";
int n1=2;
System.out.println(formattingOfString(s1,n1));
for(int i=0;i<n1;i++)
sb.append(s2);
return sb.toString();
----------------------------------------------------------------------------------------------------||
input="0201103311"
ISBN number: sum=0*10 +2*9+ 0*8 +1*7+ 1*6 +0*5+ 3*4 +3*3+ 1*2 +1*1
package Set3;
String ip="0201103311";
boolean b=ISBNnumber(ip);
if(b==true)
System.out.println("check ur data");
boolean b=false;
int sum=0;
for(int i=0,j=ip.length();i<ip.length();i++,j--){
String s=String.valueOf(ip.charAt(i));
int n=Integer.parseInt(s);
sum+=(n*j); }
//System.out.println(sum);
if(sum%11==0)
b=true;
return b;
----------------------------------------------------------------------------------------------------||
package Set3;
import java.util.*;
String s1=s.next();
boolean b=passwordValidation(s1);
if(b==true)
System.out.println("valid password");
else
boolean b=false,b1=false,b2=false;
if(s1.length()>=8)
if(!Character.isDigit(s1.charAt(0)))
b1=true;
if(b1==true)
for(int i=0;i<s1.length();i++)
b2=true;
if(b2==true)
b=true;
return b;
----------------------------------------------------------------------------------------------------||
package Set3;
import java.util.*;
String pan=s.next();
boolean b=panNumberValidation(pan);
if(b==true)
else
boolean b=false,b1=false,b2=false;
if(pan.length()==8)
if(Character.isAlphabetic(pan.charAt(pan.length()-1)) &&
Character.isUpperCase(pan.charAt(pan.length()-1)))
b1=true;
if(b1==true)
for(int i=0;i<s1.length();i++)
b2=true;
else
{b2=false;break;}
if(b2==true)
for(int i=0;i<s2.length();i++)
if(Character.isDigit(s2.charAt(i)))
b=true;
else
{b=false;break;}
return b;
}
----------------------------------------------------------------------------------------------------||
ex: h1={1:4,2:6,4:7,5:9}
output=(4+9)/2
package Set3;
import java.util.*;
m1.put(1, 4);
m1.put(2, 6);
m1.put(4, 7);
m1.put(5, 9);
System.out.println(avgValuesOfOddKeys(m1));
int l=0,m=0;
Iterator<Integer> i=m1.keySet().iterator();
while(i.hasNext()){
if(n%2!=0){
m+=m1.get(n);
l++;} }
return m/l;
----------------------------------------------------------------------------------------------------||
30) Return 1 if the last & first characters of a string are equal else
Output= 1
package Set3;
System.out.println(checkForFirstAndLastChar(input));
int n=0;
if(input.charAt(0)==input.charAt(input.length()-1))
n=1;
else n=-1;
return n;
----------------------------------------------------------------------------------------------------||
largest string and then add. The number of characters removed from
input 2="helloworld";
output="worldhello";
package Set3;
String ip1="hello";
String ip2="helloworld";
System.out.println(removalOfCharFromLargestString(ip1,ip2));
int n1=ip1.length();
int n2=ip2.length();
if(n1<n2)
sb.append(ip2.substring(n1, n2)).append(ip1);
return sb.toString();
----------------------------------------------------------------------------------------------------||
o/p: Honesty
package Set3;
import java.util.*;
System.out.println(lengthiestString(s1));
int max=0;
loop:
while(t.hasMoreTokens()){
String s3=t.nextToken();
int n=s3.length();
if(n>max){
max=n;
s2=s3;}
if(n==max)
for(int i=0;i<s3.length();i++){
char c1=s2.charAt(i);
char c2=s3.charAt(i);
if(c1!=c2){
if(c2<c1)
s2=s3;
continue loop;} }
return s2;
----------------------------------------------------------------------------------------------------||
output=1.
package Set3;
String s1="education";
System.out.println(vowelsCheck(s1));
boolean b=false;
int n1=0,n2=0,n3=0,n4=0,n5=0;
for(int i=0;i<s1.length();i++){
char c=s1.charAt(i);
if(c=='a' || c=='A')
n1++;
if(c=='e' || c=='E')
n2++;
if(c=='i' || c=='I')
n3++;
if(c=='o' || c=='O')
n4++;
if(c=='u' || c=='U')
n5++;}
b=true;
return b;
----------------------------------------------------------------------------------------------------||
output: ofgrte
output : eNYwrok
package Set3;
String s1="newyork";
System.out.println(formattingGivenString(s1));
int j=0;
if(s1.length()%2==0)
j=s1.length();
else
j=s1.length()-1;
for(int i=0;i<j;i=i+2){
sb.append(sb1.reverse());}
if(s1.length()%2==0)
s3=sb.toString();
else
s3=sb.append(s1.charAt(s1.length()-1)).toString();
return s3;
----------------------------------------------------------------------------------------------------||
o/p: ceogbl
package Set3;
String s1="bengal";
System.out.println(stringFormatting(s1));
for(int i=0;i<s1.length();i++){
char c=s1.charAt(i);
if(i%2==0){
if(c==122)
c=(char) (c-25);
else{
c=(char) (c+1);}
sb.append(c);}
else
sb.append(c);}
return sb.toString();
----------------------------------------------------------------------------------------------------||
o/p=5
package Set3;
import java.util.*;
System.out.println(maxChunk(s1));
int max=0;
while(t.hasMoreTokens()){
String s2=t.nextToken();
int n=0;
for(int i=0;i<s2.length()-1;i++)
if(s2.charAt(i)==s2.charAt(i+1))
n++;
if(n>max)
max=n;
return (max+1);
----------------------------------------------------------------------------------------------------||
solution:
package Set3;
System.out.println(commonCharsinAstring(s1,s2));
int f;
for(int i=0;i<s1.length();i++){
f=0;
char c1=s1.charAt(i);
for(int j=0;j<s2.length();j++)
if(c1==s2.charAt(j))
f=1;
if(f!=0)
sb.append(c1);
else
sb.append('+');}
return sb.toString();
}
----------------------------------------------------------------------------------------------------||
38) input1={2,4,3,5,6};
finally add it
output1=208(4+16+27+125+36)
package Set3;
int a[]={2,4,3,5,6};
System.out.println(summationPattern(a));
int n1=0,n2=0;
for(int i=0;i<a.length;i++)
if(a[i]%2==0)
n1+=(a[i]*a[i]);
else
n2+=(a[i]*a[i]*a[i]);
return n1+n2;
----------------------------------------------------------------------------------------------------||
output1=raises;
count no vowels in each word and print the word which has max
no of vowels if two word has max no of vowel print the first one
package Set3;
import java.util.*;
System.out.println(wordWithMaxVowelCount(s1));
int max=0;
String s2="aeiouAEIOU";
while(t.hasMoreTokens()){
String s4=t.nextToken();
int c=0;
for(int i=0;i<s4.length();i++)
for(int j=0;j<s2.length();j++)
if(s4.charAt(i)==s2.charAt(j))
c++;
if(c>max){
max=c;
s3=s4;} }
return s3;
----------------------------------------------------------------------------------------------------||
ip1: CTS-hyd-1234
ip2: hyderabad
package Set3;
import java.util.*;
String s1="CTS-hyd-1234";
String s2="hyderabad";
boolean b=formattingString(s1,s2);
if(b==true)
System.out.println("String format:CTS-LLL-XXXX");
else
boolean b=false;
String s4=t.nextToken();
String s5=t.nextToken();
String s6=t.nextToken();
for(int i=0;i<s6.length();i++){
if(Character.isDigit(s6.charAt(i)))
b=true;
else{
b=false;}}
return b;
----------------------------------------------------------------------------------------------------||
import java.util.*;
System.out.println(removeDuplicates(s1));
for(int i=0;i<s1.length();i++)
c1.add(s1.charAt(i));
for(char c2:c1)
sb.append(c2);
return sb.toString();
----------------------------------------------------------------------------------------------------||
{1:2.3,2:5.6,3:7.7,4:8.4}
get the even number from keys and find the avg of values of these keys.
package Set3;
import java.util.*;
System.out.println(avgOfEvenKeyValues(m1));
int n1=0,n3=0;
float n2=0;
Iterator<Integer> i=m1.keySet().iterator();
while(i.hasNext()){
n1=(Integer) i.next();
if(n1%2==0){
n2+=m1.get(n1);
n3++;} }
float n=Math.round((n2/n3)*100)/100f;
return n;
----------------------------------------------------------------------------------------------------||
Length of String is 7.
else Output1=-1;
package Set3;
import java.util.*;
String s1=s.next();
boolean b=colorCodeValidation(s1);
if(b==true)
else
boolean b=false,b1=false;
String s2=s1.substring(1,s1.length());
if(s1.length()==7)
if(s1.charAt(0)=='#')
b1=true;
if(b1==true)
for(int i=0;i<s2.length();i++){
char c=s2.charAt(i);
if(c!='#'){
b=true;
else{
b=false;
break;}}}
return b;
----------------------------------------------------------------------------------------------------||
input[]={1,2,1,1,3}
output1=4
input[]={1,2,3,4,1,1,5}
output1=6
package Set3;
int[]a={1,2,1,1,3};
System.out.println(maxSpan(a));
String s2 = null;
int n=0;
for(int i=0;i<a.length;i++)
sb.append(String.valueOf(a[i]));
String s1=sb.toString();
for(int i=0;i<s1.length();i++)
for(int j=i+1;j<s1.length();j++)
if(s1.charAt(i)==s1.charAt(j))
s2=String.valueOf(s1.charAt(j));
int n1=s1.indexOf(s2);
int n2=s1.lastIndexOf(s2);
for(int i=n1+1;i<n2;i++)
n++;
return (n+2);
----------------------------------------------------------------------------------------------------||
45) Getting the first and last n letters from a word where wordlength > 2n.
output: calnia.
package Set3;
public class ClassSeT46 {
String s1="california";
int n1=3;
System.out.println(subStringOfgivenString(s1,n1));
sb.append(s1.substring(0, n1)).append(s1.substring(s1.length()-n1,s1.length()));
return sb.toString();
----------------------------------------------------------------------------------------------------||
46) input1="aBrd";
input2="aqrbA";
input3=2;
output1=boolean true;
2nd char of ip1 and last 2nd char of ip2 show be equal
package Set3;
String ip1="aBrd";
String ip2="aqrbA";
int ip3=2;
System.out.println(charCheck(ip1,ip2,ip3));
boolean b=false;
String s1=String.valueOf(ip1.charAt(ip3-1));
String s2=String.valueOf(ip2.charAt(ip2.length()-ip3));
if(s1.equalsIgnoreCase(s2))
b=true;
return b;
----------------------------------------------------------------------------------------------------||
output:9+9+9+9=3+6=9;
package Set3;
int n=9999;
System.out.println(conversiontoaSingleDigit(n));
loop:
while(n>10){
int l=0,m=0;
while(n!=0){
m=n%10;
l=l+m;
n=n/10; }
n=l;
continue loop; }
return n;
----------------------------------------------------------------------------------------------------||
package Set3;
import java.util.*;
public class ClassSeT48 {
String s="2013";
System.out.println(leapYear(s));
int n=Integer.parseInt(s);
boolean b=c.isLeapYear(n);
return b;
----------------------------------------------------------------------------------------------------||
package Set3;
int n=28;
System.out.println(perfectNumber(n));
int n1=0;
boolean b=false;
for(int i=1;i<n;i++)
if(n%i==0)
n1+=i;
//System.out.println(n1);
if(n1==n)
b=true;
return b;
}
}
----------------------------------------------------------------------------------------------------||
String[] input2={“speaker”,”mouse”};
Float output=600.80(500.6+100.2);
package Set3;
import java.util.*;
m1.put("mouse", "100.2");
m1.put("speaker","500.6");
m1.put("monitor", "2000.23");
String[] s={"speaker","mouse"};
System.out.println(getTheTotalCostOfPheripherals(m1,s));
String[] s) {
Float f=(float) 0;
Iterator<String> i=m1.keySet().iterator();
while(i.hasNext()){
Float f1=Float.parseFloat(m1.get(s1));
for(int j=0;j<s.length;j++)
if(s[j].equals(s1))
f+=f1; }
return f;
----------------------------------------------------------------------------------------------------||
Input1=20.0; output=2:1;
package Set3;
import java.util.*;
double d=845.69;
System.out.println(noOfDigits(d));
int n1=0,n2=0;
String s=String.valueOf(d);
String s1=t.nextToken();
String s2=t.nextToken();
n1=s1.length();
n2=s2.length();
if(s1.charAt(0)=='0')
n1=s1.length()-1;
if(n2!=1)
if(s2.charAt(s2.length()-1)=='0')
n2=s2.length()-1;
String s3=String.valueOf(n1)+":"+String.valueOf(n2);
return s3;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num;
System.out.println("Enter an integer");
num = sc.nextInt();
System.out.println("The binary equivalent of "+num+" is "+ Integer.toBinaryString(num));
System.out.println("The hexadecimal equivalent of "+num+" is "+ Integer.toHexString(num));
System.out.println("The octal equivalent of "+num+" is "+ Integer.toOctalString(num));
byte b = (byte) num;
Short s = (short) num;
long l = num;
Float f = (float) num;
Double d = (double) num;
System.out.println("Byte value of "+num+" is "+b);
System.out.println("Short value of "+num+" is "+s);
System.out.println("Long value of "+num+" is "+l);
System.out.println("Float value of "+num+" is "+f);
System.out.println("Double value of "+num+" is "+d);
}
}
Wrapper Class – 1
Write a Java program to print the following static values defined in the Float Wrapper Class
Maximum exponent a float can hold
Maximum value a float can hold
Number of bits used to represent a float value
Sample Output:
Maximum exponent :127
Maximum value :3.4028235E38
Number of bits :32
import java.util.Date;
import java.util.Scanner;
import java.io.IOException;
import java.text.*;
billHeader.setIssueDate(issueDate);
billHeader.setDueDate(dueDate);
billHeader.setOriginalAmount(originalAmount);
billHeader.setAmountOutstanding(amountOutstanding);
public BillHeader() {
}
@Override
public String toString() {
import java.lang.*;
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
// fill your code here
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string");
String str = scan.nextLine();
System.out.println("Enter the start string");
// fill your code here
String chk = scan.nextLine();
if(str.startsWith(chk) )
{
System.out.println('"' + str + '"'+ " starts with "+ '"'+ chk+'"');
}
else
{
System.out.println('"' + str + '"'+ " does not start with "+ '"'+ chk+'"');
}
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
// fill your code here
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string");
String str = scan.nextLine();
String str2 = str.replaceAll(" +", " ");
String str1[] = str2.split(" ",-1);
System.out.println("The words in the string are");
for(int i = 0; i < str1.length; i++)
{
System.out.println(str1[i]);
}
}
}
String Tokenizer
Write a Java program to implement string tokenizer inorder to split a string into two different tokens
by =(equal to) and ;(semicolon).
Input Format:
Input is a string which needs to be split.
Output Format:
Each line of the Output contains two strings. The first string is formed by token '=' and the second
string is formed by the token ';'
Assume: The tokens, '=' and ';', will always come alternately. Refer Sample Input.
Sample Input:
title=Java-Samples;author=Emiley J;publisher=java-samples.com;copyright=2007;
Sample Output:
title Java-Samples
author Emiley J
publisher java-samples.com
copyright 2007
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();
StringTokenizer s1 = new StringTokenizer(s, "=");
String s2 = "";
while(s1.hasMoreTokens()) {
s2 = s2+" "+s1.nextToken();
}
StringTokenizer s3 = new StringTokenizer(s2, ";");
while(s3.hasMoreTokens()) {
System.out.println(s3.nextToken());
}
}
}
StringBuilder would append values in a normal heap instead of any common string pools.
The only difference between StringBuilder & StringBuffer is: StringBuilder is not Thread-Safe whereas
StringBuffer is Thread-Safe.
Let's try out using StringBuilder.
Write a Java Program to display the address of the customer in a particular format.
Create a main class "Main.java".
Create another class file "Address.java" with the following private members.
Data Type Variable name
String line1
String line2
String city
String country
int zipCode
Include appropriate getters and setters.
Use 'toString' method in the Address class and append using String Builder.
Input and Output Format:
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output]
Sample Input & Output:
Enter Address Details :
Enter Line 1 :
152, South Block
Enter Line 2 :
Raisina Hill
Enter City :
New Delhi
Enter Country :
India
Enter Zip Code :
110011
Address Details :
152, South Block,
Raisina Hill,
New Delhi - 110011
India
public Address() {
super();
// TODO Auto-generated constructor stub
}
public Address(String line1, String line2, String city, String country, int zipCode) {
super();
this.line1 = line1;
this.line2 = line2;
this.city = city;
this.country = country;
this.zipCode = zipCode;
}
@Override
public String toString() {
return "Address Details :\n" + new StringBuilder().append(this.getLine1()) + ",\n" + new
StringBuilder().append(this.getLine2()) + ",\n"
+ new StringBuilder().append(this.getCity()) + " - " + new
StringBuilder().append(this.getZipCode()) + "\n"
+ new StringBuilder().append(this.getCountry());
}
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
// fill your code here
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the string");
String str = scnr.nextLine();
System.out.println("Enter the end string");
String strEnd = scnr.nextLine();
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the binary number");
String binaryNo = scnr.next();
System.out.println( "The integer value of the binary number " + binaryNo + " is " + binNo );
System.out.println( "The integer value of the octal number " + octalNo + " is "+ octNo );
System.out.println( "The integer value of the hexadecimal number " + hexaDecimalNo + " is "+ hexNo);
}
}
Lets check the above concept by validating Emailids of two customers first by using equals &
equalsIgnoreCase methods.
Create a main class "Main.java".
Create another class file "Customer.java" with following private member variables.
Data Type Variable Name
String name
String email
Include appropriate getters and setters.
Use 'equals()' and 'equalsIgnoreCase()' to compare the email ids[Refer sample input & output ].
Date - 2
Neerja Banhot was the head of the all Indian cabin crew in the Pan Am 73 flight. Neerja made sure
that everything inside the flight was fine.
She noticed that the date being displayed inside the flight in an LED Board was wrong.
She asked help from a few electronics engineers who were on board. The electronics engineers figure
out that the binary forms of the date, month and year were 2 bits, 2 bits and 2 bits rotated left. Now
the engineers will need to fix this. Given the incorrect date, month and the year use the Integer
Wrapper Class rotateRight() method to print the correct date in International format.
Input Format:
The first line is an integer that corresponds to the incorrect day number.
The second line is an integer that corresponds to the incorrect month number.
The third line is an integer that corresponds to the incorrect year.
Output Format:
The Output should display the correct date in a single line separated by slashes in the international
format.
Sample Input:
20
36
7944
Sample Output:
1986/9/5
Alumni Management System - DML - Nested Queries I
Alter building
Alter table building rename column email_address to email;
Write a query to display the contents of posts posted by Ram in the year 2012, sorted by date.
...
Q15
QQ4
S Problem_Statement Solution
n
o
C Nikhil, the founder of “Pine Tree” company import java.util.Scanner;
U wished to design an Event Management class Main {
S System that would let its Customers plan and public static void main(String[] args) {
T host events seamlessly via an online platform.
O Scanner sc=new Scanner(System.in);
M As a part of this requirement, Nikhil wanted to System.out.println("Enter your name");
I write a piece of code for his company’s Amphi String name=sc.nextLine();
Event Management System that will display
Z int n=name.length();
customized welcome messages by taking
E if(n<=50)
Customers’ name as input. Help Nikhil on the
D task. {
W System.out.println("Hello "+name+" ! Welcome to
E Input Format: Amphi Event Management System");
L First line of the input is a string that }
C corresponds to a Customer’s name. Assume }
O that the maximum length of the string is 50. }
M
E Output Format:
M Output should display the welcome message
E along with the Customer’s name.
S Refer sample input and output for formatting
S specifications.
[All text in bold corresponds to input and
A
rest corresponds to output.]
G
E
Sample Input and Output:
Enter your name
Beena
Hello Beena ! Welcome to Amphi Event
Management System
The prime functionality of an Event import java.util.Scanner;
T Management System is budgeting. An Event import java.text.DecimalFormat;
O Management System should estimate the total class Main {
T expenses incurred by an event and the public static void main(String[] args) {
A percentage rate of each of the expenses DecimalFormat df = new DecimalFormat("0.00");
L involved in planning and executing an event. Scanner sc = new Scanner(System.in);
E
Nikhil, the founder of "Pine Tree" wanted to System.out.println("Enter branding expenses");
X
include this functionality in his company’s int branding = sc.nextInt();
P
E Amphi Event Management System and System.out.println("Enter travel expenses");
N requested your help in writing a program for int travel = sc.nextInt();
S the same. System.out.println("Enter food expenses");
E int food = sc.nextInt();
S The program should get the branding System.out.println("Enter logistics expenses");
F expenses, travel expenses, food expenses and int logistics = sc.nextInt();
O logistics expenses as input from the user and double totalexpense = branding+food+travel+logistics;
R calculate the total expenses for an event and
T double brandingper=branding*100/totalexpense;
the percentage rate of each of these expenses. double travelingper=travel*100/totalexpense;
H
double foodper=food*100/totalexpense;
E
E Input Format: double logisticsper=logistics*100/totalexpense;
V First input is a int value that corresponds to System.out.println("Total expenses :
E the branding expenses. Rs."+df.format(totalexpense));
N Second input is a int value that corresponds to System.out.println("Branding expenses percentage :
T the travel expenses.
"+df.format(brandingper)+"%");
Third input is a int value that corresponds to
//System.out.print("% \n");
the food expenses.
System.out.println("Travel expenses percentage : "
Fourth input is a int value that corresponds to
+df.format(travelingper)+"%");
the logistics expenses.
//cimalFormat df1 = new DecimalFormat("#.##");
System.out.println("Food expenses percentage :
Output Format:
First line of the output should display the int "+df.format(foodper)+"%");
value that corresponds to the total expenses System.out.println("Logistics expenses percentage : "
for the Event. +df.format(logisticsper)+"%");
Next four lines should display the percentage }
rate of each of the expenses. }
Refer sample input and output for formatting
specifications.
[All text in bold corresponds to input and rest
corresponds to output.]
Sample Input 1:
3
5
Sample Output 1:
*
**
***
****
*****
Sample Input 1:
Enter the subject1 mark
3
Enter the subject2 mark
5
Enter the subject3 mark
4
Enter the subject4 mark
4
Enter the subject5 mark
3
Sample Output 1:
No
Sample Input 2:
Enter the subject1 mark
3
Enter the subject2 mark
4
Enter the subject3 mark
4
Enter the subject4 mark
4
Enter the subject5 mark
5
Sample Output 2:
Yes
S The Event Organizing Company "Buzzcraft" import java.util.Scanner;
e focuses event management in a way that
ri creates a win-win situation for all involved public class Main {
e stakeholders. Buzzcraft don't look at building public static void main(String[] args) {
s one time associations with clients, instead, aim Scanner s = new Scanner(System.in);
1 at creating long-lasting collaborations that will int a = Integer.parseInt(s.nextLine());
span years to come. This goal of the company int ct=0,n=0,i=1,j=1;
has helped them to evolve and gain more while(n<a) {
clients within notable time. j=1;
The number of clients of the company from ct=0;
the start day of their journey till now is while(j<=i) {
recorded sensibly and is seemed to have if(i%j==0){
followed a specific series like: ct++;
2,3,5,7,11,13,17,19, 23 ... }
j++;
Write a program which takes an integer N as }
the input and will output the series till the Nth if(ct==2) {
term. System.out.printf("%d ",i);
n++;
Input Format: }
First line of the input is an integer N. i++;
}
Output Format:
}
Output a single line the series till Nth term,
}
each separated by a comma.
Refer sample input and output for formatting
specifications.
Sample Input 1:
5
Sample Output 1:
2 3 5 7 11
Sample Input 2:
10
Sample Output 2:
2 3 5 7 11 13 17 19 23 29
S Problem_Statement Solution
n
o
D The International Film Festival of India import java.text.DecimalFormat;
i (IFFI), founded in 1952, is one of the most public class ItemType {
s significant film festivals in Asia. The private String name;
p
l
festival is for a weel and arrangements private double costPerDay,deposit;
a have to be made for food, chairs, tables, public String getName() {
y etc. The organizing committee plans to return name;
It deposit the advance amount to the }
e contractors on conformation of boking. public void setName(String name) {
m Help them to store these details and print this.name = name;
}
them in detailed view.
T public double getCostPerDay() {
y Write a Java program to get item type, return costPerDay;
p }
e cost per day and deposit amount from
user and display these details in a detailed public void setCostPerDay(double costPerDay) {
this.costPerDay = costPerDay;
view using the following classes and
}
methods.
public double getDeposit() {
[Note :
return deposit;
Strictly adhere to the object oriented }
specifications given as a part of the public void setDeposit(double deposit) {
problem statement. this.deposit = deposit;
Follow the naming conventions as }
mentioned. Create separate classes in public void display(){
separate files.] DecimalFormat df=new DecimalFormat("0.00");
Create a class named ItemType with the System.out.println("Item type details");
following private member variables / System.out.println("Name : "+getName());
attributes. System.out.println("CostPerDay :
Data Type Variable "+df.format(getCostPerDay()));
String name System.out.println("Deposit : "+df.format(getDeposit()));
double costPerDay }
double deposit }
Include appropriate getters and setters.
In the ItemType class include the following
methods.
Method Description
In this method, display the
details of the ItemType in the
format shown in the sample
void
output.
display( )
Include the statement ‘Item
type details’ inside this import java.io.*;
method import java.util.Scanner;
class Main{
Create an another class Main and write a public static void main(String[] args) throws Exception {
main method to test the above class. ItemType i = new ItemType();
Scanner sc = new Scanner(System.in);
In the main( ) method, read the item type
details from the user and call the display( ) System.out.println("Enter the item type name");
method. i.setName(sc.nextLine());
Example of getters and setters System.out.println("Enter the cost per day");
private String name; i.setCostPerDay(sc.nextDouble());
public String getName( ) { System.out.println("Enter the deposit");
return name; i.setDeposit(sc.nextDouble());
} i.display();
public void setName(String name) { }
this.name = name; }
}
private double costPerDay;
public double getCostPerDay( ) {
return name;
}
public void setCostPerDay(double
costPerDay) {
this.costPerDay = costPerDay;
}
private double deposit;
public double getDeposit( ) {
return name;
}
public void setDeposit(double deposit) {
this.deposit = deposit;
}
Input and Output Format:
Refer sample input and output for
formatting specifications.
Cost per day and Deposit value should be
displayed upto 2 decimal places.
All text in bold correspondstoinput and the
rest corresponds to output.
Sample Input/Output 1
Enter Name
john
Enter UserName
john@123
Enter Password
john@123
Enter PhoneNo
9092314562
Enter Name
john
Enter UserName
john@12
Enter Password
john@12
Enter PhoneNo
9092314562
Same Users
Sample Input/Output 2
Enter Name
ram
Enter UserName
ram####
Enter Password
ram
Enter PhoneNo
9092314562
Enter Name
john
Enter UserName
john@123
Enter Password
john@123
Enter PhoneNo
9092312102
Different Users
Sample Input 1:
3
5
Sample Output 1:
*
**
***
****
*****
Aayush studies in Teswan National import java.util.*;
A University. Now is the time for exam import java.io.*;
A results. Aayush similar to other students,
Y class Main {
U
hopes that his scores in 5 subjects in the
exam could fetch him a scholarship for his public static void main(String[] args) {
S int sub1, sub2, sub3, sub4, sub5;
H GRE preparation.
Scanner scan = new Scanner(System.in);
'
S System.out.println("Enter the subject1 mark");
The following simple rules are used to find sub1 = scan.nextInt();
S
C
whether he is eligible to receive System.out.println("Enter the subject2 mark");
H scholarship: sub2 = scan.nextInt();
O University follows 5 point grading System.out.println("Enter the subject3 mark");
L
system. In an exam, a student can receive sub3 = scan.nextInt();
A System.out.println("Enter the subject4 mark");
R any score from 2 to 5. 2 is called an F
sub4 = scan.nextInt();
S grade, meaning that student has failed that
H System.out.println("Enter the subject5 mark");
I exam. sub5 = scan.nextInt();
P Student should not have fail any of if(sub1==5||sub2==5||sub3==5||sub4==5||sub5==5)
the exams. {
if(sub1==2||sub2==2||sub3==2||sub4==2||sub5==2)
Student must obtain a full score in
System.out.println("No");
some of his/her exams to show that else if((sub1+sub2+sub3+sub4+sub5)/5.0>=4.0)
he/she is excellent in some of the subjects. System.out.println("Yes");
He/She must have a grade point else
System.out.println("No");
average not less than 4.0
}
You are given information regarding how
else
Aayush performed in those 5 subjects . System.out.println("No");
Help him determine whether he will }
receive the scholarship or not. }
Input Format:
The input contains 5 integers denoting
Aayush’s 5 subjects score in the exam.
Output Format:
Output a single line - "Yes" (without
quotes) if Aayush will receive scholarship,
or "No" (without quotes) otherwise.
Refer sample input and output for
formatting specifications.
Sample Input 1:
Enter the subject1 mark
3
Enter the subject2 mark
5
Enter the subject3 mark
4
Enter the subject4 mark
4
Enter the subject5 mark
3
Sample Output 1:
No
Sample Input 2:
Enter the subject1 mark
3
Enter the subject2 mark
4
Enter the subject3 mark
4
Enter the subject4 mark
4
Enter the subject5 mark
5
Sample Output 2:
Yes
S The Event Organizing Company "Buzzcraft" import java.util.Scanner;
e focuses event management in a way that
ri creates a win-win situation for all involved public class Main {
e stakeholders. Buzzcraft don't look at building public static void main(String[] args) {
s one time associations with clients, instead, aim Scanner s = new Scanner(System.in);
1 at creating long-lasting collaborations that will int a = Integer.parseInt(s.nextLine());
span years to come. This goal of the company int ct=0,n=0,i=1,j=1;
has helped them to evolve and gain more while(n<a) {
clients within notable time. j=1;
The number of clients of the company from ct=0;
the start day of their journey till now is while(j<=i) {
recorded sensibly and is seemed to have if(i%j==0){
followed a specific series like: ct++;
2,3,5,7,11,13,17,19, 23 ... }
j++;
Write a program which takes an integer N as }
the input and will output the series till the Nth if(ct==2) {
term. System.out.printf("%d ",i);
n++;
Input Format: }
First line of the input is an integer N. i++;
}
Output Format:
}
Output a single line the series till Nth term,
}
each separated by a comma.
Refer sample input and output for formatting
specifications.
Sample Input 1:
5
Sample Output 1:
2 3 5 7 11
Sample Input 2:
10
Sample Output 2:
2 3 5 7 11 13 17 19 23 29
Simplified Fraction
St. Patrick Convent organizes a project exhibition "Innovative Minds" every year with an objective to
provide the platform and unleash the potential of the students by showcasing their innovative
projects. Pasha is a smart high school student and was eager to participate in the fair for the first
time.
After a lot of ground works, she decided her project and set out to design the same. Her project
requirement was to design an advanced calculator that has a fraction feature that will simplify
fractions. The project will accept a non-negative integer as a numerator and a positive integer as a
denominator and outputs the fraction in simplest form. That is, the fraction cannot be reduced any
further, and the numerator will be less than the denominator.
Help Pasha to program her advanced calculator and succeed in her first ever project presentation.
You can assume that all input numerators and denominators will produce valid fractions.
Create a driver class called Main. In the Main method, obtain input from the user in the console
and call the printValue method present in the Fraction class.
[Note: Strictly adhere to the Object Oriented Specifications given in the problem statement.
All class names, attribute names and method names should be the same as specified in the problem
statement. Create separate classes in separate files.]
Input Format:
First line of the input is a non-negative integer which is the numerator in the fraction.
Second line of the input is a positive integer which is thedenominator in the fraction.
Output Format:
Output the simplified form of the fraction in a single line.
Refer sample input and output for formatting specifications.
Sample Input 1:
28
7
Sample Output 1:
4
Sample Input 2:
13
5
Sample Output 2:
2 3/5
import java.math.BigInteger;
int fraction = a / b;
int g = bigVal.intValue();
String str = "GCD of " + big1 + " and " + big2 + " is " + g;
int rem = a % b;
int ans = a / b;
if (a == 0) {
System.out.println(0);
} else if (a < b) {
a = a / g;
b = b / g;
System.out.printf("%d/%d", a, b);
} else if (rem == 0) {
System.out.println(ans);
} else if (rem != 0) {
a = a / g;
b = b / g;
ans = a / b;
rem = a % b;
import java.util.*;
//get inputs
int num=sc.nextInt();
int den=sc.nextInt();
fraction.printValue (num,den);
}
Row Number
The flight has landed at the Karachi International Airport. Most of the passengers from Karachi were travelling by air for the first time.
Neerja, the purser wanted to help the passengers locate their seats.
The Pan Am aircraft had R rows with C seats numbered from 1. Given a seat number can you determine the row number in which the
seat would fall in.
Input Format :
The first line of input is an integer R corresponding to the number of rows.
The second line of input is an integer C corresponding to the number of seats in a row.
The third line of input is an integer S corresponding to the seat number.
Output Format :
The output consists of one line.
Print an integer corresponding to the row number in which the seat falls if the seat number exists.
Print “Invalid Input” if the seat number does not exist.
Refer sample input(s) and output(s) for formatting specifications.
Sample Input 1:
10
20
11
Sample Output 1:
1
Sample Input 2:
-9
20
13
Sample Output 2:
Invalid Input
import java.util.Scanner;
int R=sc.nextInt();
int C=sc.nextInt();
int S=sc.nextInt();
if(R>0&&C>0&&S>0)
System.out.println(S%R);
else
{
System.out.println("Invalid Input");
return aircraftName;
this.aircraftName = aircraftName;
return seatId;
this.seatId = seatId;
return travelClassid;
this.travelClassid = travelClassid;
this.businessClassSeatid = businessClassSeatid;
return seatType;
this.seatType = seatType;
return tvChannelpreferences;
this.tvChannelpreferences = tvChannelpreferences;
System.out.println("Seat Id : "+getSeatId());
System.out.println("Travelclass id : "+getTravelClassid());
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
c.setAircraftName(br.readLine());
int seatId=Integer.parseInt(br.readLine());
c.setSeatId(seatId);
c.setTravelClassid(br.readLine());
c.setSeatType(br.readLine());
int businessClassSeatid=Integer.parseInt(br.readLine());
c.setBusinessClassSeatid(businessClassSeatid);
c.setTvChannelpreferences(br.readLine());
c.displayDetails();
super();
this.aircraftName = aircraftName;
this.source = source;
this.destination = destination;
return aircraftName;
this.aircraftName = aircraftName;
return source;
this.source = source;
}
public String getDestination() {
return destination;
this.destination = destination;
@Override
return "Aircraft [aircraftName=" + aircraftName + ", source=" + source + ", destination=" + destination
+ super.toString() + "]";
this.checkinbeforetwohours = checkinbeforetwohours;
this.pilotPreference = pilotPreference;
this.purpose = purpose;
return checkinbeforetwohours;
}
this.checkinbeforetwohours = checkinbeforetwohours;
return pilotPreference;
this.pilotPreference = pilotPreference;
return purpose;
this.purpose = purpose;
@Override
System.out.println("Source : "+getSource());
System.out.println("Destination : "+getDestination());
this.checkinbeforetwohours = checkinbeforetwohours;
this.noOfKgsallowed = noOfKgsallowed;
this.additionalFeeperkg = additionalFeeperkg;
return checkinbeforetwohours;
this.checkinbeforetwohours = checkinbeforetwohours;
return noOfKgsallowed;
this.noOfKgsallowed = noOfKgsallowed;
return additionalFeeperkg;
this.additionalFeeperkg = additionalFeeperkg;
@Override
System.out.println("Source : "+getSource());
System.out.println("Destination : "+getDestination());
System.out.println("Flight check in before two hours :"+checkinbeforetwohours);
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
String aircraftName=br.readLine();
String source=br.readLine();
int choice=Integer.parseInt(br.readLine());
if(choice==1)
{
System.out.println("Is the flight check in before two hours");
Boolean b1;
if(ans.equals("yes"))
b1=true;
else
b1=false;
int noOfKgsallowed=Integer.parseInt(br.readLine());
System.out.println("Enter the additional fee charged for extra baggage per Kg");
float additionalFeeperkg=Float.parseFloat(br.readLine());
Aircraft b = new
PublicAircraft(aircraftName,source,destination,noOfKgsallowed,additionalFeeperkg,b1);
System.out.println("Public Aircraft:");
b.displayDetails();
if(choice==2)
String pilotPreference=br.readLine();
System.out.println("Private Aircraft:");
b.displayDetails();
InvalidBookException
[Note : Strictly adhere to the object-oriented specifications given as a part of the problem
statement. Follow the naming conventions as mentioned. Create separate classes in separate
files.]
Create a driver class Main with the main method to test the above classes. Get the book details
from user in comma separated format. Create book object using createBook() method and display
the book details using toString() method in Book class. Handle exception using try catch and display
the exception message.
return code;
this.code = code;
return title;
this.title = title;
return author;
}
this.author = author;
return price;
this.price = price;
Write a Java program to get item type, cost per day and deposit amount from user and display these
details in a detailed view using the following classes and methods.
[Note :
Strictly adhere to the object oriented specifications given as a part of the problem statement.
Follow the naming conventions as mentioned. Create separate classes in separate files.]
Create an another class Main and write a main method to test the above class.
In the main( ) method, read the item type details from the user and call the display( ) method.
PROBLEM
Little App helps you discover great places to eat around or de-stress in all major cities across
20000+ merchants. Explore restaurants, spa & salons and activities to find your next fantastic
deal. The development team of Little App seeks your help to find the duplication of user accounts.
Write a Java program to get two users details and display whether their phone numbers are same or
not with the following class and methods.
[Note : Strictly adhere to the object-oriented specifications given as a part of the problem
statement.
Follow the naming conventions as mentioned. Create separate classes in separate files.]
Create a class named User with the following private attributes/variables.
Date Type Variable
String name
String username
String password
long phoneNo
Include appropriate getters and setters.
Include four-argument constructor with parameters in the following order,
public User(String name, String username, String password, long phoneNo)
Create another class Main and write a main method to test the above class.
Sample Input/Output 1
Enter Name
john
Enter UserName
john@123
Enter Password
john@123
Enter PhoneNo
9092314562
Enter Name
john
Enter UserName
john@12
Enter Password
john@12
Enter PhoneNo
9092314562
Same Users
Sample Input/Output 2
Enter Name
ram
Enter UserName
ram####
Enter Password
ram
Enter PhoneNo
9092314562
Enter Name
john
Enter UserName
john@123
Enter Password
john@123
Enter PhoneNo
9092312102
Different Users
import java.text.DecimalFormat;
return name;
this.name = name;
return costPerDay;
this.costPerDay = costPerDay;
return deposit;
this.deposit = deposit;
System.out.println("Name : "+getName());
System.out.println("CostPerDay : "+df.format(getCostPerDay()));
System.out.println("Deposit : "+df.format(getDeposit()));
import java.io.*;
import java.util.Scanner;
class Main{
i.setName(sc.nextLine());
i.setCostPerDay(sc.nextDouble());
i.setDeposit(sc.nextDouble());
i.display();
}
Rectangle Dimension Change
Write a Java program to illustrate the method returning an objects by getting details from user and
check the type of objects using instanceof and display these details in a detailed view using the
following classes and methods.
[Note :
Strictly adhere to the object oriented specifications given as a part of the problem statement.
Follow the naming conventions as mentioned. Create separate classes in separate files.]
Create an another class Main and write a main() method to test the above class.
In the main( ) method, read the length and width details from the user and test the above methods.
Display the area of the rectange inside the main() method.
Problem Constraints:
1. Use instanceof operator to check the object returned by dimensionChange( ) method.
[The java instanceof operator is used to test whether the object is an instance of the specified type
(class or subclass or interface).]
PROBLEM
Write a program to implement the String methods like substring, charAt, equalsIgnoreCase and
concat.
Input format:
Input consists of two strings. String length should be greater than 5.
Output format:
Output consists of the result of all String methds.
Note:
Refer the sample input and output for specifications.
All text in bold corresponds to the input and remaining corresponds to the output.
Constraints :
Use for each loop to iterate and print the elements.
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.
Sample Output 1:
Arguments :
Command
Arguments
Number of arguments is 2
Sample Output 2:
Arguments :
Commands
Number of arguments is 1
int count=0;
System.out.println("Arguments :");
for(int a=0;a<args.length;a++)
System.out.println(args[a]);
count++;
Article count
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program
for maximum utilization of CPU. Each part of such a program is called a thread. The threads are
light-weight processes within a process.
Let's have a quick look at the way threads work in Java. For multi-threading to work, the class that
will be invoked as a thread should extend the Thread class. You may wonder, what is the use of
multi-threading. Let's understand it by the following exercise. Given 'n' number of lines of text, you
have to find the total number of articles present in the given lines. while obtaining inputs from the
user, the Main method has the full control of the execution.
The time is wasted in input gathering, which can be invaluable for large computing applications, has
to be utilized properly. Hence a thread is invoked when a line is obtained and the articles are
counted while the input for the subsequent lines is obtained from the user. Thus threading can
increase efficiency and time constraints.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create a class called Article which extends the Thread class with the following private attributes.
Attributes Datatype
line String
count Integer
Include appropriate getters and setters.
Generate default and parameterized constructors. The format for the parameterized constructor
is Article(String line)
Create a driver class called Main. In the Main method, invoke 'n' threads for 'n' lines of input and
compute the total count of the articles in the given lines.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String line;
int count;
public Article() {
super();
super();
this.line = line;
return line;
this.line = line;
return count;
this.count = count;
@Override
Matcher m = Pattern.compile("(?i)\\b((a)|(an)|(the))\\b").matcher(this.getLine());
while (m.find()) {
this.count++;
import java.util.Scanner;
int n = sc.nextInt();
int count = 0;
sc.nextLine();
for(int i=0;i<n;i++) {
a.setLine(sc.nextLine());
a.start();
a.join();
count +=a.getCount();
}
Profit or Loss
We are going to create a console application that can estimate whether the booking is a profit or loss,
thereby enabling hall owners to reduce or increase expenses depending on the status. Hence if
several Booking details are given, compute whether the bookings are profitable or not. Use Threads
to compute for each booking, Finally display the details along with the profit/loss status.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create a class Event with the following private attributes
Attributes Datatype
name String
hallbooking HallBooking
Include appropriate getters and setters.
Create default constructor and a parameterized constructor with arguments in order Event(String
name,HallBooking hallbooking).
Create a class HallBooking with following private attributes
Attributes Datatype
hallName String
cost Double
hallCapacity Integer
seatsBooked Integer
Include appropriate getters and setters.
Create default constructor and a parameterized constructor with arguments in order
HallBooking(String hallName, Double cost, Integer hallCapacity,Integer seatsBooked).
Create a class ComputeStatus that implements Runnable interface with List<Event>
eventList attribute.
Create a driver class Main which creates ThreadGroup with two threads. Each thread will have half of
the event details. After the first half of event details are obtained, invoke the first thread and after the
other half is obtained invoke the second thread. The Threads print the status of the events. Use the
join method appropriately to ensure printing the status in the correct order.
Input Format:
Output Format:
The output consists of event names with their status (Profit or Loss).
Refer to sample output for formatting specifications.
Problem Constraints:
If n>0 and n then even. Otherwise, display as "Invalid Input".
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public Event() {
}
@Override
public void run() {
// System.out.println(Thread.currentThread().getName());
Iterator iterator = eventList.iterator();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (iterator.hasNext()) {
Event e = (Event) iterator.next();
if (e.getHallBooking().getSeatsBooked() * 100 / e.getHallBooking().getHallCapacity() >= 60) {
System.out.println(e.getName() + " yields profit");
} else {
System.out.println(e.getName() + " yields loss");
}
}
}
}
public class HallBooking {
private String hallName;
private Double cost;
private Integer hallCapacity;
private Integer seatsBooked;
public HallBooking() {
}
All three worker threads are concurrently executed on shared or dedicated CPUs depending on the
type of machine. Although the master thread can continue its execution, in this case, it needs to make
sure that all operations are completed before combining individual results. This is accomplished by
waiting for each thread to complete by invoking join() method associated with each worker thread.
The main thread is called Main, which acts like a master thread. It creates three worker threads
(SineClass, CosClass, and TanClass) and assigns them to compute values for different data inputs.
Hint:
Use the following code snippet to print to 2 decimal places.
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("Sum of sin, cos, tan = " + df.format(z));
@Override
public void run() {
double b = Math.toRadians(cos);
value = Math.cos(b);
}
public double getValue() {
return value;
}
@Override
public void run() {
double b = Math.toRadians(sins);
value = Math.sin(b);
return value;
}
@Override
public void run() {
double b = Math.toRadians(tan);
value = Math.tan(b);
return value;
}
import java.text.DecimalFormat;
import java.util.Scanner;
s.start();
try {
s.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
c.start();
try {
c.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Calculate Factorial
Objectives :
To get experience on Number Equality using JUnit Testing Library.
Functional Requirements:
Suriya and Manikandan are best friends, they try to play a game on words. If a word is given to
them, they need to find as many words as possible using the characters in the given word. While
playing, they taught to find how many numbers of combinations are possible. But, they find it difficult
to get it. They knew they can get the combinations by a factorial. Can you write a function to
determine the total number of combinations they can generate?
FactorialBO class contains the following method.
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class FactorialJUnit {
FactorialBO fb;
@Before
public void createBoInstance() {
fb=new FactorialBO();
}
@Test
public void testFactorial() {
assertEquals(120,fb.calculateFactorial(5));
}
}
public class FactorialBO {
public long calculateFactorial(int n) {
long val = 1;
for(int i=1;i<=n;i++) {
val*=i;
}
return val;
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number:");
Integer n = Integer.parseInt(buff.readLine());
System.out.println("The factorial of "+n+" is "+new FactorialBO().calculateFactorial(n));
}
}
Objectives :
To get experience @Test and @Before annotation using JUnit Testing Library.
Functional Requirements:
The fair organizers have listed the accepted domains as "com", "in", "net", and "org".
Write a program to validate the email addresses that have the above listed domain names.
Example:
Valid Domain mail: [email protected]
Invalid Domain mail: [email protected]
Note :
The code for implementing the above requirement is provided as part of the code template.
Jars for JUnit are available in the link - JUNIT JARS
Test Specification :
Create a class named DomainValidationJUnit and include the following test methods to test
the validateMailDomain method in the above code specifications.
Objectives:
To get experience in Testing Exceptions using JUnit Testing Library.
Functional Requirements:
An exception is an unwanted or unexpected event, which occurs during the execution of a program
i.e at runtime, it disrupts the normal flow of the program. For example, there are 10 statements in
your program and there occurs an exception at statement 5, rest of the code will not be executed i.e.
statement 6 to 10 will not run. If we perform exception handling, rest of the statement will be
executed. That is why we use exception handling.
For practice in exception handling, obtain the cost for 'n' days of an item and n as input and calculate
the cost per day for the item. In case, zero is given as input for n, an arithmetic exception is thrown,
handle the exception and prompt the user accordingly (Refer sample I/O).
Test
Method Name Method Description
Case
Test This method is used to test the cost per day
testCalculateCost
case 1 returned by the calculateCost method.
This method is used to test the ArithmeticException
Test testCalculateCostExceptio
case, whether the method is throwing
case 2 n
ArithmeticException in days given as 0.
import org.junit.Before;
import org.junit.Test;
//@SuppressWarnings("deprecation")
@Test
assertEquals(20.0,cbo.calculateCost(100, 5),0.0);
@Test(expected=ArithmeticException.class)
cbo.calculateCost(10, 0);
//assertEquals(message,m);
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
Integer cost=Integer.parseInt(br.readLine());
Integer n=Integer.parseInt(br.readLine());
double costPerDay;
try{
catch(ArithmeticException e){
System.out.println(e);
return (cost/days);
Date Formats
Objectives:
To get experience on equalTo in Basic assertThat using JUnit Testing Library.
Functional Requirements:
SimpleDateFormat in Java can be used to convert String to Date in Java.
java.text.SimpleDateFormat is an implementation of DateFormat which defines a date pattern and
can convert a particular String which follows that pattern into Date in Java. Write a program to
convert the dates given by the user into different formats.
Note :
The code for implementing the above requirement is provided as part of the code template.
Jars for JUnit are available in the link - JUNIT JARS
import org.hamcrest.CoreMatchers;
import org.junit.Test;
@Test
@Test
// assertThat("12.12.1991",equalsTo(dbo1.convertToFormat1("12-12-1991")))
@Test
public void testConvertToFormat2() {
assertThat("12.12.1991",CoreMatchers.equalTo(dbo1.convertToFormat2("12-12-1991")));
@Test
assertThat("12/12/1991",CoreMatchers.equalTo(dbo1.convertToFormat3("12-12-1991")));
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
Date d1;
try { d1 = s1.parse(value); }
return s2.format(d1);
Date d1;
try { d1 = s1.parse(value); }
return s2.format(d1);
Date d1;
try { d1 = s1.parse(value); }
return s2.format(d1);
}
Finding Square
Objectives:
To get experience in Custom assertThat using JUnit Testing Library.
Functional Requirements:
Write a program to accept an integer as argument and print the square of that integer.
Note :
The code for implementing the above requirement is provided as part of the code template.
Jars for JUnit are available in the link - JUNIT JARS
Test Specification :
Create a class named SquareJUnit and include the following test methods to test
the findSquareValue method in the above code specifications.
Test Case Method Name Method Description
Test case 1 testFindSquareValue This method is used to test the square of the Integer.
import org.junit.Before;
import org.junit.Before;
import org.junit.Test;
SquareBO sb;
@Before
@Test
sb=new SquareBO;
assertThat(9,SquareChecker.checkSquare(9))
@Override
description.appendText(""+value+"");
return (value==n);
mismatchDescription.appendText("java.lang.AssertionError: Expected:"
};
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
Integer n = Integer.parseInt(buff.readLine());
System.out.println(new SquareBO().findSquareValue(n));
return n*n;
Introduction to JDBC
JDBC is an Application Programming Interface(API) which describes how a client may access a
database. Here this program provides you the basic knowledge about SELECT statement in Oracle.
The SELECT statement is used to retrieve the records from the database based on the client's needs.
The retrieved data will be stored in a ResultSet and this ResultSet is used to display those selected
records. Here, use a SELECT statement to display the records from the ItemType table.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create a driver class Main to display the list of objects in the following format.
NOTE : Use System.out.format("%-5s %-15s %-10s %s\n","ID","Name","Deposit","Cost per day") to
display ItemType details.
Table Properties:
CREATE TABLE item_type(
id number(19) NOT NULL,
name varchar2(255) NOT NULL,
deposit BINARY_DOUBLE NOT NULL,
cost_per_day BINARY_DOUBLE NOT NULL,
PRIMARY KEY (id));
CREATE SEQUENCE item_type_seq START WITH 1 INCREMENT BY 1;
oracle.properties:
db.url = jdbc:oracle:thin:@localhost:1521:xe
db.username = root
db.password = student
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input and Output:
Id Name Deposit Cost per day
1 Food 50000.0 10000.0
2 Electronics 85000.0 15000.0
3 Fashion 36000.0 8000.0
4 Grooming 15000.0 5000.0
5 Books 20000.0 7500.0
Select Statement
Write a program to retrieve all the records present in the User table and display those records in the
specified format using the SELECT select.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Table properties:
CREATE TABLE “user”(
id number(19) NOT NULL,
name VARCHAR2(45) NOT NULL,
contact_detail VARCHAR2(45) NOT NULL,
username VARCHAR2(45) NOT NULL,
password VARCHAR2(45) NOT NULL,
PRIMARY KEY (id));
CREATE SEQUENCE user_seq START WITH 1 INCREMENT BY 1;
Use the following code snippet to establish DBConnection:
import java.util.ResourceBundle;
ResourceBundle rb = ResourceBundle.getBundle("oracle");
String url = rb.getString("db.url");
String username = rb.getString("db.username");
String password = rb.getString("db.password");
oracle.properties:
db.url = jdbc:oracle:thin:@localhost:1521:xe
db.username = root
db.password = student
Download the oracle jar file in the below link.
Oracle jar
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input and Output:
Id Name Contact Detail Username Password
1 John 9876543210 johny 12345
2 Peter 9873216540 peterey pet123
3 Adam 9871236504 adamanta ad@123
4 Linda 8794561320 lindahere abcd
5 Tony 7894561230 tonii abc123
Using PreparedStatement
Let’s try the PreparedStatement interface in this problem. The PreparedStatement interface enables
you to perform Database operations by obtaining parameters at run-time. Let's have practice in
PreparedStatement in the following exercise.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create a class called User with the following private attributes
Attributes Datatype
id Long
name String
contactDetail String
username String
password String
Generate getters and setters.
Generate Default and two parameterized constructors.
Format for Parameterized constructors are
User(String name, String contactDetail, String username, String password)
User(Long id, String name, String contactDetail, String username,String password)
Create a class called UserDAO with the following methods
Method name Description
This method accepts a User object as an argument and
public void insertDetails(User u)
inserts the details in the user table.
This method retrieves all user details in the ascending order of id from the user ta
public List<User> getAllUser()
stores it in the list of user objects, and returns the list.
Create a driver class called Main. In the main method, accept user details from the user and call
appropriate methods in the UserDAO class.
Table properties:
CREATE TABLE "user"(
id number(19) NOT NULL,
name VARCHAR2(45) NOT NULL,
contact_detail VARCHAR2(45) NOT NULL,
username VARCHAR2(45) NOT NULL,
password VARCHAR2(45) NOT NULL,
PRIMARY KEY (id));
CREATE SEQUENCE "user_seq" START WITH 1 INCREMENT BY 1;
In the previous problem, we stored data in a single table. But now we are gonna use 2 tables. One is
the User and another is Hall. A User will be the owner of a Hall. So, the user object is kept in the hall
class and the user id is kept in the hall table. We need to get the username of the owner, retrieve the
object from the user table and get the details of the hall and place the user object in it as owner. Then
store the hall details in the hall table with the user id. This will be helpful for the hall owners to
register their halls for the event in our application. Let's get to programming this feature.
Create a driver class Main and use the main method for user interactions.
Table properties:
CREATE TABLE "user"(
id number(19) NOT NULL,
name VARCHAR2(45) NOT NULL,
contact_detail VARCHAR2(45) NOT NULL,
username VARCHAR2(45) NOT NULL,
password VARCHAR2(45) NOT NULL,
PRIMARY KEY (id));
CREATE SEQUENCE "user_seq" START WITH 1 INCREMENT BY 1;
[All Texts in bold corresponds to the input and rest are output]
Sample Input and Output 1:
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create a class User with the following private attributes
Attributes Datatype
id Long
name String
contactDetail String
username String
password String
Generate appropriate Getters and Setters
Generate default and parameterized constructors
Parameterized constructor should be in the following format
User(Long id,String name, String contactDetail, String username, String password)
Table Properties:
CREATE TABLE "user"(
id number(19) NOT NULL,
name VARCHAR2(45) NOT NULL,
contact_detail VARCHAR2(45) NOT NULL,
username VARCHAR2(45) NOT NULL,
password VARCHAR2(45) NOT NULL,
PRIMARY KEY (id));
CREATE SEQUENCE "user_seq" START WITH 1 INCREMENT BY 1;
oracle.properties:
db.url = jdbc:oracle:thin:@localhost:1521:xe
db.username = root
db.password = student
Download the oracle jar file in the below link.
Oracle jar
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
[All Texts in bold corresponds to the input and rest are output]
Sample Input and Output 1:
Create a driver class Main and use the main method for the user interactions.
Table properties:
CREATE TABLE exhibition(
id NUMBER(19) NOT NULL,
name VARCHAR2(45) NOT NULL,
PRIMARY KEY(id));
CREATE SEQUENCE exhibition_seq START WITH 1 INCREMENT BY 1;
CREATE TABLE stall(
id NUMBER(19) NOT NULL,
name VARCHAR2(255) NOT NULL,
detail VARCHAR2(255) NOT NULL,
owner VARCHAR2(255) NOT NULL,
exhibition_id NUMBER(19) NOT NULL,
foreign key(exhibition_id) references exhibition(id),
PRIMARY KEY (id));
CREATE SEQUENCE stall_seq START WITH 1 INCREMENT BY 1;
[All Texts in bold corresponds to the input and rest are output]
Sample Input and Output 1:
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create a class ItemType with the following private attributes
Attributes Datatype
id Long
name String
deposit Double
costPerDay Double
Create a class Item with the following private member attributes
Attributes Datatype
id Long
name String
itemType ItemType
vendor String
Generate appropriate Getters and Setters for the above classes
Generate default and parameterized constructors
Parameterized constructor should be in the following format
ItemType(Long id, String name, Double deposit, Double costPerDay)
Item(Long id, String name, ItemType itemType, String vendor)
Table Structure:
CREATE TABLE item_type(
id number(19) NOT NULL,
name varchar2(255) NOT NULL,
deposit BINARY_DOUBLE NOT NULL,
cost_per_day BINARY_DOUBLE NOT NULL,
PRIMARY KEY (id));
CREATE SEQUENCE item_type_seq START WITH 1 INCREMENT BY 1;
oracle.properties:
db.url = jdbc:oracle:thin:@localhost:1521:xe
db.username = root
db.password = student
Create a driver class called Main. In the main method, accept event details from the user and call
appropriate methods in EventDAO class. When an id not present in the table is given print "Id not
found " and terminate.
Table properties:
CREATE TABLE event(
id NUMBER(10) NOT NULL,
name VARCHAR2(255) NOT NULL,
detail VARCHAR2(255) NOT NULL,
start_date TIMESTAMP(0) NOT NULL,
end_date TIMESTAMP(0) NOT NULL,
organizer VARCHAR2(255) NOT NULL,
PRIMARY KEY (id));
CREATE SEQUENCE event_seq START WITH 1 INCREMENT BY 1;
oracle.properties:
db.url = jdbc:oracle:thin:@localhost:1521:xe
db.username = root
db.password = student
Download the oracle jar file in the below link.
Oracle jar
Generate getters and setters.
Generate Default and two parameterized constructors.
Format for Parameterized constructors are
Hall(String name, String contactDetail, Double costPerDay, String owner)
Hall(Long id, String name, String contactDetail, Double costPerDay,String owner)
Create a class called HallDAO with the following methods
Method name Description
This method retrieves all the Hall details
public List<Hall>
from the hall table, stores the details in list of
getHallList()
Hall objects, and returns the list.
This method accepts list of Hall objects as
public void
argument and stores each object details into
bulkInsert(List<Hall> list)
the hall table.
Create a driver class called Main. In the main method, accept event details from the user and call
appropriate methods in HallDAO class.
Note: while retrieving data from table sort by cost_per_day.
Use batch for inserting multiple rows.
System.out.format ("%-5s %-15s %-15s %-15s %s\n","Id","Hall name","Contact detail","Cost
per day","Organizer");
Table properties:
CREATE TABLE hall(
id number(19) NOT NULL,
name VARCHAR2(255) NOT NULL,
contact_detail VARCHAR2(255) NOT NULL,
cost_per_day BINARY_DOUBLE NOT NULL,
owner VARCHAR2(255) NOT NULL,
PRIMARY KEY (id));
CREATE SEQUENCE hall_seq START WITH 1 INCREMENT BY 1;
Use the following code snippet to establish DBConnection:
import java.util.ResourceBundle;
ResourceBundle rb = ResourceBundle.getBundle("oracle");
String url = rb.getString("db.url");
String username = rb.getString("db.username");
String password = rb.getString("db.password");
oracle.properties:
db.url = jdbc:oracle:thin:@localhost:1521:xe
db.username = root
db.password = student
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create a driver class called Main. If the List of Users is empty print "The list is empty" in the main
method. Else display the user detail by calling the display method.
Input format:
Read the input from the "input.csv" file which contains the user details.
Output format:
Use "%-15s %-20s %-15s %s\n" to print statements for the heading of the details in the Main
method.
Sample Output :
Name Email Username Password
Ram [email protected] ram ram123
krish [email protected] krish abc
Input,csv
Ram,[email protected],ram,ram123
krish,[email protected],krish,abc
user.java
public class User {
private String name;
private String email;
private String username;
private String password;
public User() {
}
Main.java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
public class Main {
userBo.java’
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class UserBO {
public List<User> readFromFile(BufferedReader br) throws IOException {
List<User> userList = new ArrayList<User>();
User user;
try {
String line;
while ((line = br.readLine()) != null) {
String[] tokens = line.split(",");
user = new User();
user.setName(tokens[0]);
user.setEmail(tokens[1]);
user.setUsername(tokens[2]);
user.setPassword(tokens[3]);
userList.add(user);
}
br.close();
File Writing
The file we write can be of several formats. But for now, we are just going to write a CSV text file, in
which all the fields are separated by comma delimiter. Use FileWriter and BufferedWriter to write the
data to a file.
As a first thing, we are gonna create a file that contains the record of all the users registered. So write
a program that can write all the user details from the console into a file "output.csv".
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create a driver class Main and use the main method to get the details from the user.
Input format:
The first line of input consists of an integer that corresponds to the number of users.
The next n line of input consists of user details in the CSV format (name, mobileNumber, username,
password)
Refer to sample Input for other further details.
Output format:
Write the user details in the output.csv file.
Refer to sample Output for other further details.
Sample Input:
[All Texts in bold corresponds to the input and rest are output]
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Scanner;
userList.add(user);
user = null;
}
FileWriter fw = new FileWriter("output.csv");
BufferedWriter bw = new BufferedWriter(fw);
UserBO.writeFile(userList, bw);
}
import java.io.BufferedWriter;
import java.util.ArrayList;
for(User u:userList)
{
bw.write(u.getName()+",");
bw.write(u.getMobileNumber()+",");
bw.write(u.getUsername()+",");
bw.write(u.getPassword());
bw.write("\n");
}
bw.flush();
bw.close();
}
}
Hall details
In the last problem, we read a file and got its contents. Now we are gonna write some contents into
our desired file. Writing details in a file is so important as the file can be easily transferred to
whenever we want. So in our application for the exhibition, we have many many halls. So a file with
all the hall details should be fine for future reference. So get the hall details in CSV format in the
console and store them as the list of objects. Then write this list into the file "output.txt".
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create default constructor and a parameterized constructor with arguments in order Hall(String
name, String contact, Double costPerDay, String owner).
Include appropriate getters and setters.
Create the following methods in the Hall class,
Method Description
In this method, get the list of hall details as parame
static void writeHallDetails(List<Hall> halls) write the hall details to hall.csv file as comma-sepa
(name,contact,costPerDay,owner)
Input Format:
The next line of the input corresponds to the total number of halls 'n'.
The next 'n' line of input contains hall details (name, contact,costperday, and owner separated by
comma[,]).
Output Format:
The output is hall.csv file with hall details.
The hall.csv file consists of hall details separated by commas[,] in order (name,contact,costPerDay,
owner).
Refer to sample output for formatting specifications.
Sample Output:
hall.csv
Party hall,9876543210,4000.0,Jarviz
Disco hall,9876543201,5000.0,Starc
Dining hall,9873216540,3000.0,Chris
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
Hall.writeHallDetails(hallsList);
}
When the file is given as input, read each line, split it into a number of fields using substring() as per
the size of each field then use trim() to get only the variable and removing the unwanted spaces. Note
that the trim() method only removes spaces in the starting and ending of the word and not in
between.
Now in our application, it is normal to have all the records stored in a file. When we want to enter the
content of the file into the application, we cannot enter each detail in the console one by one. So we
must develop a program that can parse the details in the file into required objects.
Now we have got a situation where all the event details we want are in a file. So we want to read all
the details in it and store them as objects.
Write a program to do this and also to display the events organized by specific persons.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Input format:
The first line of the input is the name of the organiser.
Read all the details of that organiser from the input file.
The input file is "input.csv". The sizes of fields in the fixed-length file are,
Field Size
name 0-19
details 19-39
type 39-51
organiser 51-61
attendeesCount 61-67
projectedExpense 67-74
Output format:
Use "%-15s%-20s%-15s%-15s%-15s" to display details in tabular format.
Print "The given person has no upcoming events" if the person is not in the file.
Refer to sample output for other further details and format of the output.
}
}
public Event(String name, String detail, String type, String organiser, int attendeesCont,
double projectedExpense) {
super();
this.name = name;
this.detail = detail;
this.type = type;
this.organiser = organiser;
this.attendeesCont = attendeesCont;
this.projectedExpense = projectedExpense;
}
@Override
public String toString() {
return String.format("%-15s%-20s%-15s%-15s%-
15s\n",this.getName(),this.getDetail(),this.type,this.attendeesCont,this.projectedExpense);
}
import java.io.BufferedReader;
import java.util.ArrayList;
Let's get more practice in reading data from fixed-length format files. You are provided with ItemType
details in "input.txt". Write a program that reads the file and displays the contents of the file in the
required format. The length and position of attributes are as follows.
Attribute Length Position
name 15 1
deposit 7 16
costPerDay 5 22
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create an ItemType class with following private attributes
Attribute Datatype
name String
deposit Double
costPerDay Double
Include appropriate default constructor, getters and setters for the attributes of the Item class.
Include a parameterized Constructor for the ItemType class.
Create a driver class called Main. If the list of ItemType objects that have a deposit amount greater
than 2000, then print "No item type has deposit more than 2000" in the main method. Else print the
details of the ItemType.
Input format:
Read the details from the input file "input.txt"
Output format:
Use "%-15s %-15s %s\n" for displaying ItemType details in tabular form in the console
Print one digit after the decimal for the double datatype.
Print the statement for the heading of the details is present in the main method.
Refer to the sample output for the formatting specifications.
Sample Input:
Sample Output :
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
if(itList1.isEmpty()) {
}else {
it.display(itList1);
public ItemType() {
super();
}
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
for(int i=0;i<list.size();i++) {
System.out.printf("%-15s %-15s %s\n"
,list.get(i).getName(),list.get(i).getDeposit(),list.get(i).getCostPerDay());
}
}
}
Serialize Customer
During IO Journey, we started off by character level read-write and then byte level read-
write. Java also has yet another unique option of persisting data / objects. An Object can
be directly saved into a file and can be later reloaded. This process is called Serialization
and the restoration is called De-serialization. The extension of the file is ".ser".
An Object is considered ready for serialization if its class implements Serializable
Interface.
Serializable Interface is called Marker Interface. A Marker Interface is one which has no
methods and member variables, but just indicates / marks that the given class is
implementing the Interface.
Use ObjectOutputStream class for converting an object to serialized file.
Quickly, write a code to serialize a customer object, get the customer details from the
console and store the customer object into a file called “Serialize.ser”. Class
must implement Serializable.
Input and Output Format:
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output]
Enter the Customer name
Amarnath
Enter the Customer number
12
Enter the Customer address
Coimbatore
Read and Write
In our application, we are gonna read the contents of a file and write it into another file with some
conditions. There can be many events for the same organization or owner. But we want only one
event for every owner available. So we are gonna read the event details from the file "input.txt" and
then write the event details into "output.txt" but after removal of duplicate entries.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create a class Event with the following private attributes
Attributes Datatype
eventName String
attendeesCount Integer
ownerName String
Include appropriate getters and setters
Create default constructor and a parameterized constructor with arguments in order Event(String
eventName, Integer attendeesCount, String ownerName).
Create a class EventBO to access the above class. Include the following public methods.
Method Description
This method accepts the BufferedReader object as
public List<Event> readFromFile(BufferedReader br)
and then adds them to a list. Finally, it returns the l
This method takes event list and file writer as the a
void writeFile(List<Event> eventList,FileWriter fr)
the removal of duplicate event details (i.e) an even
Create a driver class named Main which reads data from console and to test the above class.
Input:
Read the contents[event details] from the file "input.txt".
Output:
Write the contents[event details] with the removal of duplicate events into the "output.txt".
Use a treemap so that the order of the itemtype remains the same.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Input format:
The input file is "input.csv". The sizes of fields in the fixed-length file are,
Field Size
name 0-9
itemType name 9-24
vendor 24-34
Output format:
Print the name of the ItemType and its total count.
Sample Input: (input.csv)
Sample Output:
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create a class ItemBO to access the above class. Include the following public methods.
Method Description
This method takes BufferedReader
that contains a CSV file "input.csv" which consists of
List<Item> readFile(BufferedReader br)
(Item Number,Vendor,Item Type Name,Cost).
It store item details it in a list and returns it.
Output Format:
The output consists of item details in the format of System.out.format("%-20s %-20s %-20s %s\n",
"Item Number","Vendor Name","Item Type","Cost").
Refer to sample output for formatting specifications.
Sample Output1:
Item Number Vendor Name Item Type Cost
1 Martin Leather 2000.0
15 Louis Mud 1300.5
23 Jaques kallis Electronics 100.0
38 McCullum Wood 3000.4
Sample Output:
Java Interfaces
Consider a Banking Scenario, There are many accounts, like Savings Account, Current Account,
Demat Account and so on. We have a base Class Account which contains all the basic properties and
methods of an Account. We do have some Maintainance Charges that apply to only some of the
accounts. If you would like to enforce that the Savings Account & Current Account should have
maintenance charges, then the simplest way is to ask your class implement the interface. If you do
not implement the method in the class, it would raise a compilation error.
So, Java Interfaces essentially gives acts like a contract where its given that the methods declared in
the interface has to be implemented in the class. Lets code the above Scenario.
Create a class named Account with following private attributes
Attribute Datatype
name String
accountNumber String
balance double
startDate String
Include appropriate getters and setters.
Include appropriate parameterized constructors
@Override
class Account {
String name;
String accountNumber;
double balance;
String startDate;
super();
this.name = name;
this.accountNumber = accountNumber;
this.balance = balance;
this.startDate = startDate;
return name;
this.name = name;
return accountNumber;
this.accountNumber = accountNumber;
return balance;
this.balance = balance;
return startDate;
@Override
import java.text.DecimalFormat;
import java.util.*;
double accountBalance;
int years;
System.out.println("1.Current Account");
System.out.println("2.Savings Account");
int n = s.nextInt();
switch (n) {
case 1:
System.out.println("Name");
name = s.next();
System.out.println("Account Number");
account = s.next();
System.out.println("Account Balance");
accountBalance = s.nextInt();
s.nextLine();
sdate = s.nextLine();
years = s.nextInt();
System.out
break;
case 2:
System.out.println("Name");
name = s.next();
System.out.println("Account Number");
account = s.next();
System.out.println("Account Balance");
accountBalance = s.nextInt();
s.nextLine();
sdate = s.nextLine();
years = s.nextInt();
System.out
.println("Maintenance Charge For Savings Account " +
df.format(sa.calculateMaintanceCharge(years)));
break;
default:
System.out.println("Invalid choice");
break;
Interface
The Interface defines a rule that any classes that implement it should override all the methods. Let's
implement Interface in our application. We'll start simple, by including display method in the Stall
interface. Now all types of stalls that implement the interface should override the method.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Input Format:
The first input corresponds to choose the stall type.
The next line of input corresponds to the details of the stall in CSV format according to the stall type.
Output Format:
Print “Invalid Stall Type” if the user has chosen the stall type other than the given type
Otherwise, display the details of the stall.
Refer to sample output for formatting specifications.
Note: All Texts in bold corresponds to the input and rest are output
ChooseStall Type
1)Gold Stall
2)Premium Stall
3)Executive Stall
2
Enter Stall details in comma separated(Stall Name,Stall Cost,Owner Name,Number of Projectors)
Knitting plaza,300000,Zain,20
Stall Name:Knitting plaza
Cost:300000.Rs
Owner Name:Zain
Number of Projectors:20
ChooseStall Type
1)Gold Stall
2)Premium Stall
3)Executive Stall
3
Enter Stall details in comma separated(Stall Name,Stall Cost,Owner Name,Number of Screens)
Fruits Hunt,10000,Uber,7
Stall Name:Fruits Hunt
Cost:10000.Rs
Owner Name:Uber
Number of Screens:7
ChooseStall Type
1)Gold Stall
2)Premium Stall
3)Executive Stall
4
Invalid Stall Type
public PremiumStall() {
public ExecutiveStall() {
}
import java.util.Scanner;
switch (n) {
case 1:
scan.nextLine();
System.out.println(
"Enter Stall details in comma separated(Stall Name,Stall
Cost,Owner Name,Number of TV sets)");
stallDetails = scan.nextLine();
arr = stallDetails.split(",");
break;
case 2:
scan.nextLine();
System.out.println(
"Enter Stall details in comma separated(Stall Name,Stall
Cost,Owner Name,Number of Projectors)");
stallDetails = scan.nextLine();
arr = stallDetails.split(",");
cost = Integer.parseInt(arr[1]);
num = Integer.parseInt(arr[3]);
stallDetails = scan.nextLine();
arr = stallDetails.split(",");
cost = Integer.parseInt(arr[1]);
num = Integer.parseInt(arr[3]);
}
}
public class GoldStall implements Stall {
Round up - Interfaces
In one of the earlier exercises in Interfaces, we looked at how banks encrypt & decrypt transaction
details to ensure safety. We also saw understood that each of them complies with the methods
specified by the Governing Agency in the form of an interface. To Round-off interfaces, let's look at a
similar example, where the governing agency mandates that any customer who performs a
transaction has to be notified through SMS, Email and a monthly e-statement. As expected, we define
an interface Notification and three methods as specified below. Lets code this example.
Create an interface named Notification with the following methods
notificationBySms( ),
notificationByEmail( ),
notificationByCourier( ).
Create a class named ICICI which implements Notification interface
Create a class named HDFC which implements Notification interface
[Note: All text in bold corresponds to the input and remaining text corresponds to output]
@Override
public void notificationBySms() {
System.out.println("ICICI - Notification By SMS");
}
@Override
public void notificationByEmail() {
System.out.println("ICICI - Notification By Mail");
}
@Override
public void notificationByCourier() {
System.out.println("ICICI - Notification By Courier");
}
}
public class HDFC implements Notification {
@Override
public void notificationBySms() {
System.out.println("HDFC - Notification By SMS");
}
@Override
public void notificationByEmail() {
System.out.println("HDFC - Notification By Mail");
}
@Override
public void notificationByCourier() {
System.out.println("HDFC - Notification By Courier");
}
}
public interface Notification {
}
public class BankFactory {
Get the option for the shape to compute the area and get the attribute according to the shape option
and set the values to the Shape class attributes. Calculate the area and print the area.
While printing round off the area to 2 decimal formats.
[Note: Strictly adhere to the object-oriented specifications given as a part of the problem statement.
Use the same class names, attribute names and method names]
Input Format
The first line of the input is an integer corresponds to the shape.
The next line of inputs are Double which corresponds to,
For Rectangle(Option 1) get the length and breadth.
For Triangle(Option 2) get the base and height.
Output Format
The output consists area of the shape.
Print the double value correct to two decimal places.
Print “Invalid choice”, if the option for the shape is chosen other than the given options.
Refer to sample output for formatting specifications.
Sample Input/Output 2:
Enter the shape
1.Rectangle
2.Triangle
2
Enter the base and height:
15
19
Area of triangle is 142.50
Sample Input/Output 3:
Enter the shape
1.Rectangle
2.Triangle
3
Invalid choice
Single inheritance
Write a Java program to implement Single Inheritance.
[Note : Strictly adhere to the object oriented specifications given as a part of the problem statement.
Use the same class names and member variable names.
Follow the naming conventions mentioned for getters / setters. Create separate classes in separate
files. Do not create the classes within namespaces]
Create a class named Donor which extends Person class with the following private data members.
Data Type Data Member
String bloodBankName
String donorType
String donationDate
Include appropriate getters and setters.
Create an another class Main and write a main method to test the above class.
In the main( ) method, read the person and donor details from the user and call the
displayDonationDetails( ) method.
Sample Input/Output:
Enter the name :
Justin
Enter Date of Birth :
11-01-1995
Enter Gender :
Male
Enter Mobile Number :
9994910354
Enter Blood Group :
B+ve
Enter Blood Bank Name :
Blood Assurance
Enter Donor Type :
Whole Blood
Enter Donation Date :
09-07-2017
Donation Details :
Name : Justin
Date Of Birth : 11-01-1995
Gender : Male
Mobile Number : 9994910354
Blood Group : B+ve
Blood Bank Name : Blood Assurance
Donor Type : Whole Blood
Donation Date : 09-07-2017
public Donor() {
return bloodBankName;
this.bloodBankName = bloodBankName;
return donorType;
this.donorType = donorType;
this.donationDate = donationDate;
System.out.println("Name : "+getName());
System.out.println("Gender : "+getGender());
class Person{
Person(){
}
return name;
this.name = name;
return dateOfBirth;
this.dateOfBirth = dateOfBirth;
return gender;
}
public void setGender(String gender) {
this.gender = gender;
return mobileNumber;
this.mobileNumber = mobileNumber;
return bloodGroup;
this.bloodGroup = bloodGroup;
}
import java.util.Scanner;
d.setName(sc.nextLine());
d.setDateOfBirth(sc.nextLine());
d.setGender(sc.nextLine());
d.setMobileNumber(sc.nextLine());
d.setBloodGroup(sc.nextLine());
d.setBloodBankName(sc.nextLine());
d.setDonorType(sc.nextLine());
d.displayDonationDetails();
ABC Bank announced a new scheme of reward points for a transaction using an ATM card. Each
transaction using the normal card will be provided by 1% of the transaction amount as reward point.
If a transaction is made using a premium card and it is for fuel expenses, additional 10 points will be
rewarded. Help the bank to calculate the total reward points.
Create a class VISACard with the following method.
Method Description
public double computeRewardPoints(String type, double amount) This method returns the 1% of the transac
Hint:
Use super keyword to calculate reward points from base class.
Card type will be either ‘VISA card’ or ‘HPVISA card’. Otherwise, display ‘Invalid data’
Calculate the reward points corresponding to the card type and transaction type and print the reward
points(upto two precision).
}
class HPVISACard extends VISACard{
if(type.equalsIgnoreCase("Fuel")) {
total=total+10;
return total;
}else{
return total;
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
double amount = 0;
do {
tDetails = sc.nextLine();
transactionType = dSplit[0];
amount = Double.parseDouble(dSplit[1]);
cardType = dSplit[2];
DecimalFormat df = new DecimalFormat("0.00");
if (cardType.equals("VISA card")) {
+ df.format(v.computeRewardPoints(transactionType, amount)));
flag = sc.nextLine();
+ df.format(h.computeRewardPoints(transactionType, amount)));
flag = sc.nextLine();
} else {
System.out.println("Invalid data");
flag = sc.nextLine();
} while (flag.equals("Yes"));
GST Calculation
[Note :
Strictly adhere to the object oriented specifications given as a part of the problem statement.
Follow the naming conventions as mentioned. Create separate classes in separate files.]
Write a program to calculate the total amount with GST for the events. There are two types of Events
Stage show and Exhibition. For Stage show GST will be 15% and for exhibition GST will be 5%
Create Main class with main method.
In the main() method, read the event details from the user and then create the object of the event
according to the event type.
The total amount will be calculated according to the GST of the corresponding event. Display the
total amount upto two precision.
import java.util.*;
import java.text.DecimalFormat;
int npd;
name = sc.nextLine();
cpd = sc.nextDouble();
npd = sc.nextInt();
sc.nextLine();
type = sc.nextLine();
switch (type) {
case "1":
break;
case "2":
break;
default:
System.out.println("Invalid input");
break;
}
}
class Event{
super();
this.name = name;
this.type = type;
this.costPerDay = costPerDay;
this.noOfDays = noOfDays;
int noOfSeats;
public StageEvent(String name, String type, double costPerDay, int noOfDays, int noOfSeats) {
this.noOfSeats = noOfSeats;
return total;
}
@Override
int noOfStalls;
public Exhibition(String name, String type, double costPerDay, int noOfDays, int noOfStalls) {
this.noOfStalls = noOfStalls;
return total;
@Override
Abstract Event
Let's have a practice in creating an Abstract class for the Event. In this application create an abstract
class Event, StageEvent class and a class Exhibition with the provided attributes and let's implement
an abstract method to calculate the total cost of the event and print the details of the particular event
of this application.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Create a driver class called Main. In the main method, obtain input from the user and create objects
accordingly.
Input format:
Input format for Exhibition is in the CSV format (name,detail,type,organiser,noOfStalls,rentPerStall)
Input format for StageEvent is in the CSV
format (name,detail,type,organiser,noOfShows,costPerShow)
Output format:
Print "Invalid choice" if the input is invalid to our application and terminate.
Display one digit after the decimal point for Double datatype.
Refer to sample Input and Output for formatting specifications.
Note: All text in bold corresponds to the input and rest corresponds to output.
public Exhibition(String name, String detail, String type, String organiser, Integer noOfStalls,
Double rentPerStall) {
this.noOfStalls = noOfStalls;
this.rentPerStall = rentPerStall;
Double calculateAmount() {
public StageEvent(String name, String detail, String type, String organiser, Integer noOfShows,
Double costPerShow) {
this.noOfShows = noOfShows;
this.costPerShow = costPerShow;
Double calculateAmount() {
this.name = name;
this.detail = detail;
this.type = type;
this.organiser = organiser;
return name;
this.name = name;
return detail;
this.detail = detail;
return type;
}
public void setType(String type) {
this.type = type;
return organiser;
this.organiser = organiser;
import java.util.Scanner;
System.out.println("1.Exhibition");
System.out.println("2.StageEvent");
int ch = sc.nextInt();
switch (ch) {
case 1:
sc.nextLine();
s = sc.nextLine();
name = split[0];
detail = split[1];
type = split[2];
organiser = split[3];
noOfStalls = Integer.parseInt(split[4]);
rentPerStall = Double.parseDouble(split[5]);
totalCost = e.calculateAmount();
System.out.println("Exhibition Details");
System.out.println("Detail:" + e.getDetail());
System.out.println("Type:" + e.getType());
break;
case 2:
sc.nextLine();
s = sc.nextLine();
name = split1[0];
detail = split1[1];
type = split1[2];
organiser = split1[3];
noOfShows = Integer.parseInt(split1[4]);
costPerShow = Double.parseDouble(split1[5]);
totalCost = se.calculateAmount();
System.out.println("Detail:" + se.getDetail());
System.out.println("Type:" + se.getType());
default:
System.out.println("Invalid choice");
break;
Overriding-simple
Overriding is another concept that every application developer should know. Overriding is a runtime
polymorphism. The inherited class has the overridden method which has the same name as the
method in the parent class. The argument number, types or return types should not differ in any case.
The method is invoked with the object of the specific class ( but with the reference of the parent
class).
Now let's try out a simple overriding concept in our application. For this, we can take our original
example of Class Event, and its child classes Exhibition and StageEvent.
[All Texts in bold corresponds to the input and rest are output]
Sample Input/Output 1:
Sample Input/Output 2:
public StageEvent()
{}
super(name,detail,ownerName);
this.name = name;
this.detail = detail;
this.ownerName = ownerName;
this.noOfShows = noOfShows;
this.noOfSeatsPerShow = noOfSeatsPerShow;
@Override
return revenue;
this.name = name;
this.detail = detail;
this.ownerName = ownerName;
return 0.0;
import java.io.IOException;
import java.util.Scanner;
double totalrevenue = 0;
switch(choice){
case 1 :
totalrevenue = exObj.projectedRevenue();
break;
case 2 :
totalrevenue = seObj.projectedRevenue();
break;
default : break;
public Exhibition()
super(name,detail,ownerName);
this.name = name;
this.detail = detail;
this.ownerName = ownerName;
this.noOfStalls = noOfStalls;
@Override
return revenue;
}
Write a java program to find the duplicate mobile number using the exception handling mechanism.
Strictly adhere to the Object-Oriented specifications given in the problem statement. All class
names, attribute names and method names should be the same as specified in the problem
statement.
Attributes Datatype
mobile String
alternateMobile String
landLine String
email String
address String
Create a driver class called Main. In the Main method, obtain inputs from the user. Validate the
mobile and alternateMobile and display the ContactDetail if no exception occurs else handle the
exception.
Pass the exception message as "Mobile number and alternate mobile number are same". If mobile
and alternateMobile are the same.
Note: All text in bold corresponds to the input and rest corresponds to the output.
public DuplicateMobileNumberException(String s)
super(s);
return "DuplicateMobileNumberException: Mobile number and alternate mobile number are same ";
}
public class ContactDetailBO {
if (mobile.equals(alternateMobile)) {
}-----------
public ContactDetail(String mobile, String alternateMobile, String landLine, String email, String address) {
this.mobile = mobile;
this.alternateMobile = alternateMobile;
this.landLine = landLine;
this.email = email;
this.address = address;
public ContactDetail()
return mobile;
this.mobile = mobile;
}
public String getAlternateMobile() {
return alternateMobile;
this.alternateMobile = alternateMobile;
return landLine;
this.landLine = landLine;
return email;
this.email = email;
return address;
this.address = address;
return "Mobile:"+this.mobile+"\nAlternate
mobile:"+this.alternateMobile+"\nLandLine:"+this.landLine+"\nEmail:"+this.email+"\nAddress:"+this.address;
import java.io.*;
String st = br.readLine();
try {
BO.validate(str[0], str[1]);
System.out.println(userInfo.toString());
} catch (DuplicateMobileNumberException e) {
System.out.println(e.toString());
SeatNotAvailableException
An organization is organizing a charity fate for the well being of poor kids. Since the manager was
running short on time, he asked you to help him with the ticket bookings. You being from a
programming background decide to design a program that asks the user about the seat number they
want. Seat booking details are stored in an array. If the seat number requested is available booking
should be done else print the message " SeatNotAvailableException". If the seat number requested is
not in the range throws an exception ArrayIndexOutOfBoundsException.
Create an array of size n*n (n rows each with n seats) which is got from the user. Get the tickets to be
booked from the user and handle any exception that occurs in Main Class. (Take seat numbers from 0
to (n*n)-1)
Note: Vacant seats are denoted by (0) and booked seats by (1). Show message as "Already Booked"
as a Custom exception.
[All Texts in bold corresponds to the input and rest are output]
Sample Input and Output 1:
public SeatNotAvailableException(String s) {
super(s);
}
}
----------------------------------------------------------------------------------------------------------
import java.util.Scanner;
import java.io.*;
int n = sc.nextInt();
int s;
try {
for(int i=0;i<seats;i++) {
s = sc.nextInt();
if(a[s]==0) {
a[s] =1;
int t=0;
for(int j=0;j<n;j++) {
for(int k=0;k<n;k++) {
mat[j][k] = a[t];
t++;
}else {
}catch (Exception e) {
System.out.println(e);
finally {
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
System.out.print(mat[i][j]+" ");
System.out.println();
Parse Exception
For our application, we would have obtained date inputs. If the user enters a different format other
than specified, an Invalid Date Exception occurs and the program is interrupted. To avoid that, handle
the exception and prompt the user to enter the right format as specified.
Create a driver class called Main. In the main method, Obtain start time and end time for stage event
show, if an exception occurs, handle the exception and notify the user about the right format.
Input format:
The input consists of the start date and end date.
The format for the date is dd-MM-yyyy-HH:mm:ss
Output format:
Refer sample Input and Output for formatting specifications
Note: All text in bold corresponds to the input and rest corresponds to the output.
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
try{
d=s.next();
String d2=sdf.format(sdf.parse(d));
d1 =s.next();
String d3=sdf.format(sdf.parse(d1));
System.out.println("Start date:"+d2);
System.out.println("End date:"+d3);
}catch (ParseException e) {
Arithmetic Exception
An exception is an unwanted or unexpected event, which occurs during the execution of a program
i.e at runtime, it disrupts the normal flow of the program. For example, there are 10 statements in
your program and there occurs an exception at statement 5, the rest of the code will not be executed
i.e. statement 6 to 10 will not run. If we perform exception handling, the rest of the statement will be
executed. That is why we use exception handling.
For practice in exception handling, obtain the cost for 'n' days of an item and n as input and calculate
the cost per day for the item. In case, zero is given as input for n, an arithmetic exception is thrown,
handle the exception and prompt the user accordingly.
Create a driver class called Main. In the Main method, obtain input from the user and store the values
in int type. Handle exception if one occurs.
Input format:
The first line of input is an integer which corresponds to the cost of the item for n days.
The second line of input is an integer which corresponds to the value n.
Output format:
If the value of n is zero throws an exception.
Otherwise, print the integer output which corresponds to the cost per day of the item.
NOTE: All text in bold corresponds to the input and rest corresponds to the output.
import java.util.*;
try{
int cost = days/num;
}catch(ArithmeticException e){
System.out.println(e);
ArrayIndexOutOfBoundsException
The next prominent exception which you will see is ArrayIndexOutOfBoundsException. It occurs
when the program tries to access the array beyond its size. As we know arrays have fixed size. So
when you try to use array beyond its size it throws this exception. Let's try to handle this exception.
Handling this exception will also prove to be good for our application. For example, if there are only
100 seats in the event and the user tries to book the 105th seat, it will throw this exception. So you
must handle it to do a specific job.
Create an array of size 100 and assume it as seat array. Get the tickets to be booked from the
user and handle any exception that occurs in Main Class. At last display all the tickets booked.
Note: All Texts in bold corresponds to the input and rest are output.
import java.util.Scanner;
int n,count = 1;
n = sc.nextInt();
try{
for(int i=0;i<n;i++) {
count = sc.nextInt();
seatArray[count-1] = count;
if(seatArray[i] != 0){
System.out.println(seatArray[i]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
PROBLEM
1 Fill up the blank to complete the code. public class MyClass { public static void main(String[] a...
3 Can we use the .class files outside the system to execute anywhere?
Can we use the .class files outside the system to execute anywhere?
1)
Yes
2)
No
5 Which keyword is used to import a package from the Java API library?
Which keyword is used to import a package from the Java API library?
1)
getlib
2)
lib
3)
package
4)
import
6 Predict the output for the below code snippet? public class Main { public static void main(String...
7 Predict the type of error in the below code. public class Main { public static void main(string a...
PROBLEM
3 Predict the output for the below code. public class Main { public static void main(String[] args)...
}
}
1)
Java Programming
2)
Nothing will be displayed
3)
throws an error
4)
//Java Programming
4 Predict the output for the below code snippet? public class Main { public static void main(String...
}
}
1)
Java
Multi
PROBLEM
line
comment
Hello
2)
Hello
3)
/*Java
Multi
line
comment*/
Hello
4)
None of the mentioned options
7 Consider the below code snippet which is saved in the file named Main.java. When we try to execut...
Consider the below code snippet which is saved in the file named Main.java. When we try to execute it, what will
class Sample {
public static void Main(String[] args){
}
}
1)
Not able to execute
2)
Throws an error
3)
Successfully executed
4)
Throws an exception
9 Which is used to convert the java code into machine, when the program is run?
Which is used to convert the java code into machine, when the program is run?
1)
interpreter
2)
compiler
3)
JVM
4)
JRE
11 Consider the below code snippet and predict whether it can execute or not. public class Main { pu...
Consider the below code snippet and predict whether it can execute or not.
}
}
1)
Yes
2)
No
}
2)
public class Main {
}
3)
public class Main {
PROBLEM
}
4)
public class Main {
14 What are all the errors which occur after successful compilation?
What are all the errors which occur after successful compilation?
1)
runtime error
2)
logical error
3)
syntax error
4)
None of the mentioned options
15 Consider the java file with the extension Main.Java. If we compile Main.Java, what will we get?
Consider the java file with the extension Main.Java. If we compile Main.Java, what will we get?
PROBLEM
1)
successful compilation
2)
throws an error
3)
warning
4)
None of the mentioned options
PROBLEM
1 Determine the output of the code. interface A { } class C { } class D extends C { } class ...
PROBLEM
Determine the output of the code.
interface A { }
class C { }
class D extends C { }
1)
b is an instance of A
2)
b is an instance of C
3)
Compilation error
4)
b is an instance of A
b is an instance of C
1)
static
2)
final
3)
PROBLEM
protected
4)
constant
1)
public
2)
protected
3)
private
4)
All of the listed options
4 Which of the following is true considering the code, public interface A { void method(); ...
1)
will not compile as B does not implement the method in A
2)
will not compile as method is not declared as abstract in B
3)
will not compile as A should use extendes not implementes in B.
4)
will compile fine
1)
A class can extend more than one class.
2)
A class can extend only one class but many interfaces.
PROBLEM
3)
An interface can implement many interfaces.
4)
A class can extend one class and implement many interfaces.
1)
interface
2)
Interface
3)
intf
4)
Intf
7 What is the output of this program? public interface TestInf { int i =10; } public class...
1)
10
2)
12
3)
compilation error
4)
PROBLEM
1)
False
2)
True
1)
static
2)
private
3)
abstract
4)
None of the listed options
10 What is the output of this program? interface A { void display(); } interface B extends ...
t.display();
}
}
1)
compilation error as B extends A and does not implement method display
2)
compilation error as B does not implements A
3)
runtime exception
4)
Hi
11 What is the output of this program? public interface A { protected String getName(); } p...
1)
name
2)
compilation error due to protected method
3)
compilation error in method definition
4)
PROBLEM
1)
extend many class
2)
extend many interface
3)
implement many interfaces
4)
implement many classes
1)
Serializable
2)
Runnable
3)
All of the listed options
4)
None of the listed options
14 Which of the following is the correct syntax for implementing an interface A by class B?
Which of the following is the correct syntax for implementing an interface A by class B?
1)
B extends A
2)
B import A
3)
B implement A
4)
B implements A
1)
True
2)
False
1 What will be the output for the following code snippet? static int computeDivision(int a, int...
1)
/ by zero
2)
NumberFormatException
3)
i value is printed
4)
NullPointerException
2 What will be the output for the following code snippet? try { int data=25/0; System....
try {
int data=25/0;
System.out.print(data + " ");
}
catch(Exception e) {
System.out.print("Exception ");
}
finally {
System.out.println("finally block ");
}
System.out.println("Further code...");
1)
Further code...
2)
finally block Further code...
3)
Exception finally block
Further code...
4)
CompileTime Error
getMessage()
3)
toString()
4)
All
7 Which of the following handles the exception when catch is not used?
Which of the following handles the exception when catch is not used?
1)
finally
2)
throw handler
3)
default handler
4)
java run time system
PROBLEM
9 For each try block there can be zero or more catch blocks and one or more finally block.
For each try block there can be zero or more catch blocks and one or more finally block.
1)
true
2)
false
10 What will be the output for the following code snippet? try { System.out.printf("1"); ...
System.out.printf("3");
}
System.out.printf("4");
1)
RunTime Exception
2)
CompileTime Error
3)
134
4)
1834
11 Which of the following is a super class of all exception type classes?
13 At a time only one Exception is occured and at a time only one catch block is executed.
At a time only one Exception is occured and at a time only one catch block is executed.
1)
PROBLEM
true
2)
false
14 What will be the output for the following code snippet? try { int n = 100/0; System.o...
1)
java.lang.ArithmeticException: / by zero
2)
java.lang.ArithmeticException
3)
1
4)
CompileTime Error
15 What will be the output for the following code snippet? try{ int a[]=new int[2]; a[2]=2/0; } catc...
try{
int a[]=new int[2];
a[2]=2/0;
}
catch(ArithmeticException e){System.out.print("ArithmeticException ");}
catch(ArrayIndexOutOfBoundsException e){System.out.print("ArrayIndexOutOfBoundsException ");}
catch(Exception e){System.out.print("Exception ");}
System.out.print("Further Code");
1)
ArithmeticException Further Code
2)
ArrayIndexOutOfBoundsException Further Code
PROBLEM
3)
Exception Further Code
4)
CompileTimeError
16 What will be the output for the following code snippet? static void validate(int age) { i...
1)
Arithmetic Exception
2)
Not Valid Further code...
3)
Further code...
4)
Compile Time Error
17 What will be the output for the following code snippet? try { int a[]=new int[2]; a[2...
a[2]=2/0;
}
catch(Exception e) {
System.out.print("Exception ");
}
catch(ArithmeticException e) {
System.out.print("ArithmeticException ");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.print("ArrayIndexOutOfBoundsException ");
}
System.out.print("Further Code");
1)
ArithmeticException Further Code
2)
ArrayIndexOutOfBoundsException Further Code
3)
Exception Further Code
4)
CompileTimeError
18 What will happen when p() method is called? void m() { throw new java.io.IOException("dev...
catch(Exception e) {
System.out.println("Exception handled");
}
}
1)
Exception handled
2)
CompileTime Error
3)
No exception occurred
4)
None of the listed options
20 What will be the output for the following code snippet? try { int num=Integer.parseInt ("...
1)
Arithmetic Exception
2)
NumberFormatException
3)
XYZ
4)
num
PROBLEM
1 Output for the below code snippet Date d; SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yy...
1)
compile error
2)
04-03-2018
3)
14-04-2018
4)
14-03-2018
1)
Java3Quiz7
2)
Java3Quiz34
3)
Java12Quiz34
4)
Java12Quiz7
3 Output for the below code snippet String s1 = "one"; StringBuffer sb = new StringBuffer(s1); ...
1)
one
2)
PROBLEM
two
3)
onetwo
4)
twoone
4 What is the value returned by function compareTo() if the invoking string is less than the string...
What is the value returned by function compareTo() if the invoking string is less than the string compared?
1)
zero
2)
value greater than zero
3)
value less than zero
4)
None of the listed options
5 Output for the below code snippet try{ String s1 = null; System.out.print(s1+" "); ...
1)
null null
2)
null NullPointerException
3)
NullPointerException NullPointerException
4)
NullPointerException
6 Output for the below code snippet String s1 = "abc"; String s2 = "def"; System.out.println(s1...
PROBLEM
Output for the below code snippet
String s1 = "abc";
String s2 = "def";
System.out.println(s1.compareTo(s2));
1)
false
2)
true
3)
0
4)
-3
7 Which of these method of class String is used to remove leading and trailing whitespaces?
Which of these method of class String is used to remove leading and trailing whitespaces?
1)
startsWith()
2)
trim()
3)
Trim()
4)
doTrim()
8 Output for the below code snippet String s = "Java String Quiz"; System.out.println(s.charAt(...
1)
Runtime Exception
2)
Prints "z"
3)
Prints "Z"
4)
Convert "Z" to int 90 and prints "90"
PROBLEM
9 Output for the below code snippet String s1 = " Hey, buddy! "; s1=s1.trim(); System.out.print...
1)
8
2)
10
3)
11
4)
12
10 Output for the below code snippet<br /> String s=" Hello World "; System.out.print(s.length()...
1)
13 11
2)
13 10
3)
11 10
4)
13 13
11 Output for the below code snippet String str = null; if(str.length() == 0){ System.out.print("1")...
13 Which of the following is used to format the date from one form to another?
Which of the following is used to format the date from one form to another?
1)
SimpleDateFormat
2)
DateFormat
3)
SimpleFormat
4)
DateConverter
14 What will the Output for the below code snippet? System.out.println("13" + 5 + 3);
System.out.println("13" + 5 + 3);
1)
21
2)
138
3)
1353
4)
compile-time error
15 Which of these method of class String is used to check whether a given object starts with a parti...
Which of these method of class String is used to check whether a given object starts with a particular string litera
1)
startsWith()
2)
endsWith()
3)
Starts()
4)
ends()
16 Output for the below code snippet Date d; SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yy...
1)
04-03-2018
2)
Error
3)
14-04-2018
4)
14-03-2018
PROBLEM
17 Output for the below code snippet String s = "String Quiz"; System.out.println(s.charAt(s.toL...
1)
Runtime Exception
2)
Prints "z"
3)
Prints "Z"
4)
Converts "Z" to int 90 and prints "90"
19 Output for the below code snippet. StringBuilder sb=new StringBuilder("Hello World"); sb.delete...
1)
Ho World
2)
Hlo World
3)
Hello World
PROBLEM
4)
Hello Wd
TOTAL SCORE: 100.0%
PROBLEM
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
True
2)
False
2 The read() method in BufferedReader class return which of the following data type
The read() method in BufferedReader class return which of the following data type
PROBLEM
1)
char
2)
String
3)
int
4)
try {
FileInputStream fin=new FileInputStream("output.txt");
int i=0;
while((i=fin.read())!=-1) {
System.out.print((char)i);
}
fin.close();
}
catch(Exception e) {
System.out.println(e);
}
what will be the output of the above code snippet if the output.txt file contains the following line?
output.txt
Welcome
1)
871011089911110910110
2)
Welcome
3)
compilerError
4)
success
PROBLEM
FileReader
2)
FileWriter
3)
FileInputStream
4)
InputStreamReader
5 StringReader takes an input ______ and changes it into ______ stream
character,String
2)
String,integer
3)
integer,character
4)
String,character
6 try { FileOutputStream fileOut=new FileOutputStream("output.txt"); fileOut.write(66); ...
try {
FileOutputStream fileOut=new FileOutputStream("output.txt");
fileOut.write(66);
fileOut.close();
System.out.println("success");
}
catch(Exception e) {
System.out.println(e);
}
PROBLEM
What will be the content in output.txt for the above code snippet?
1)
66
2)
A
3)
B
4)
success
7 Which of the following FileReader class has? A)read() B)close() C)readLine() D)readByte()
A)read()
B)close()
C)readLine()
D)readByte()
1)
A
2)
A and B
3)
A, B and C
4)
A,B,C and D
8 The getBuffer() method in StringWriter class returns ______
String
2)
byte
3)
char
4)
StringBuffer
PROBLEM
True
2)
False
10 Reader and Writer is a
class
2)
Interface
3)
Abstract class
4)
To read input from the keyboard ______ class present in java.util package.
1)
java.util
2)
java.net
3)
java.io
4)
java.awt
12 InputStreamReader reader = new InputStreamReader(System.in); In above object creation "in" is an ...
System
2)
PROBLEM
Reader
3)
InputStream
4)
StringReader
13 Which of these class is used to read input bytes from a file in a file system.
Which of these class is used to read input bytes from a file in a file system.
1)
FileReader
2)
FileWriter
3)
FileInputStream
4)
InputStreamReader
14 The Writer's subClass must implements
flush()
2)
close()
4)
IOException
2)
InterruptedException
3)
SystemException
PROBLEM
4)
SystemInputException
16 ______ stream that connects two running programs
Program stream
2)
Conduit
3)
Channel
4)
Pipe
17 Function of nextLine() method in Scanner class.
it moves the scanner position to the next line and returns the value as a string.
3)
it returns the value as a string and then moves the scanner position to the next line
4)
System
2)
PrintStream
3)
StringWriter
4)
BufferedWriter
PROBLEM
What is a buffer?
1)
1)
1**2#34*#12
2)
1**2*34**#12
3)
1**2#34***12
4)
1**2#34**#12
TOTAL SCORE: 100.0%
PROBLEM
Gospel music
2)
Avant-rock
3)
Logging Tool
4)
Action game
2 What license is Log4j distributed under?
1)
Shareware
4)
Loggers
2)
Appenders
3)
Layouts
4)
The ___________ ignores any logging messages that have a level lower than the threshold level.
1)
Appender
PROBLEM
2)
Logger
3)
Layout
4)
logging levels
3)
console output
4)
Mozilla Foundation
2)
Blender Foundation
8 Which of the following is correct about Appender object?
The Appender object is responsible for publishing logging information to various preferred destinations such as a database, file, co
PROBLEM
3)
jdbc
2)
console
3)
file
4)
rollingFile
10 What is the purpose of immediateFlush configuration of FileAppender?
output stream to the file being flushed with each append operation.
2)
TOTAL SCORE: 100.0%
PROBLEM
fatal
2)
error
3)
warning
4)
debug
2 Log4J configuration parameters are specified inside ________ file
Conf.groovy
2)
Config.groovy
3)
Log.groovy
4)
Used to output location information of the caller which generated the logging event.
2)
Used to output the line number from where the logging request was issued.
3)
Used to output the application supplied message associated with the logging event.
4)
Used to output the method name where the logging request was issued.
4 Which of the following is correct about layout object in Appender?
Appender uses the Layout objects and the conversion pattern associated with them to format the logging information.
2)
The Layout objects may be a console, a file, or another item depending on the appender.
3)
The Layout objects is required to control the filtration of the log messages.
4)
Appender can have a Layout objects associated with it independent of the logger level.
5 Which of the following is correct about log4j?
It is thread-safe.
2)
Which of the following method of logger print a log message in info mode?
PROBLEM
1)
Which of the following level designates all levels including custom levels?
1)
OFF
2)
TRACE
3)
WARN
4)
ALL
8 Which of the following level designates error events that might still allow the application to co...
Which of the following level designates error events that might still allow the application to continue running?
1)
DEBUG
2)
ERROR
3)
FATAL
4)
INFO
9 What is the purpose of driver configuration of JDBCAppender?
2)
to specify the SQL statement to be executed every time a logging event occurs.
4)
Individual layout subclasses implement _________ method for layout specific formatting.
1)
Used to output the fully qualified class name of the caller issuing the logging request.
3)
Used to output the file name where the logging request was issued.
12 A program must never be ________
understandable
2)
accurate
PROBLEM
3)
long
4)
portable
13 _______ is a method that creates a mock object from a domain class.
mockForConstraints
2)
mockForConstraintsTests
3)
mockConstraintsTests
4)
mockConstraints
14 Say TRUE or FALSE Logger uses the Layout objects and the conversion pattern associated with them ...
TRUE
2)
FALSE
15 Which of the following is correct about filter in Appender?
The Filter objects can analyze logging information beyond level matching and decide whether logging requests should be handled b
2)
The filter may be a console, a file, or another item depending on the appender.
3)
Appender can have a filter associated with it independent of the logger level.
Which of the following is correct flowchart for Snakes and Ladder game
1)
2)
3)
4)
Find the correct sequence of frog lifecycle
1)
tadpole with legs->tadpole->froglet->frog->frogspawn.
2)
tadpole->tadpole with legs->froglet->frog->frogspawn.
3)
frogspawn->tadpole with legs->froglet->frog->tadpole.
4)
frogspawn->tadpole->tadpole with legs->froglet->frog
1)
4)
2)
3)
Fill up the missing content in decision box to determine and output whether Number
N is Even or Odd
1)
Is Remainder = 0
2)
Is Remainder = 1
3)
Is Remainder != 0
4)
None of the listed options
Find the missing line in the below Pseudocode to print the area of a rectangle.
Read l
Read b
____________________
Write area
1)
compute area equal to l times b
2)
compute a equal to l times b
3)
compute area equal to length times breadth
4)
all of the mentioned options
Correct Answer: 4 5
Fill up the missing content in decision box to print Hello World 10 times.
1)Box 3
2)Box 10
3)Box 7
4)Box 2
What symbol do flowcharts use to show an action or process?
1)diamond
2)rectangle
3)parallelogram
4)o
Write an algorithm to find the factorial of given number
Factorial(number):
SET Fact = 1 and i = 1
WHILE i<=number
SET Fact=Fact*i
SET i=i+1
ENDWHILE
PRINT Fact
END
Fibonacci Sequence
Fibonacci(number):
SET first = 0 , second = 1 and i = 2
PRINT first and second
WHILE (i<number)
SET next = first + second and PRINT next
SET first = second
SET second = next and i = i+1
ENDWHILE
END
Number of digits
ArrayMaxElement(arr, N):
SET i=1 and max=arr[0]
WHILE (i<N):
IF (arr[i]>max) THEN
SET max=arr[i]
ENDIF
SET i=i+1
ENDWHILE
PRINT max
END
Search Element
Even or Odd
Input Format:
Input consists of an single integer.
Output Format:
Refer to the sample input an output.
[All text in bold corresponds to input and the rest corresponds to output.]
Sample Input and Output 1:
Enter the number:
4
The given number is even
Sample Input and Output 2:
Enter the number:
5
The given number is odd
S1P2 - REVERSE OF A NUMBER
Reverse of a number
Input format :
Input consists of an integer value.
Output format :
Output consists of the reverse of the given number.
M8P2-P2-DIGIT COUNTING
DIGIT COUNTING
Write a program to find the number of digits in a given number.
(Note : Please use initialize statement before input statement)
Input Format:
Input consists of an integer.
Output Format:
Output consists of a single line. Refer sample output for details.
Sample Input 1:
42
Sample Output 1:
The number of digits in 42 is 2
Fibonacci Series
Madhu and Balaji had a competition to generate a fibonacci series.
Its a Hundred rupees bet!!!
Why cant you help him?
Create a variable 'n' to get the range.
(Note : Please use initialize statement before input statement)
Sample Input and Output 1:
[All text in bold corresponds to input and the rest corresponds to output.]
Enter the range:
7
Fibonacci series:
0
1
1
2
3
5
8
Greatest Common Divisor
1)
public class Main {
}
2)
public class Main {
}
3)
public class Main {
public static void main(String[] args) {
}
4)
public class Main {
}
Select the appropriate code where 'Write your code' should be commented using multi line
comments
1)
public class Main {
//Write
//your
//code
}
2)
public class Main {
your
code*/
}
3)
public class Main {
*/Write
your
code/*
}
4)
public class Main {
*/Write
your
code*/
}
A file named myprog.java is compiled and the compiler generates
1)
myprog.exe
2)
myprog.class
3)
myprog.obj
4)
none of the mentioned
Which is the correct "Hello World" program?
1)
Class HelloWorld
System.out.println("Hello World");
}
2)
class HelloWorld
System.out.println("Hello World")
}
3)
class HelloWorld
System.out.println("Hello World");
}
4)
class HelloWorld
system.out.println("Hello World");
}
The ________ defines where the Java compiler and Java runtime look for .class files to load
1)
class
2)
classpath
3)
libraries
4)run time environment
1)Yes
2)No
Eclipse is an __________________(IDE) used in computer programming.
1)Integrated Design Environment
2)Internal Design Environment
3)Internal Development Environment
4)Integrated Development Environment
Consider the java file HelloWorld.java with Class HelloWorld. How to compile the code
inside the file using command.
1)javac HelloWorld.java
2)java HelloWorld.java
3)javac HelloWorld
4)java HelloWorld
How many types of errors are there?
1)3
2)2
3)1
4)4
Which errors prevent the code from successful compilation, because of error in the syntax
like missing a semicolon.
1)compilation errors
2)run time errors
3)logical errors
4)None of the mentioned options
Consider the java file HelloWorld.java with Class HelloWorld. How to run the code inside
the file using command after compilation.
1)javac HelloWorld.java
2)java HelloWorld.java
3)javac HelloWorld
4)java HelloWorld
Java programming language is a
1)object oriented language
2)structured language
3)procedural language
4)web based language
Java can be easily extended since it is based on the ______ model.
1)object-oriented
2)procedural
3)secure
4)platform-oriented
JVM stands for
1. If the length of the password is less than 8, then the password strength is 'weak'.
2. If the password length is greater than eight but does not contain any special characters or
numbers, the strength is considered as 'ok'.
3. If the password length is greater than 8 and contains special characters/numbers, the strength
is considered as 'good'.
Create a class Main.java
String name
String password
[All text in bold corresponds to input and the rest corresponds to output]
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
c.setName(userName);
c.setPassword(password);
cus.add(c);
c=null;
c=new Customer();
String regex1="((?=.*[a-z]).{1,8}$)";
String regex2="((?=.*[a-z]).{9,}$)";
String regex3="((?=.*[@#$%^&+=])(?=.*[a-z]).{9,}$)";
for(int i=0;i<cus.size();i++)
{
System.out.println("Customer name: "+cus.get(i).getName()+","+"
password: "+cus.get(i).getPassword());
Pattern p = Pattern.compile(regex1);
Matcher m = p.matcher(cus.get(i).getPassword());
Pattern p1 = Pattern.compile(regex2);
Matcher m1 = p1.matcher(cus.get(i).getPassword());
Pattern p2 = Pattern.compile(regex3);
Matcher m2 = p2.matcher(cus.get(i).getPassword());
if(m2.matches())
{
System.out.println("Password strength is good");
}
else if(m1.matches())
{
System.out.println("Password strength is ok");
}
else if(m.matches())
{
System.out.println("Password strength is weak");
}
//if(cus.get(0).getPassword().)
}
}
Call History
Practice makes a man perfect !!! Let us use FileWriter & BufferedWriter to
read call log data from console and rewrite it into a CSV file. Please refer to
the specification given below.
Note : Read the input from the user and write using 'FileWriter writer = new
FileWriter("call.csv");'
Enter the mobile number
8972007627
yes
8976543289
no
Output(call.csv):
8972007627,5
8976543289,6
import java.io.*;
import java.util.Scanner;
FileWriter fileWriter =
new FileWriter(fileName);
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
String cond="yes";
while(cond.equals("yes")) {
System.out.println("Enter the mobile number");
bufferedWriter.write(sc.next());
System.out.println("Enter the duration (in Seconds)");
bufferedWriter.write(","+sc.next());
bufferedWriter.newLine();
System.out.println("Do you want to add another call history ?");
cond=sc.next();
}
bufferedWriter.close();
}
catch(IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Discounts - Inheritance
One of the easier ways to identify the scenarios that reflect inheritance is to look for a
"is-a" relationship in the requirements document. On trying to check if we have such
hierarchies, we find that there are different types of customers/account holders in the
Bank. Customers can be Normal, Priviledged, SeniorCitizen and so on.
The Bank also introduces an offer where privileged customers get a 30% off on the bill
while senior citizens get 12% off.
Lets implement the inheritance for the given scenario yet again for a better
understanding.
1. Create Customer, Privileged & SeniorCitizen class with data members as given below.
2. Implement generateBillAmount Method as per the specification.
Create a class Customer with the following private data members
String name
String address
Integer age
String mobileNumber
Methods in class Customer
Create a driver class named Main which creates an instance of the above mentioned
classes.
Use setters to set the values to objects and display all details using getters from the main
method.
Note :
Strictly adhere to the object oriented specifications given as part of the problem
statement.
Use the same class names and member variable names.
Input and Output Format:
[All text in bold corresponds to input and the rest corresponds to output.]
Sample Input and Output 1:
1)Privilege Customer
2)SeniorCitizen Customer
Enter Customer Type
1
Enter The Name
Ram
Enter The Age
25
Enter The Address
CBE
Enter The Mobile Number
9576531641
Enter The Purchased Amount
5000
Bill Details
Name Ram
Mobile 9576531641
Age 25
Address CBE
Your bill amount is Rs 5000.0. Your bill amount is discount under privilege customer
You have to pay Rs 3500.00
public Customer() {
// TODO Auto-generated constructor stub
}
void displayCustomer() {
//fill your code here
}
}
import java.text.DecimalFormat;
void displayCustomer() {
System.out.println("Bill Details\nName "+getName()+"\nMobile
"+getMobileNumber()+"\nAge "+getAge()+"\nAddress "+getAddress()+"\nYour bill amount is Rs
"+getAmount()+". Your bill amount is discount under privilege customer\nYou have to pay Rs
"+format.format(generateBillAmount(amount)));
}
import java.text.DecimalFormat;
void displayCustomer() {
System.out.println("Bill Details\nName "+getName()+"\nMobile
"+getMobileNumber()+"\nAge "+getAge()+"\nAddress "+getAddress()+"\nYour bill amount is Rs
"+getAmount()+". Your bill amount is discount under senior citizen customer\nYou have to pay Rs
"+format.format(generateBillAmount(amount)));
}
import java.text.DecimalFormat;
import java.util.Scanner;
Customer customer;
if(choice<1 || choice>2)
{
System.out.println("Invalid Customer Type");
System.exit(0);
}
sc.nextLine();
System.out.println("Enter The Name");
String name = sc.nextLine();
switch (choice) {
case 1:
case 2:
Finally !!!
One of the technical requirements that you might often expect is to "execute a set of
lines" irrespective of the flow that goes through try / catch. A simple scenario that you
would know is to close a database connection / release resources if it goes through
successfully in a try block and happens to take an exception route. Lets practice the
"finally" keyword.
String accountNumber
Double amount
Boolean validate(transactionAmount)
class Transaction
{
String accountNumber;
Double amount;
Transaction()
{
}
Transaction(String a,Double b)
{
accountNumber=a;
amount=b;
}
void setAccountNumber(String a)
{
accountNumber=a;
}
void setAmount(Double a)
{
amount=a;
}
Double getAmount()
{
return amount;
}
boolean validate(Double a) throws Exception
{
if(amount<=500 || a>amount)
throw new Exception ("Insufficient Balance");
return true;
}
}
import java.util.Scanner;
class Main
{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter the transaction details\nEnter the account number\nEnter the available
amount");
Transaction t=new Transaction(s.nextLine(),Double.parseDouble(s.nextLine()));
try
{
do
{
System.out.println("Enter the transaction amount");
Double d=Double.parseDouble(s.nextLine());
t.validate(d);
t.setAmount(t.getAmount()-d);
System.out.println("Do you want to enter more ?(yes/no)");
}
while(s.nextLine().equals("yes"));
}
catch (Exception e)
{
System.out.println("Insufficient Balance");
}
finally
{
System.out.printf("Your available balance %.1f",t.getAmount());
}
}
}
SDF Exception
Lets' try to catch a very specific exception, i.e, SimpleDateFormat Exception, which is
thrown when we read a String and try to convert it into Date. Assume we are reading
Date-of-Birth of a customer and if they enter it in an incorrect format, capture it &
display a message.
Write a program to get the customer account name, account type and Date-Of-Birth.
Validate the Date-Of-Birth details and display the details.
String accountName
String accountType
Date dob
boolean validateDOB(String This method is used to validate the given date of birth and return true
dob) based on the validation.
Account Details
Name : Sastha
Type : Savings
D.O.B : Feb-25-1993
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
System.out.println("\nAccount Details");
System.out.println("Name : " + getAccountName());
System.out.println("Type : " + getAccountType());
try {
int[] numberOfDaysEachMonth = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31};
if (month > 0 && month < 13) {
if (day > 0 && day < numberOfDaysEachMonth[month - 1]) {
result = true;
} else {
System.out.println("Wrong Format(eg:01/01/2015)");
result = false;
}
} else {
System.out.println("Wrong Format(eg:01/01/2015)");
result = false;
}
} catch (Exception e) {
//System.out.println(e);
}
return result;
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;
import java.util.Date;
public class Main {
do{
System.out.println("Enter date-of-birth");
dob = sc.next();
status = ac.validateDOB(dob);
}while(status != true);
Lets think that RBI comes and says that there will be a fixed credit score . So every bank
must follow that credit score for all the transactions. In our problem let us consider the
fixed credit score to be 10%. So we have to calculate the credit score for the customer.
Create a interface Bank with method - calculateCreditScore() of return type as double.
Create a class RBI which implemets the interface Banks with 3 private data member
variables -accountNumber of type String, creditScore of type double , holderName of
type String and a fixed variable CREDIT of type double. Include the
method calculateCreditScore() and display().
Create the class ICICI which extends the class RBI .
Create a driver class named Main which creates an instance of the above mentioned
classes. Credit score must be calculated seperately for all the classes (value must be
round to 2 decimal place).
[All text in bold corresponds to input and the rest corresponds to output.]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;public class Main {
public static String accountNumber;
public static double creditScore;
public static String holderName;public static void main(String[] args) throws IOException {
System.out.println("Select the Bank Name\r\n" + "1.ICICI\r\n" + "2.HDFC");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int i = Integer.parseInt(br.readLine());
switch (i) {
case 1:
System.out.println("Enter the Holder Name");
holderName = br.readLine();
System.out.println("Enter the Account Number");
accountNumber = br.readLine();
System.out.println("Enter the Previous Credit Score");
creditScore = Double.parseDouble(br.readLine());
ICICI icici = new ICICI(accountNumber, creditScore, holderName);
System.out.println("Enter the Amount to be Paid");
icici.calculateCreditScore(Double.parseDouble(br.readLine()));
icici.display();
break;
case 2:
System.out.println("Enter the Holder Name");
holderName = br.readLine();
System.out.println("Enter the Account Number");
accountNumber = br.readLine();
System.out.println("Enter the Previous Credit Score");
creditScore = Double.parseDouble(br.readLine());
HDFC hdfc = new HDFC(accountNumber, creditScore, holderName);
System.out.println("Enter the Amount to be Paid");
hdfc.calculateCreditScore(Double.parseDouble(br.readLine()));
hdfc.display();
break;
default:
System.out.println("Invalid Bank type");
break;
}}}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
Student s = new Student();
System.out.println(s.data);
s.msg();
}
}
1)
Compilation errors
2)
50
Hello
3)
Nothing will be displayed
4)
Hello
How many public class per source code file.
1)
1
2)
2
3)
3
4)
any number
In the command "javac -d . Sample.java", what does the 'dot' denotes.
1)
current folder
2)
the folder one level up
3)
the folder that two levels up
4)
the folder outside the project
Select the non-access modifiers which cannot be applicable for attributes and
methods.
1)
abstract
2)
final
3)
finalize
4)
static
The statement which is true about protected modifiers
1)
Accessible only within the class.
2)
Accessible within the package.
3)
Accessible within the package and outside the package through child classes.
4)
Accessible throughout the project
The statement which is true about default modifiers
1)
Accessible only within the class.
2)
Accessible within the package.
3)
Accessible within the package and outside the package through child classes.
4)
Accessible throughout the project
Consider that we have a class named Stall inside the package 'myPack'. How to add
that class inside Main class, so that the Stall class can be accessible inside Main.
1)
import myPack.*;
2)
import myPack;
3)
import myPack.Stall;
4)
imports myPack.Stall
The method in System class that terminates the current Java Virtual Machine running
on system.
1)
terminate( )
2)
exit()
3)
Exit()
4)
Terminate()
- Programming Fundamentals
Write an algorithm to find the factorial of given number.
Factorial(number):
SET Fact = 1 and i = 1
WHILE i<=number
SET Fact=Fact*i
SET i=i+1
ENDWHILE
PRINT Fact
END
Fibonacci Sequence
S3P16-Series1
Series 1
The Event Organizing Company "Buzzcraft" focuses event management in a way that
creates a win-win situation for all involved stakeholders. Buzzcraft don't look at building
one time associations with clients, instead, aim at creating long-lasting collaborations
that will span years to come. This goal of the company has helped them to evolve and
gain more clients within notable time.
The number of clients of the company from the start day of their journey till now is
recorded sensibly and is seemed to have followed a specific series like:
2,3,5,7,11,13,17,19, 23 ...
Write a program which takes an integer N as the input and will output the series till the
Nth term.
Input Format:
First line of the input is an integer N.
Output Format:
Output a single line the series till Nth term, each separated by a comma.
Refer sample input and output for formatting specifications.
Sample Input 1:
5
Sample Output 1:
2 3 5 7 11
Sample Input 2:
10
Sample Output 2:
2 3 5 7 11 13 17 19 23 29
import java.util.Scanner;
import java.util.Scanner;
import java.text.DecimalFormat;
class Main {
double brandingper=branding*100/totalexpense;
double travelingper=travel*100/totalexpense;
double foodper=food*100/totalexpense;
double logisticsper=logistics*100/totalexpense;
//System.out.print("% \n");
}
Thrill ride
"Fantasy Kingdom" is a brand new Amusement park that is going to be inaugurated
shortly in the City and is promoted as the place for breath-taking charm. The theme park
has more than 30 exhilarating and thrilling rides and as a special feature of the park, the
park Authorities have placed many Booking Kiosks at the entrance which would
facilitate the public to purchase their entrance tickets and ride tickets.
There are few rides in the park which are not suitable for Children and aged people,
hence the park Authorities wanted to program the kiosks to issue the tickets based on
people’s age. If the age given is less than 15 (Children) or greater than 60 (Aged), then
the system should display as "Not Allowed", otherwise it should display as "Allowed".
Write a block of code to help the Authorities program this functionality.
Input Format:
First line of the input is an integer that corresponds to the age of the person opting for
the ride.
Output Format:
Output should display "Allowed" or "Not Allowed" based on the conditions given.
Refer sample input and output for formatting specifications.
Sample Input 1:
20
Sample Output 1:
Allowed
Sample Input 2:
12
Sample Output 2:
Not Allowed
import java.util.*;
import java.io.*;
class Main{
public static void main(String[] args) throws Exception{
int age=sc.nextInt();
if((age<15)||(age>60)){
System.out.println("Not Allowed");
}else{
System.out.println("Allowed");}
Character Pattern 3
Sample Input 1:
5
Sample Output 1:
*
**
***
****
*****
import java.util.*;
import java.io.*;
class Main{
int n=sc.nextInt();
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
System.out.print("*");
System.out.println();
}
Display Item Type
The International Film Festival of India (IFFI), founded in 1952, is one of the most
significant film festivals in Asia. The festival is for a weel and arrangements have to be
made for food, chairs, tables, etc. The organizing committee plans to deposit the
advance amount to the contractors on conformation of boking.
Help them to store these details and print them in detailed view.
Write a Java program to get item type, cost per day and deposit amount from user and
display these details in a detailed view using the following classes and methods.
[Note :
Strictly adhere to the object oriented specifications given as a part of the problem
statement.
Follow the naming conventions as mentioned. Create separate classes in
separate files.]
Create an another class Main and write a main method to test the above class.
In the main( ) method, read the item type details from the user and call the display( )
method.
import java.text.DecimalFormat;
return name;
this.name = name;
return costPerDay;
this.costPerDay = costPerDay;
return deposit;
this.deposit = deposit;
System.out.println("Name : "+getName());
System.out.println("CostPerDay : "+df.format(getCostPerDay()));
System.out.println("Deposit : "+df.format(getDeposit()));
Main
--------------
import java.io.*;
import java.util.Scanner;
class Main{
i.setName(sc.nextLine());
i.setCostPerDay(sc.nextDouble());
i.setDeposit(sc.nextDouble());
i.display();
PROBLEM
Little App helps you discover great places to eat around or de-stress in all major cities across
20000+ merchants. Explore restaurants, spa & salons and activities to find your next fantastic
deal. The development team of Little App seeks your help to find the duplication of user
accounts.
Write a Java program to get two users details and display whether their phone numbers are
same or not with the following class and methods.
[Note : Strictly adhere to the object-oriented specifications given as a part of the problem
statement.
Follow the naming conventions as mentioned. Create separate classes in separate files.]
Create a class named User with the following private attributes/variables.
Date Type Variable
String name
String username
String password
long phoneNo
public boolean comparePhoneNumber(User user) In this method, compare the phone number of the two use
Create another class Main and write a main method to test the above class.
Sample Input/Output 1
Enter Name
john
Enter UserName
john@123
Enter Password
john@123
Enter PhoneNo
9092314562
Enter Name
john
Enter UserName
john@12
Enter Password
john@12
Enter PhoneNo
9092314562
Same Users
Sample Input/Output 2
Enter Name
ram
Enter UserName
ram####
Enter Password
ram
Enter PhoneNo
9092314562
Enter Name
john
Enter UserName
john@123
Enter Password
john@123
Enter PhoneNo
9092312102
Different Users
Create an another class Main and write a main() method to test the above class.
In the main( ) method, read the length and width details from the user and test the
above methods. Display the area of the rectange inside the main() method.
Problem Constraints:
1. Use instanceof operator to check the object returned by dimensionChange( ) method.
[The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).]
Problem Requirements:
instanceof 1 -
super();
this.length = length;
this.width = width;
return length;
this.length = length;
}
public int getWidth() {
return width;
this.width = width;
return (getLength()*getWidth());
System.out.println("Rectangle Dimension");
System.out.println("Length:"+getLength());
System.out.println("Width:"+getWidth());
length=d*getLength();
setLength(length);
width=d*getWidth();
setWidth(width);
}
}
import java.util.Scanner;
import java.io.IOException;
int length,width,area,d;
Rectangle rec;
length=sc.nextInt();
width=sc.nextInt();
r.display();
area=r.area();
d=sc.nextInt();
rec=r.dimensionChange(d);
rec.display();
area=rec.area();
}
}
Simplified Fraction
St. Patrick Convent organizes a project exhibition "Innovative Minds" every year with an
objective to provide the platform and unleash the potential of the students by
showcasing their innovative projects. Pasha is a smart high school student and was eager
to participate in the fair for the first time.
After a lot of ground works, she decided her project and set out to design the same. Her
project requirement was to design an advanced calculator that has a fraction feature that
will simplify fractions. The project will accept a non-negative integer as a numerator and
a positive integer as a denominator and outputs the fraction in simplest form. That is, the
fraction cannot be reduced any further, and the numerator will be less than the
denominator.
Help Pasha to program her advanced calculator and succeed in her first ever project
presentation. You can assume that all input numerators and denominators will produce
valid fractions.
Input Format:
First line of the input is a non-negative integer which is the numerator in the fraction.
Second line of the input is a positive integer which is thedenominator in the fraction.
Output Format:
Output the simplified form of the fraction in a single line.
Refer sample input and output for formatting specifications.
Sample Input 1:
28
7
Sample Output 1:
4
Sample Input 2:
13
5
Sample Output 2:
2 3/5
if (num <= 0) {
System.out.println(0);
System.out.println(num/gcd+"/"+den/gcd);
if (rem != 0) {
else {
System.out.println(quo);
}
else {
System.out.println(1);
int gcd = 1;
gcd = i;
break;
return gcd;
import java.util.Scanner;
f.printValue(num, den);
}
PROBLEM
Write a Java program to display the array of Integers and array of Strings. Use for each
loop to iterate and print the elements.
Constraints :
Use for each loop to iterate and print the elements.
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.
Sample Output 1:
Arguments :
Command
Arguments
Number of arguments is 2
Sample Output 2:
Arguments :
Commands
Number of arguments is 1
public class Main{
int count=0;
System.out.println("Arguments :");
for(int a=0;a<args.length;a++)
System.out.println(args[a]);
count++;
ArrayList - Introduction
We have been using an array to store a group of objects. But arrays are of fixed size and
are difficult to use compared to collections. So we are gonna move into collections. The
basic collection is a list. Now let us try out basic ArrayList.
Create a class Main and in the main method get the usernames and store them in an
ArrayList. After getting all the names, just display them in the same order.
Input and Output format:
Refer to sample Input and Output for formatting specifications.
Note: All Texts in bold corresponds to the input and rest are output
Sample Input and Output 1:
Enter the username 1
John
Do you want to continue?(y/n)
y
Enter the username 2
Joe
Do you want to continue?(y/n)
n
The Names entered are:
John
Joe
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String args[]) throws Exception{
//write your code here
boolean result=false;
List<String> list = new ArrayList<String>();
int i=1;
Scanner scanner = new Scanner(System.in);
do{
System.out.println("Enter the username " + i++);
String name = scanner.nextLine();
list.add(name);
System.out.println("Do you want to continue?(y/n)");
String diss = scanner.nextLine();
result=diss.equals("y");
}while(result);
Set Introduction
In the program let’s try using a Set. The property of Set is, it doesn't allow duplicate
elements and does not maintain order like a list. Understand it by going through and
completing the problem.
Write a program to get the username and store it in the set and display the unique
number of the username in the set.
Create a driver class called Main. In the Main method, obtain username input from the
user.
java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
}
TreeMap()
To assist Event organizers, you need to develop a console application that shows the
number of tickets sold in a particular price category. Thus enabling them to increase or
decrease seats allocated for different price levels and thereby boosting ticket sales. The
list of booking details that contains customer and price details are given.
Use TreeMap with price as key and number of seats booked as value.
Create a driver class named Main. In the main method, obtain details and display the
price along with the number of tickets in increasing order of price.
Input Format:
The first line of the input corresponds to the number of events 'n'.
The next 'n' line of inputs corresponds to the event details in CSV format (Customer
Name, Ticket Price, No of Seats Booked).
Refer to Sample Input and Output for formatting specifications.
Output Format:
The output consists of the number of tickets booked for a particular ticket price in
increasing order of price.
Use ("%-15s %s\n","Ticket Price","Tickets Booked") for the format.
Refer to Sample Input and Output for formatting specifications.
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
map.put(price, (seat+seatBooked));
} else {
map.put(price, seatBooked);
}
}
System.out.println("Ticket Price Tickets Booked");
for(Map.Entry m:map.entrySet()){
System.out.printf("%-15s %s\n",m.getKey(),m.getValue());
}
}
}
Comparable Interface
Let's get in touch with the comparable interface. Given the list of Address details, sort
them based on Pincode. If two address has the same Pincode, then sort them based on
address line 1. This sorting will help us for segregating users based on Pincode when
certain details (City and state details) are unavailable.
Create a driver class named Main to test the above class. Obtain input from the console
and sort the user list.
Input Format:
The first line input corresponds to the number of users 'n'.
The next 'n' line of inputs corresponds to the user details in CSV
format(Username,AddressLine 1,AddressLine 2,PinCode).
Refer to sample input for formatting specifications.
Output Format:
The output consists of user details in the CSV format in sorted order. Print the output in
the main method.
Refer to sample output for formatting specifications.
Sample Input and Output 1:
[All text in bold corresponds to the input and rest corresponds to the output]
import java.util.*;
import java.io.*;
if (pinCode == address.pinCode)
{
return (addressLine1.compareTo(address.addressLine1));
//return 0;
}
else if (pinCode > address.pinCode)
{
return 1;
}
else
{
return -1;
}
}
}
reverse() method
In the collection, sort() method sort the objects in the ascending order. Suppose if we
want to sort the list of objects in the descending order, we can use of reverse() method.
Write a program to implement the reverse() method along with sort() to sort the list of
User objects in the descending order.
Implement Comparable and sort the user objects based on name and reverse it by using
the reverse().
Create a driver class Main and using the main method get the details, create a map and
display the details.
Input format:
The first line of input consists of number of users n.
The next n line of input consists of user details in the CSV format
(name,mobileNumber,userName,password).
Output format:
Display the name and the mobile number of the user in the reverse order.
Use "%-15s%-15s" to display details in tabular format.
Refer to sample input and output for other further details and format of the output.
return (this.name.compareTo(user.name));
@Override
public String toString() {
return String.format("%-15s%-15s",getName(),getMobileNumber());
}
}
------------------------------
import java.io.*;
import java.util.*;
}
Collections.sort(UserList);
Collections.reverse(UserList);
}
catch (Exception e){
}
finally {
System.out.println("The user details in reverse order:");
System.out.printf("%-15s%-15s\n","Name", "Mobile number");
Generic Classes
Create a generic class Item with a data. Write two methods set and get, to set a value to
the data variable and to get the value of the data variable respectively. From Main class
create two object for the class Item of types Integer and String.
private T t;
public T get() {
return t;
}
}
-------------------
import java.util.Scanner;
import java.io.*;
integerItem.set(sc.nextInt());
sc.nextLine();
}
}
Iterator class
It is time to explore some unique classes and methods in Collections. The Iterator class is
one such. You have created test data for Stall class with the name of stall starting with
prefix 'test', It's time to remove those objects. While iterating a collection through a for
loop or a for each loop, you cannot modify or remove an element. The Iterator
class facilitates such functionalities. Hence while you iterate through a Collection using
Iterator you can modify the elements. Let's implement it to delete test data.
Create a driver class called Main. In the Main method, obtain stall input from the user
and create a list of Stall details. Using the Iterator class iterate through the List and
remove stalls with a name starting with 'test'.
Display the list of details in tabular form.
Input format:
The first line consists of the number of stalls 'n'
The next 'n' line consists of 'n' stall details given in CSV format. (name,
detail,type,ownerName)
Output format:
The first line of output displays the heading of the stall details.
Then the stall details without containing the prefix 'test' are displayed in tabular format
Use ("%-15s %-20s %-15s %s") for formatting
Refer to the sample Input and Output for further details and for the formatting
specifications.
Create driver class Main and use the main method to get inputs, sort, and display.
Input Format:
The first line has the number of halls n.
The next n lines have details of the hall in CSV
format. (name,contactNumber,costPerDay,ownerName).
Output format:
Use "%-15s%-15s%-15s%-15s" to display the hall details in the sorted order based on
the cost per day as in tabular form.
Refer to sample input and output for other further details and format of the output.
Note: All Texts in bold corresponds to the input and rest are output.
Seat Arrangement
Having recapped with already learned collection concepts, it's time to get involved in
complex collection concepts. We would have created a list of primitive datatype and
objects. Let's start with List of List in this exercise. Create a structure of seats in a
StageEvent given the details of the number of rows and columns. Assign Section
chronologically starting with 'A' and number starting from 1.
Create a driver class called Main. In the Main method, obtain input from the user and
create a list of list of Seats. obtain Seat details for booking and at last display the
Booked seats.
Input format:
The first line corresponds to the number of rows
The second line corresponds to the number of seats per row
The third line consists of tickets to be booked in CSV format.
Output format:
Seats that are booked are represented by "--" whereas the unbooked seats are
represented by the section and number
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input/Output 1:
Create a Main class. Obtain email addresses from the user and add them to a Set. At last,
get a String that has multiple email addresses in CSV format. Print "Email addresses are
present" if all email addresses are present in the Set, else print "Email addresses are not
present".
Note: All Texts in bold corresponds to the input and rest are output
List of List
We have already seen a problem in the list of lists. So let's try to use it in our application.
While the users try to book the tickets for the events they should know the count of
remaining tickets. Let's create a list of 5 days of the week each has a list of the count of
remaining tickets for 4 shows. List<List<Integer>> is the general format and for
the problem, dayList<showList<count>>, ie., store the count of ticket available for each
show of a day in a list and then place these lists for each day of a week inside another
list.
The maximum number of tickets for a show is 100. So after getting the bulk booked
tickets from the user, subtract and store the remaining count of tickets for the whole
week in this list of lists.
Create a driver class Main and use the main method to get the count of already booked
tickets and create a list of the list to store the remaining count.
Note:CSV input format is (show1,show2,show3,show4) for each day. And enter day to
know remaining ticket count for the day.
Refer sample input/output for other further details and format of the output.
Input Format:
The first five lines have the number of tickets booked in each day
The next lines have the day in which the remaining ticket to be shown
[All Texts in bold corresponds to the input and rest are output]
Sample Input/Output 1:
Create a driver class named Main to test the above class. Obtain input from the console ,
get a list of TicketBooking, and use Collections.min() and Collections.max() to find the
customer who spent more and less amount for ticket booking.
Input Format:
The first line input corresponds to the number of customers 'n'. n>0 else display "Invalid
Input".
The next 'n' line of inputs corresponds to the user details in CSV format (Customer
Name, Price).
Refer to sample input for formatting specifications.
Output Format:
The output consists of the minimum and maximum amount spent by the customer. If
two or more customer price is the same, keep the 1st one's price.
Refer to sample output for formatting specifications.
[All Texts in bold corresponds to the input and rest are output]
Sample Input/Output-1:
Enter the number of customers
4
Enter the booking price accordingly with customer name in CSV(Customer Name,Price)
Jenny,1200
Maria,450
Jaquilin,600
Renita sarah,150
Renita sarah spends minimum amount of Rs.150
Jenny spends maximum amount of Rs.1200
Replica of a List
User data is always important and backup has to be made for every now and then. First
of all, we'll back up the User authorization data for practice. The List of user details is
provided. create a replica of the given list and store it in a backup list. An exact replica of
a collection can be created using the copy() method of the List API.
Follow the instruction below and display the backup list.
Create a driver class named Main to test the above class. In Main class create
destination list of size as same source list with null values(without a null list it
throws IndexOutOfBoundsException) and this has sent as destination list to the backUp
method.
Input Format:
The first line input corresponds to the number of users 'n'. n>0 else display "Invalid
Input".
The next 'n' line of inputs corresponds to the user details in CSV format(Username,
Password).
Refer to sample input for formatting specifications.
Output Format:
The output consists user details in the format of System.out.format("%-20s
%s\n","Username","Password");.
Refer sample output for formatting specifications.
[All Texts in bold corresponds to the input and rest are output]
Sample Input/Output-1:
Enter number of users
3
Enter the user details in CSV(Username,password)
Daniel,merry
Bisoph,qwertyuio!@12345
Jaques,877878785565
Copy of user list:
Username Password
Daniel merry
Bisoph qwertyuio!@12345
Jaques 877878785565
State map
Let's have a different variant of multimap. Create a
Map<String,Map<String,List<Address>>> with State name as key and a map as a value
having City name as key and List of address as value. It should be understood that the
address should have the state and city name as that of the key. At last obtain state and
city as search terms and display the corresponding list of addresses.
Attributes Datatype
addressLine1 String
addressLine2 String
city String
state String
pincode Integer
Create a driver class called Main. In the main method, obtain address details and create
the map of above specification. Obtain state and city as search term and display the
address that has the given city and state. If no such address is present, Print "Searched
city not found" or "Searched state not found" accordingly.
Note:
[Strictly adhere to the Object-Oriented Specifications given in the problem statement.
All class names, attribute names and method names should be the same as specified in
the problem statement.]
Input format:
Output format:
Address details are displayed in tabular format (Use "%-15s %-15s %-15s %-15s %s\n"
for formatting Address details.)
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input/Output 1:
\
Generic Methods
Write a single generic method declaration that can be called with arguments of different
types to print the elements of Integer, Double and Character arrays.
Output Format:
Output should display the welcome message along with the Customer’s name.
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and rest corresponds to output.]
import java.util.Scanner;
class Main {
public static void main(String[] args) {
import java.util.Scanner;
import java.text.DecimalFormat;
class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("0.00");
Thrill ride
"Fantasy Kingdom" is a brand new Amusement park that is going to be inaugurated
shortly in the City and is promoted as the place for breath-taking charm. The theme park
has more than 30 exhilarating and thrilling rides and as a special feature of the park, the
park Authorities have placed many Booking Kiosks at the entrance which would
facilitate the public to purchase their entrance tickets and ride tickets.
There are few rides in the park which are not suitable for Children and aged people,
hence the park Authorities wanted to program the kiosks to issue the tickets based on
people’s age. If the age given is less than 15 (Children) or greater than 60 (Aged), then
the system should display as "Not Allowed", otherwise it should display as "Allowed".
Write a block of code to help the Authorities program this functionality.
Input Format:
First line of the input is an integer that corresponds to the age of the person opting for
the ride.
Output Format:
Output should display "Allowed" or "Not Allowed" based on the conditions given.
Refer sample input and output for formatting specifications.
Sample Input 1:
20
Sample Output 1:
Allowed
Sample Input 2:
12
Sample Output 2:
Not Allowed
import java.util.*;
import java.io.*;
class Main{
PROBLEM
Character Pattern 3
Sample Input 1:
5
Sample Output 1:
*
**
***
****
*****
import java.util.*;
import java.io.*;
class Main{
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
System.out.print("*");
System.out.println();
Aayush's Scholarship
Aayush studies in Teswan National University. Now is the time for exam results. Aayush
similar to other students, hopes that his scores in 5 subjects in the exam could fetch him
a scholarship for his GRE preparation.
The following simple rules are used to find whether he is eligible to receive scholarship:
University follows 5 point grading system. In an exam, a student can receive any
score from 2 to 5. 2 is called an F grade, meaning that student has failed that exam.
Student should not have fail any of the exams.
Student must obtain a full score in some of his/her exams to show that he/she is
excellent in some of the subjects.
He/She must have a grade point average not less than 4.0
You are given information regarding how Aayush performed in those 5 subjects . Help
him determine whether he will receive the scholarship or not.
Input Format:
The input contains 5 integers denoting Aayush’s 5 subjects score in the exam.
Output Format:
Output a single line - "Yes" (without quotes) if Aayush will receive scholarship, or "No"
(without quotes) otherwise.
Refer sample input and output for formatting specifications.
Sample Input 1:
Enter the subject1 mark
3
Enter the subject2 mark
5
Enter the subject3 mark
4
Enter the subject4 mark
4
Enter the subject5 mark
3
Sample Output 1:
No
Sample Input 2:
Enter the subject1 mark
3
Enter the subject2 mark
4
Enter the subject3 mark
4
Enter the subject4 mark
4
Enter the subject5 mark
5
Sample Output 2:
Yes
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args) {
if(sub1==5||sub2==5||sub3==5||sub4==5||sub5==5)
{
if(sub1==2||sub2==2||sub3==2||sub4==2||sub5==2)
System.out.println("No");
else if((sub1+sub2+sub3+sub4+sub5)/5.0>=4.0)
System.out.println("Yes");
else
System.out.println("No");
}
else
System.out.println("No");
}
}
Series 1
The Event Organizing Company "Buzzcraft" focuses event management in a way that
creates a win-win situation for all involved stakeholders. Buzzcraft don't look at building
one time associations with clients, instead, aim at creating long-lasting collaborations
that will span years to come. This goal of the company has helped them to evolve and
gain more clients within notable time.
The number of clients of the company from the start day of their journey till now is
recorded sensibly and is seemed to have followed a specific series like:
2,3,5,7,11,13,17,19, 23 ...
Write a program which takes an integer N as the input and will output the series till the
Nth term.
Input Format:
First line of the input is an integer N.
Output Format:
Output a single line the series till Nth term, each separated by a comma.
Refer sample input and output for formatting specifications.
Sample Input 1:
5
Sample Output 1:
2 3 5 7 11
Sample Input 2:
10
Sample Output 2:
2 3 5 7 11 13 17 19 23 29
import java.util.Scanner;
Welcome Message
"Pine Tree" is a recently launched startup Event Management company. The company
gained a good reputation within a short span because of its highly reliable service
delivery.
Nikhil, the founder of this company wished to take the company’s services to the next
step and decided to design an Event Management System that would let its Customers
plan and host events seamlessly via an online platform. As a part of this requirement,
Nikhil wanted to write a piece of code for his company’s Amphi Event Management
System that will welcome all the Customers who are using it. Help Nikhil on the task.
Output Format:
Output should display "Welcome to Amphi Event Management System".
Refer sample output for formatting specifications.
Sample Output:
Welcome to Amphi Event Management System
public class Main{
Ticket type
"FantasyKingdom" is a brand new Amusement park that is going to be inaugurated
shortly in the City and is promoted as the place for breath-taking charm. The theme park
has more than 30 exhilarating and craziest rides and as a special feature of the park,
the park Authorities has placed many Ticketing Kiosks at the entrance which would
facilitate the public to purchase their entrance tickets and ride tickets.
The Entrance Tickets are to be issued typically based on age, as there are different fare
for different age groups. There are 2 types of tickets – Child ticket and Adult ticket. If the
age given is less than 15, then Child ticket is issued whereas for age greater than equal
to 15, Adult ticket is issued. Write a piece of code to program this requirement in the
ticketing kiosks.
Input Format:
First line of the input is an integer that corresponds to the age of the person.
Output Format:
Output should display "Child Ticket" or "Adult Ticket" based on the conditions given.
Refer sample input and output for formatting specifications.
Sample Input 1:
20
Sample Output 1:
Adult Ticket
Sample Input 2:
12
Sample Output 2:
Child Ticket
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int age=sc.nextInt();
if(age>=15)
{
System.out.println("Adult Ticket");
}
else
{
System.out.println("Child Ticket");
}
}
}
Lucky Pairs
Richie and Riya are participating in a game called "Lucky pairs" at the Annual Game
Fair in their Company. As per the rules of the contest, two members form a team and
Richie initially has the number A and Riya has the number B.
There are a total of N turns in the game, and Richie and Riya alternatively take turns. In
each turn the player whose turn it is, multiplies his or her number by 2. Richie has the
first turn. Suppose after the entire N turns, Richie’s number has become C and Riya’s
number has become D. The final score of the team will be the sum of the scores (C+D)
of both the players after N turns.
Write a program to facilitate the quiz organizers to find the final scores of the teams.
Input Format:
The only line of input contains 3 integers A, B, and N.
Output Format:
Output a single line which contains the integer that gives the final score of the team
which will be the sum of the scores of both the players after N turns.
Refer sample input and output for formatting specifications.
Sample Input 1:
121
Sample Output 1:
4
Sample Input 2:
323
Sample Output 2:
16
SOLUTION
import java.util.Scanner;
int A = sc.nextInt();
int B = sc.nextInt();
int N = sc.nextInt();
int sum = 0;
if(i%2 == 0)
{
B = B * 2;
}
else{
A = A * 2;
}
sum = A+B;
}
System.out.println(sum);
}
Display Item Type
The International Film Festival of India (IFFI), founded in 1952, is one of the most
significant film festivals in Asia. The festival is for a weel and arrangements have to be
made for food, chairs, tables, etc. The organizing committee plans to deposit the
advance amount to the contractors on conformation of boking.
Help them to store these details and print them in detailed view.
Write a Java program to get item type, cost per day and deposit amount from user and
display these details in a detailed view using the following classes and methods.
[Note :
Strictly adhere to the object oriented specifications given as a part of the problem
statement.
Follow the naming conventions as mentioned. Create separate classes in
separate files.]
Create an another class Main and write a main method to test the above class.
In the main( ) method, read the item type details from the user and call the display( )
method.
PROBLEM
Little App helps you discover great places to eat around or de-stress in all major cities across
20000+ merchants. Explore restaurants, spa & salons and activities to find your next fantastic
deal. The development team of Little App seeks your help to find the duplication of user
accounts.
Write a Java program to get two users details and display whether their phone numbers are
same or not with the following class and methods.
[Note : Strictly adhere to the object-oriented specifications given as a part of the problem statement.
Follow the naming conventions as mentioned. Create separate classes in separate files.]
String name
String username
String password
long phoneNo
public boolean comparePhoneNumber(User user) In this method, compare the phone number of the two use
Create another class Main and write a main method to test the above class.
Sample Input/Output 1
Enter Name
john
Enter UserName
john@123
Enter Password
john@123
Enter PhoneNo
9092314562
Enter Name
john
Enter UserName
john@12
Enter Password
john@12
Enter PhoneNo
9092314562
Same Users
Sample Input/Output 2
Enter Name
ram
Enter UserName
ram####
Enter Password
ram
Enter PhoneNo
9092314562
Enter Name
john
Enter UserName
john@123
Enter Password
john@123
Enter PhoneNo
9092312102
Different Users
User.java
String name;
String username;
String password;
long phoneNo;
public User(){}
this.name = name;
this.username = username;
this.password = password;
this.phoneNo = phoneNo;
return name;
}
public void setName(String name) {
this.name = name;
//System.out.println(this.name);
return username;
this.username = username;
return password;
this.password = password;
return phoneNo;
this.phoneNo = phoneNo;
if(this.phoneNo == user.getPhoneNo()){
return true;
else{
return false;
Main.java
import java.io.*;
//import java.util.Scanner;
//import java.text.DecimalFormat;
class Main{
String name;
System.out.println("Enter Name");
name = br.readLine();
String username;
System.out.println("Enter UserName");
username = br.readLine();
String password;
System.out.println("Enter Password");
password = br.readLine();//Double.parseDouble(br.readLine());
long phoneNo;
System.out.println("Enter PhoneNo");
phoneNo = Long.parseLong(br.readLine());
String name1;
System.out.println("Enter Name");
name1 = br.readLine();
String username1;
System.out.println("Enter UserName");
username1 = br.readLine();
String password1;
System.out.println("Enter Password");
password1 = br.readLine();//Double.parseDouble(br.readLine());
long phoneNo1;
System.out.println("Enter PhoneNo");
phoneNo1 = Long.parseLong(br.readLine());
if(result == true){
System.out.println("Same Users");
else{
System.out.println("Different Users");
// User.comparePhoneNumber(User);
}
Rectangle Dimension Change
Write a Java program to illustrate the method returning an objects by getting
details from user and check the type of objects using instanceof and display these
details in a detailed view using the following classes and methods.
[Note :
Strictly adhere to the object oriented specifications given as a part of the problem
statement.
Follow the naming conventions as mentioned. Create separate classes in
separate files.]
Create an another class Main and write a main() method to test the above class.
In the main( ) method, read the length and width details from the user and test the
above methods. Display the area of the rectange inside the main() method.
Problem Constraints:
1. Use instanceof operator to check the object returned
by dimensionChange( ) method.
[The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).]
Problem Requirements:
Java
instanceof 1
PROBLEM
Write a program to implement the String methods like substring, charAt,
equalsIgnoreCase and concat.
Input format:
Input consists of two strings. String length should be greater than 5.
Output format:
Output consists of the result of all String methds.
Note:
Refer the sample input and output for specifications.
All text in bold corresponds to the input and remaining corresponds to the output.
Constraints :
Use for each loop to iterate and print the elements.
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.
Problem Requirements:
Java
for 1
PROBLEM
Sample Output 1:
Arguments :
Command
Arguments
Number of arguments is 2
Sample Output 2:
Arguments :
Commands
Number of arguments is 1
Customer Class With Constructor
Refering to the SRS document, we were able to create classes for representing
Customers and their Addresses. To populate values into the objects created by classes,
one of the prefered ways is using Constructors. Constructors are member functions
which are called when an object is created.
Write a program to get the customer details, assign the values to object and display it.
Create a class named Customer with the following public member variables
Data Type Variable Name
String customerName
String customerEmail
String customerType
String customerAddress
Include 4 argument constructors in the Customer class in the following
order Customer(String customerName, String customerEmail, String
customerType,String customerAddress)
Sum of an array
Write a program to find the sum of the elements in an array using for each
loop.
Input Format:
Input consists of n+1 integers. The first integer corresponds to ‘n’ , the size of
the array. The next ‘n’ integers correspond to the elements in the array.
Assume that the maximum value of n is 15.
Output Format:
Refer sample output for details.
All text in bold corresponds to the input and remaining corresponds to the
output.
Sample Input and Output:
Enter n :
5
2
3
6
8
1
Sum of array elements is : 20
Problem Requirements:
Java
for 1
PROBLEM
Write a program to implement the String methods to convert given strings into
uppercase and lowercase letters.
Input format:
Input consists of two strings.
Output format:
The first line of output should display the string in uppercase characters. (Convert first
string)
The second line of output should display the string in lowercase characters. (Convert
second string)
Note:
Refer the sample input and output for specifications.
All text in bold corresponds to the input and remaining corresponds to the output.
Sample Output 1:
Programming - Command Line Arguments
Sample Output 2:
Arguments - Command Line Arguments
Customer Address
Write a program to get the address details and display it using classes and objects.
String street
String city
int pincode
String country
Create a Main class to include the main method and test the above class.
this.Street = street;
this.City = city;
this.Country = country;
this.Pincode = pincode;
/*public void setStreet(String street) {
this.street = street;
}
public String getStreet() {
return street;
}
public void setCity(String city) {
this.city = city;
}
public String getCity() {
return city;
}
void displayAddress() {
System.out.println("Street: "+this.Street);
System.out.println("City: "+this.City);
System.out.println("Pincode: "+this.Pincode);
System.out.println("Country: "+this.Country);
Main
import java.util.Scanner;
import java.io.*;
public class Main{
public static void main(String[] args) throws IOException{
//Fill your code
int pincode;
String country, street, city;
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num;
System.out.println("Enter an integer");
num = sc.nextInt();
System.out.println("The binary equivalent of "+num+" is "+ Integer.toBinaryString(num));
System.out.println("The hexadecimal equivalent of "+num+" is "+ Integer.toHexString(num));
System.out.println("The octal equivalent of "+num+" is "+ Integer.toOctalString(num));
byte b = (byte) num;
Short s = (short) num;
long l = num;
Float f = (float) num;
Double d = (double) num;
System.out.println("Byte value of "+num+" is "+b);
System.out.println("Short value of "+num+" is "+s);
System.out.println("Long value of "+num+" is "+l);
System.out.println("Float value of "+num+" is "+f);
System.out.println("Double value of "+num+" is "+d);
}
}
Write a java program to find the duplicate mobile number using the exception handling
mechanism.
Attributes Datatype
mobile String
alternateMobile String
landLine String
email String
address String
Method Description
Create a driver class called Main. In the Main method, obtain inputs from the user.
Validate the mobile and alternateMobile and display the ContactDetail if no exception
occurs else handle the exception.
Pass the exception message as "Mobile number and alternate mobile number are same".
If mobile and alternateMobile are the same.
Note: All text in bold corresponds to the input and rest corresponds to the output.
public DuplicateMobileNumberException(String s)
super(s);
return "DuplicateMobileNumberException: Mobile number and alternate mobile number are same ";
if (mobile.equals(alternateMobile)) {
}-----------
public ContactDetail(String mobile, String alternateMobile, String landLine, String email, String
address) {
this.mobile = mobile;
this.alternateMobile = alternateMobile;
this.landLine = landLine;
this.email = email;
this.address = address;
public ContactDetail()
return mobile;
this.mobile = mobile;
return alternateMobile;
this.alternateMobile = alternateMobile;
return landLine;
return email;
this.email = email;
return address;
this.address = address;
return "Mobile:"+this.mobile+"\nAlternate
mobile:"+this.alternateMobile+"\nLandLine:"+this.landLine+"\nEmail:"+this.email+"\nAddress:"+this.ad
dress;
import java.io.*;
String st = br.readLine();
try {
BO.validate(str[0], str[1]);
System.out.println(userInfo.toString());
} catch (DuplicateMobileNumberException e) {
System.out.println(e.toString());
SeatNotAvailableException
An organization is organizing a charity fate for the well being of poor kids. Since the
manager was running short on time, he asked you to help him with the ticket bookings.
You being from a programming background decide to design a program that asks the
user about the seat number they want. Seat booking details are stored in an array. If the
seat number requested is available booking should be done else print the message
" SeatNotAvailableException". If the seat number requested is not in the range throws
an exception ArrayIndexOutOfBoundsException.
Create an array of size n*n (n rows each with n seats) which is got from the user. Get the
tickets to be booked from the user and handle any exception that occurs in Main Class.
(Take seat numbers from 0 to (n*n)-1)
Note: Vacant seats are denoted by (0) and booked seats by (1). Show message as
"Already Booked" as a Custom exception.
[All Texts in bold corresponds to the input and rest are output]
Sample Input and Output 1:
public SeatNotAvailableException(String s) {
super(s);
}
----------------------------------------------------------------------------------------------------------
import java.util.Scanner;
import java.io.*;
int n = sc.nextInt();
int s;
try {
for(int i=0;i<seats;i++) {
s = sc.nextInt();
if(a[s]==0) {
a[s] =1;
int t=0;
for(int j=0;j<n;j++) {
for(int k=0;k<n;k++) {
mat[j][k] = a[t];
t++;
}else {
}catch (Exception e) {
System.out.println(e);
finally {
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
System.out.print(mat[i][j]+" ");
System.out.println();
}
Parse Exception
For our application, we would have obtained date inputs. If the user enters a different
format other than specified, an Invalid Date Exception occurs and the program is
interrupted. To avoid that, handle the exception and prompt the user to enter the right
format as specified.
Create a driver class called Main. In the main method, Obtain start time and end time for
stage event show, if an exception occurs, handle the exception and notify the user about
the right format.
Input format:
The input consists of the start date and end date.
The format for the date is dd-MM-yyyy-HH:mm:ss
Output format:
Refer sample Input and Output for formatting specifications
Note: All text in bold corresponds to the input and rest corresponds to the output.
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
String d,d1;
try{
d=s.next();
String d2=sdf.format(sdf.parse(d));
d1 =s.next();
String d3=sdf.format(sdf.parse(d1));
System.out.println("Start date:"+d2);
System.out.println("End date:"+d3);
}catch (ParseException e) {
Arithmetic Exception
An exception is an unwanted or unexpected event, which occurs during the execution
of a program i.e at runtime, it disrupts the normal flow of the program. For example,
there are 10 statements in your program and there occurs an exception at statement 5,
the rest of the code will not be executed i.e. statement 6 to 10 will not run. If we
perform exception handling, the rest of the statement will be executed. That is why we
use exception handling.
For practice in exception handling, obtain the cost for 'n' days of an item and n as input
and calculate the cost per day for the item. In case, zero is given as input for n, an
arithmetic exception is thrown, handle the exception and prompt the user accordingly.
Create a driver class called Main. In the Main method, obtain input from the user and
store the values in int type. Handle exception if one occurs.
Input format:
The first line of input is an integer which corresponds to the cost of the item for n days.
The second line of input is an integer which corresponds to the value n.
Output format:
If the value of n is zero throws an exception.
Otherwise, print the integer output which corresponds to the cost per day of the item.
NOTE: All text in bold corresponds to the input and rest corresponds to the output.
import java.util.*;
try{
}catch(ArithmeticException e){
System.out.println(e);
}
ArrayIndexOutOfBoundsException
The next prominent exception which you will see is ArrayIndexOutOfBoundsException.
It occurs when the program tries to access the array beyond its size. As we know arrays
have fixed size. So when you try to use array beyond its size it throws this exception.
Let's try to handle this exception.
Handling this exception will also prove to be good for our application. For example, if
there are only 100 seats in the event and the user tries to book the 105th seat, it will
throw this exception. So you must handle it to do a specific job.
Create an array of size 100 and assume it as seat array. Get the tickets to be booked
from the user and handle any exception that occurs in Main Class. At last display all the
tickets booked.
Note: All Texts in bold corresponds to the input and rest are output.
import java.util.Scanner;
int n,count = 1;
try{
for(int i=0;i<n;i++) {
count = sc.nextInt();
seatArray[count-1] = count;
if(seatArray[i] != 0){
System.out.println(seatArray[i]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
Single inheritance
Write a Java program to implement Single Inheritance.
[Note : Strictly adhere to the object oriented specifications given as a part of the
problem statement. Use the same class names and member variable names.
Follow the naming conventions mentioned for getters / setters. Create separate classes
in separate files. Do not create the classes within namespaces]
Create an another class Main and write a main method to test the above class.
In the main( ) method, read the person and donor details from the user and call the
displayDonationDetails( ) method.
Sample Input/Output:
Enter the name :
Justin
Enter Date of Birth :
11-01-1995
Enter Gender :
Male
Enter Mobile Number :
9994910354
Enter Blood Group :
B+ve
Enter Blood Bank Name :
Blood Assurance
Enter Donor Type :
Whole Blood
Enter Donation Date :
09-07-2017
Donation Details :
Name : Justin
Date Of Birth : 11-01-1995
Gender : Male
Mobile Number : 9994910354
Blood Group : B+ve
Blood Bank Name : Blood Assurance
Donor Type : Whole Blood
Donation Date : 09-07-2017
public Donor() {
return bloodBankName;
}
public void setBloodBankName(String bloodBankName) {
this.bloodBankName = bloodBankName;
return donorType;
this.donorType = donorType;
return donationDate;
this.donationDate = donationDate;
System.out.println("Name : "+getName());
System.out.println("Gender : "+getGender());
class Person{
Person(){
return name;
}
public void setName(String name) {
this.name = name;
return dateOfBirth;
this.dateOfBirth = dateOfBirth;
return gender;
this.gender = gender;
}
public String getMobileNumber() {
return mobileNumber;
this.mobileNumber = mobileNumber;
return bloodGroup;
this.bloodGroup = bloodGroup;
import java.util.Scanner;
public class Main {
d.setName(sc.nextLine());
d.setDateOfBirth(sc.nextLine());
d.setGender(sc.nextLine());
d.setMobileNumber(sc.nextLine());
d.setBloodGroup(sc.nextLine());
d.setBloodBankName(sc.nextLine());
d.setDonorType(sc.nextLine());
System.out.println("Enter Donation Date :");
d.setDonationDate(sc.nextLine());
d.displayDonationDetails();
}
Calculate Reward Points
[Note: Strictly adhere to the object-oriented specifications given as a part of
the problem statement.
Follow the naming conventions as mentioned. Create separate classes in
separate files.]
ABC Bank announced a new scheme of reward points for a transaction using an ATM
card. Each transaction using the normal card will be provided by 1% of the transaction
amount as reward point. If a transaction is made using a premium card and it is for fuel
expenses, additional 10 points will be rewarded. Help the bank to calculate the total
reward points.
Hint:
Use super keyword to calculate reward points from base class.
Card type will be either ‘VISA card’ or ‘HPVISA card’. Otherwise, display ‘Invalid data’
Calculate the reward points corresponding to the card type and transaction type and
print the reward points(upto two precision).
if(type.equalsIgnoreCase("Fuel")) {
total=total+10;
return total;
}else{
return total;
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
double amount = 0;
do {
tDetails = sc.nextLine();
transactionType = dSplit[0];
amount = Double.parseDouble(dSplit[1]);
cardType = dSplit[2];
if (cardType.equals("VISA card")) {
+ df.format(v.computeRewardPoints(transactionType,
amount)));
flag = sc.nextLine();
+ df.format(h.computeRewardPoints(transactionType,
amount)));
flag = sc.nextLine();
} else {
System.out.println("Invalid data");
flag = sc.nextLine();
} while (flag.equals("Yes"));
GST Calculation
[Note :
Strictly adhere to the object oriented specifications given as a part of the problem
statement.
Follow the naming conventions as mentioned. Create separate classes in separate files.]
Write a program to calculate the total amount with GST for the events. There are two
types of Events Stage show and Exhibition. For Stage show GST will be 15% and for
exhibition GST will be 5%
Create Main class with main method.
In the main() method, read the event details from the user and then create the object of
the event according to the event type.
The total amount will be calculated according to the GST of the corresponding event.
Display the total amount upto two precision.
import java.util.*;
import java.text.DecimalFormat;
public class Main {
double cpd;
int npd;
name = sc.nextLine();
cpd = sc.nextDouble();
npd = sc.nextInt();
sc.nextLine();
type = sc.nextLine();
switch (type) {
case "1":
break;
case "2":
break;
default:
System.out.println("Invalid input");
break;
class Event{
super();
this.name = name;
this.type = type;
this.costPerDay = costPerDay;
this.noOfDays = noOfDays;
int noOfSeats;
public StageEvent(String name, String type, double costPerDay, int noOfDays, int noOfSeats) {
this.noOfSeats = noOfSeats;
}
return total;
@Override
int noOfStalls;
public Exhibition(String name, String type, double costPerDay, int noOfDays, int noOfStalls) {
this.noOfStalls = noOfStalls;
return total;
}
@Override
Abstract Event
Let's have a practice in creating an Abstract class for the Event. In this application create
an abstract class Event, StageEvent class and a class Exhibition with the provided
attributes and let's implement an abstract method to calculate the total cost of the event
and print the details of the particular event of this application.
Create a driver class called Main. In the main method, obtain input from the user and
create objects accordingly.
Input format:
Input format for Exhibition is in the CSV format
(name,detail,type,organiser,noOfStalls,rentPerStall)
Input format for StageEvent is in the CSV
format (name,detail,type,organiser,noOfShows,costPerShow)
Output format:
Print "Invalid choice" if the input is invalid to our application and terminate.
Display one digit after the decimal point for Double datatype.
Refer to sample Input and Output for formatting specifications.
Note: All text in bold corresponds to the input and rest corresponds to output.
public Exhibition(String name, String detail, String type, String organiser, Integer noOfStalls,
Double rentPerStall) {
this.noOfStalls = noOfStalls;
this.rentPerStall = rentPerStall;
Double calculateAmount() {
public StageEvent(String name, String detail, String type, String organiser, Integer noOfShows,
Double costPerShow) {
this.noOfShows = noOfShows;
this.costPerShow = costPerShow;
Double calculateAmount() {
this.detail = detail;
this.type = type;
this.organiser = organiser;
return name;
this.name = name;
return detail;
this.detail = detail;
return type;
return organiser;
this.organiser = organiser;
import java.util.Scanner;
System.out.println("1.Exhibition");
System.out.println("2.StageEvent");
int ch = sc.nextInt();
switch (ch) {
case 1:
sc.nextLine();
s = sc.nextLine();
detail = split[1];
type = split[2];
organiser = split[3];
noOfStalls = Integer.parseInt(split[4]);
rentPerStall = Double.parseDouble(split[5]);
totalCost = e.calculateAmount();
System.out.println("Exhibition Details");
System.out.println("Detail:" + e.getDetail());
System.out.println("Type:" + e.getType());
break;
case 2:
sc.nextLine();
s = sc.nextLine();
name = split1[0];
detail = split1[1];
type = split1[2];
organiser = split1[3];
noOfShows = Integer.parseInt(split1[4]);
costPerShow = Double.parseDouble(split1[5]);
System.out.println("Detail:" + se.getDetail());
System.out.println("Type:" + se.getType());
break;
default:
System.out.println("Invalid choice");
break;
Overriding-simple
Overriding is another concept that every application developer should know. Overriding
is a runtime polymorphism. The inherited class has the overridden method which has the
same name as the method in the parent class. The argument number, types or return
types should not differ in any case. The method is invoked with the object of the specific
class ( but with the reference of the parent class).
Now let's try out a simple overriding concept in our application. For this, we can take our
original example of Class Event, and its child classes Exhibition and StageEvent.
[All Texts in bold corresponds to the input and rest are output]
Sample Input/Output 1:
Sample Input/Output 2:
public StageEvent()
{}
super(name,detail,ownerName);
this.name = name;
this.detail = detail;
this.ownerName = ownerName;
this.noOfShows = noOfShows;
this.noOfSeatsPerShow = noOfSeatsPerShow;
@Override
return revenue;
public Event(){
this.name = name;
this.detail = detail;
this.ownerName = ownerName;
}
return 0.0;
import java.io.IOException;
import java.util.Scanner;
double totalrevenue = 0;
switch(choice){
case 1 :
totalrevenue = exObj.projectedRevenue();
break;
case 2 :
totalrevenue = seObj.projectedRevenue();
break;
default : break;
}
}
public Exhibition()
super(name,detail,ownerName);
this.name = name;
this.detail = detail;
this.ownerName = ownerName;
this.noOfStalls = noOfStalls;
@Override
return revenue;
}
Java Interfaces
Consider a Banking Scenario, There are many accounts, like Savings Account, Current
Account, Demat Account and so on. We have a base Class Account which contains all
the basic properties and methods of an Account. We do have some Maintainance
Charges that apply to only some of the accounts. If you would like to enforce that the
Savings Account & Current Account should have maintenance charges, then the simplest
way is to ask your class implement the interface. If you do not implement the method in
the class, it would raise a compilation error.
So, Java Interfaces essentially gives acts like a contract where its given that the methods
declared in the interface has to be implemented in the class. Lets code the above
Scenario.
Create a class named Account with following private attributes
Attribute Datatype
name String
accountNumber String
balance double
startDate String
Include appropriate getters and setters.
Include appropriate parameterized constructors
@Override
class Account {
String name;
String accountNumber;
double balance;
String startDate;
super();
this.name = name;
this.accountNumber = accountNumber;
this.balance = balance;
this.startDate = startDate;
return name;
this.name = name;
return accountNumber;
this.accountNumber = accountNumber;
return balance;
}
this.balance = balance;
return startDate;
this.startDate = startDate;
@Override
}
import java.text.DecimalFormat;
import java.util.*;
double accountBalance;
int years;
System.out.println("1.Current Account");
System.out.println("2.Savings Account");
int n = s.nextInt();
switch (n) {
case 1:
System.out.println("Name");
name = s.next();
System.out.println("Account Number");
account = s.next();
System.out.println("Account Balance");
accountBalance = s.nextInt();
s.nextLine();
sdate = s.nextLine();
years = s.nextInt();
System.out
.println("Maintenance Charge For Current Account " +
df.format(c.calculateMaintanceCharge(years)));
break;
case 2:
System.out.println("Name");
name = s.next();
System.out.println("Account Number");
account = s.next();
System.out.println("Account Balance");
accountBalance = s.nextInt();
s.nextLine();
sdate = s.nextLine();
years = s.nextInt();
System.out
break;
default:
System.out.println("Invalid choice");
break;
}
Interface
The Interface defines a rule that any classes that implement it should override all the
methods. Let's implement Interface in our application. We'll start simple, by including
display method in the Stall interface. Now all types of stalls that implement the interface
should override the method.
Input Format:
The first input corresponds to choose the stall type.
The next line of input corresponds to the details of the stall in CSV format according to
the stall type.
Output Format:
Print “Invalid Stall Type” if the user has chosen the stall type other than the given type
Otherwise, display the details of the stall.
Refer to sample output for formatting specifications.
Note: All Texts in bold corresponds to the input and rest are output
ChooseStall Type
1)Gold Stall
2)Premium Stall
3)Executive Stall
2
Enter Stall details in comma separated(Stall Name,Stall Cost,Owner Name,Number of
Projectors)
Knitting plaza,300000,Zain,20
Stall Name:Knitting plaza
Cost:300000.Rs
Owner Name:Zain
Number of Projectors:20
ChooseStall Type
1)Gold Stall
2)Premium Stall
3)Executive Stall
3
Enter Stall details in comma separated(Stall Name,Stall Cost,Owner Name,Number of
Screens)
Fruits Hunt,10000,Uber,7
Stall Name:Fruits Hunt
Cost:10000.Rs
Owner Name:Uber
Number of Screens:7
ChooseStall Type
1)Gold Stall
2)Premium Stall
3)Executive Stall
4
Invalid Stall Type
public PremiumStall() {
public ExecutiveStall() {
}
import java.util.Scanner;
switch (n) {
case 1:
scan.nextLine();
System.out.println(
"Enter Stall details in comma separated(Stall
Name,Stall Cost,Owner Name,Number of TV sets)");
stallDetails = scan.nextLine();
arr = stallDetails.split(",");
break;
case 2:
scan.nextLine();
System.out.println(
"Enter Stall details in comma separated(Stall
Name,Stall Cost,Owner Name,Number of Projectors)");
stallDetails = scan.nextLine();
arr = stallDetails.split(",");
cost = Integer.parseInt(arr[1]);
num = Integer.parseInt(arr[3]);
stallDetails = scan.nextLine();
arr = stallDetails.split(",");
cost = Integer.parseInt(arr[1]);
num = Integer.parseInt(arr[3]);
}
}
public class GoldStall implements Stall {
public GoldStall() {
Round up - Interfaces
In one of the earlier exercises in Interfaces, we looked at how banks encrypt & decrypt
transaction details to ensure safety. We also saw understood that each of them complies
with the methods specified by the Governing Agency in the form of an interface. To
Round-off interfaces, let's look at a similar example, where the governing agency
mandates that any customer who performs a transaction has to be notified through SMS,
Email and a monthly e-statement. As expected, we define an interface Notification and
three methods as specified below. Lets code this example.
Create an interface named Notification with the following methods
notificationBySms( ),
notificationByEmail( ),
notificationByCourier( ).
Create a class named ICICI which implements Notification interface
Create a class named HDFC which implements Notification interface
[Note: All text in bold corresponds to the input and remaining text corresponds to
output]
@Override
public void notificationBySms() {
System.out.println("ICICI - Notification By SMS");
}
@Override
public void notificationByEmail() {
System.out.println("ICICI - Notification By Mail");
}
@Override
public void notificationByCourier() {
System.out.println("ICICI - Notification By Courier");
}
}
public class HDFC implements Notification {
@Override
public void notificationBySms() {
System.out.println("HDFC - Notification By SMS");
}
@Override
public void notificationByEmail() {
System.out.println("HDFC - Notification By Mail");
}
@Override
public void notificationByCourier() {
System.out.println("HDFC - Notification By Courier");
}
}
public interface Notification {
}
public class BankFactory {
Get the option for the shape to compute the area and get the attribute according to the
shape option and set the values to the Shape class attributes. Calculate the area and
print the area.
While printing round off the area to 2 decimal formats.
Input Format
The first line of the input is an integer corresponds to the shape.
The next line of inputs are Double which corresponds to,
For Rectangle(Option 1) get the length and breadth.
For Triangle(Option 2) get the base and height.
Output Format
The output consists area of the shape.
Print the double value correct to two decimal places.
Print “Invalid choice”, if the option for the shape is chosen other than the given options.
Refer to sample output for formatting specifications.
Sample Input/Output 2:
Enter the shape
1.Rectangle
2.Triangle
2
Enter the base and height:
15
19
Area of triangle is 142.50
Sample Input/Output 3:
Enter the shape
1.Rectangle
2.Triangle
3
Invalid choice
Article count
Multithreading is a Java feature that allows concurrent execution of two or more parts of
a program for maximum utilization of CPU. Each part of such a program is called a
thread. The threads are light-weight processes within a process.
Let's have a quick look at the way threads work in Java. For multi-threading to work, the
class that will be invoked as a thread should extend the Thread class. You may wonder,
what is the use of multi-threading. Let's understand it by the following exercise. Given 'n'
number of lines of text, you have to find the total number of articles present in the given
lines. while obtaining inputs from the user, the Main method has the full control of the
execution.
The time is wasted in input gathering, which can be invaluable for large computing
applications, has to be utilized properly. Hence a thread is invoked when a line is
obtained and the articles are counted while the input for the subsequent lines is
obtained from the user. Thus threading can increase efficiency and time constraints.
Create a driver class called Main. In the Main method, invoke 'n' threads for 'n' lines of
input and compute the total count of the articles in the given lines.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String line;
int count;
public Article() {
super();
}
public Article(String line) {
super();
this.line = line;
return line;
this.line = line;
return count;
this.count = count;
@Override
Matcher m = Pattern.compile("(?i)\\b((a)|(an)|(the))\\b").matcher(this.getLine());
while (m.find()) {
this.count++;
}
}
import java.util.Scanner;
int n = sc.nextInt();
int count = 0;
sc.nextLine();
for(int i=0;i<n;i++) {
a.setLine(sc.nextLine());
a.start();
a.join();
count +=a.getCount();
}
Profit or Loss
We are going to create a console application that can estimate whether the booking is a
profit or loss, thereby enabling hall owners to reduce or increase expenses depending on
the status. Hence if several Booking details are given, compute whether the bookings are
profitable or not. Use Threads to compute for each booking, Finally display the details
along with the profit/loss status.
Output Format:
The output consists of event names with their status (Profit or Loss).
Refer to sample output for formatting specifications.
Problem Constraints:
If n>0 and n then even. Otherwise, display as "Invalid Input".
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public Event() {
}
@Override
public void run() {
// System.out.println(Thread.currentThread().getName());
Iterator iterator = eventList.iterator();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (iterator.hasNext()) {
Event e = (Event) iterator.next();
if (e.getHallBooking().getSeatsBooked() * 100 /
e.getHallBooking().getHallCapacity() >= 60) {
System.out.println(e.getName() + " yields profit");
} else {
System.out.println(e.getName() + " yields loss");
}
}
}
}
public class HallBooking {
private String hallName;
private Double cost;
private Integer hallCapacity;
private Integer seatsBooked;
All three worker threads are concurrently executed on shared or dedicated CPUs
depending on the type of machine. Although the master thread can continue its
execution, in this case, it needs to make sure that all operations are completed before
combining individual results. This is accomplished by waiting for each thread to complete
by invoking join() method associated with each worker thread.
The main thread is called Main, which acts like a master thread. It creates three worker
threads (SineClass, CosClass, and TanClass) and assigns them to compute values for
different data inputs.
Hint:
Use the following code snippet to print to 2 decimal places.
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("Sum of sin, cos, tan = " + df.format(z));
@Override
public void run() {
double b = Math.toRadians(cos);
value = Math.cos(b);
}
public double getValue() {
return value;
}
@Override
public void run() {
double b = Math.toRadians(sins);
value = Math.sin(b);
return value;
}
@Override
public void run() {
double b = Math.toRadians(tan);
value = Math.tan(b);
}
return value;
}
import java.text.DecimalFormat;
import java.util.Scanner;
s.start();
try {
s.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
c.start();
try {
c.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Wrapper Class – 1
Write a Java program to print the following static values defined in the Float Wrapper
Class
Sample Output:
Maximum exponent :127
Maximum value :3.4028235E38
Number of bits :32
import java.util.Date;
import java.util.Scanner;
import java.io.IOException;
import java.text.*;
billHeader.setIssueDate(issueDate);
billHeader.setDueDate(dueDate);
billHeader.setOriginalAmount(originalAmount);
billHeader.setAmountOutstanding(amountOutstanding);
public BillHeader() {
}
@Override
public String toString() {
import java.lang.*;
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
// fill your code here
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string");
String str = scan.nextLine();
System.out.println("Enter the start string");
// fill your code here
String chk = scan.nextLine();
if(str.startsWith(chk) )
{
System.out.println('"' + str + '"'+ " starts with "+ '"'+ chk+'"');
}
else
{
System.out.println('"' + str + '"'+ " does not start with "+ '"'+ chk+'"');
}
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
// fill your code here
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string");
String str = scan.nextLine();
String str2 = str.replaceAll(" +", " ");
String str1[] = str2.split(" ",-1);
System.out.println("The words in the string are");
for(int i = 0; i < str1.length; i++)
{
System.out.println(str1[i]);
}
}
}
String Tokenizer
Write a Java program to implement string tokenizer inorder to split a string into two
different tokens by =(equal to) and ;(semicolon).
Input Format:
Input is a string which needs to be split.
Output Format:
Each line of the Output contains two strings. The first string is formed by token '=' and
the second string is formed by the token ';'
Assume: The tokens, '=' and ';', will always come alternately. Refer Sample Input.
Sample Input:
title=Java-Samples;author=Emiley J;publisher=java-samples.com;copyright=2007;
Sample Output:
title Java-Samples
author Emiley J
publisher java-samples.com
copyright 2007
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();
StringTokenizer s1 = new StringTokenizer(s, "=");
String s2 = "";
while(s1.hasMoreTokens()) {
s2 = s2+" "+s1.nextToken();
}
StringTokenizer s3 = new StringTokenizer(s2, ";");
while(s3.hasMoreTokens()) {
System.out.println(s3.nextToken());
}
}
}
StringBuilder would append values in a normal heap instead of any common string pools.
The only difference between StringBuilder & StringBuffer is: StringBuilder is not Thread-
Safe whereas StringBuffer is Thread-Safe.
Let's try out using StringBuilder.
Write a Java Program to display the address of the customer in a particular format.
Create a main class "Main.java".
Create another class file "Address.java" with the following private members.
Data Type Variable name
String line1
String line2
String city
String country
int zipCode
Include appropriate getters and setters.
Use 'toString' method in the Address class and append using String Builder.
Input and Output Format:
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output]
Sample Input & Output:
Enter Address Details :
Enter Line 1 :
152, South Block
Enter Line 2 :
Raisina Hill
Enter City :
New Delhi
Enter Country :
India
Enter Zip Code :
110011
Address Details :
152, South Block,
Raisina Hill,
New Delhi - 110011
India
public Address() {
super();
// TODO Auto-generated constructor stub
}
public Address(String line1, String line2, String city, String country, int zipCode) {
super();
this.line1 = line1;
this.line2 = line2;
this.city = city;
this.country = country;
this.zipCode = zipCode;
}
@Override
public String toString() {
return "Address Details :\n" + new StringBuilder().append(this.getLine1()) + ",\n" + new
StringBuilder().append(this.getLine2()) + ",\n"
+ new StringBuilder().append(this.getCity()) + " - " + new
StringBuilder().append(this.getZipCode()) + "\n"
+ new StringBuilder().append(this.getCountry());
}
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
// fill your code here
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the string");
String str = scnr.nextLine();
System.out.println("Enter the end string");
String strEnd = scnr.nextLine();
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter the binary number");
String binaryNo = scnr.next();
}
}
Lets check the above concept by validating Emailids of two customers first by using
equals & equalsIgnoreCase methods.
Create a main class "Main.java".
Create another class file "Customer.java" with following private member variables.
Data Type Variable Name
String name
String email
Include appropriate getters and setters.
Use 'equals()' and 'equalsIgnoreCase()' to compare the email ids[Refer sample input &
output ].
She noticed that the date being displayed inside the flight in an LED Board was wrong.
She asked help from a few electronics engineers who were on board. The electronics
engineers figure out that the binary forms of the date, month and year were 2 bits, 2
bits and 2 bits rotated left. Now the engineers will need to fix this. Given the incorrect
date, month and the year use the Integer Wrapper Class rotateRight() method to print
the correct date in International format.
Input Format:
The first line is an integer that corresponds to the incorrect day number.
The second line is an integer that corresponds to the incorrect month number.
The third line is an integer that corresponds to the incorrect year.
Output Format:
The Output should display the correct date in a single line separated by slashes in the
international format.
Sample Input:
20
36
7944
Sample Output:
1986/9/5
Exception All Around !
You start thinking -- Are exceptions around to catch only the alternate flows /
mistakes made by end-users. Exceptions mean exceptions !!! It can even be
used in business rules. A simple example would be to raise an exception
when a customer's unpaid credit card amount cross $2000 or is unpaid upto
45 days. Lets write a program that would check these details and raise a
custom exception stating "Further Transactions Not Possible until clearance of
bill.". Assume that the current date is '01/12/2015'.
import java.text.*;
class Account{
String accountNumber;
String accountName;
Double dueAmount;
Account(){}
Account(String a,String b,Double c){
accountNumber=a;
accountName=b;
dueAmount=c;
}
boolean validate(String a,Double b,Double c) throws ParseException{
if(b>(double)2000)
return false;
String a1[]=a.split("/");
if(a1[2].equals("2016"))
return true;
else{
int n=2015-Integer.parseInt(a1[2]);
int m=11-Integer.parseInt(a1[1]);
int d=31-Integer.parseInt(a1[0]);
//System.out.println(n*365+m*30+d);
if(n*365+m*30+d>15)
return false;
return true;
}
}
void display(){
System.out.println("Transaction successsfully completed.");
System.out.println("Account Number : "+accountNumber);
System.out.println("Account Name : "+accountName);
System.out.println("Unpaid Amount : "+dueAmount);
}
}
class OverLimitException extends Exception{
public OverLimitException(String c){
super(c);
}
}
Path : /Main.java
import java.util.*;
import java.text.*;
import java.util.concurrent.TimeUnit;
class Main{
public static void main(String[] args) throws ParseException{
Scanner s=new Scanner(System.in);
String a,b,e;
Double c,d;
System.out.println("Enter the transaction details\nEnter the account number");
a=s.nextLine();
System.out.println("Enter the account holder name");
b=s.nextLine();
System.out.println("Enter the last due date");
e=s.nextLine();
System.out.println("Enter the unpaid amount\nEnter the transaction amount");
c=Double.parseDouble(s.nextLine());
d=Double.parseDouble(s.nextLine());
Account a1=new Account(a,b,c+d);
if(!a1.validate(e,c,d))
System.out.println("Further Transactions Not Possible until clearance of bill.");
else{
a1.display();
}
}
}