All 17 PDF Free

Download as pdf or txt
Download as pdf or txt
You are on page 1of 636

Factorial(number):

SET Fact = 1 and i = 1

WHILE i<=number

SET Fact=Fact*i

SET i=i+1

ENDWHILE

PRINT Fact

END

NumberOfDigits(number):

SET count=0

WHILE (number > 0):

SET count=count+1 and SET number=number/10

ENDWHILE

PRINT count

END

NumberOfDigits(number):

SET count=0

WHILE (number > 0):

SET count=count+1 and SET number=number/10

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)

Note in the above array 12 must not considered as such

i.e,it must be considered as 1,2


package Set3;

public class ClassSeT01 {

public static void main(String[] args) {

String[] s1={"2AA","12","A2C","C5a"};

getSum(s1); }

public static void getSum(String[] 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

Input:{“goa”,”kerala”,”gujarat”} [string array]

Output:{{GOA,goa},{KER,kerala},{GUJ,Gujarat}} [hashmap]

package Set3;

import java.util.*;

public class ClassSeT02 {

public static void main(String[] args) {

String[] s1={"goa","kerala","gujarat"};

putvalues(s1);

public static void putvalues(String[] s1) {

ArrayList<String> l1=new ArrayList<String>();


HashMap<String,String> m1=new HashMap<String,String>();

ArrayList<String> l2=new ArrayList<String>();

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]

expected output String: "Vikas,Lokesh,Ashok"

package Set3;

public class ClassSeT03 {

public static void main(String[] args) {

String[] ip={"Vikas","Lokesh","Ashok"};

System.out.println(getTheNamesinGivenFormat(ip));

public static String getTheNamesinGivenFormat(String[] ip) {

StringBuffer sb=new StringBuffer();

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;

2)@ & . should not be repeated;

3)there should be five charcters between @ and .;

4)there should be atleast 3 characters before @ ;

5)the end of mail id should be .com;

package Set3;

import java.util.*;

public class ClassSeT04 {

public static void main(String[] args) {

String ip="[email protected]";

boolean b=emailIdValidation(ip);

if(b==true)

System.out.println("valid mail Id");

else

System.out.println("not a valid Id");

public static boolean emailIdValidation(String ip) {

int i=0;

boolean b=false;

StringTokenizer t=new StringTokenizer(ip,"@");

String s1=t.nextToken();

String s2=t.nextToken();

StringTokenizer t1=new StringTokenizer(s2,".");

String s3=t1.nextToken();

String s4=t1.nextToken();

if(ip.contains("@") && ip.contains("."))

i++;

if(i==1)

if(s3.length()==5)

if(s1.length()>=3)
if(s4.equals("com"))

b=true;

return b;

----------------------------------------------------------------------------------------------------||

5) Square root calculation of

((x1+x2)*(x1+x2))+((y1+y2)*(y1+y2))

o/p should be rounded of to int;

package Set3;

public class ClassSeT05 {

public static void main(String[] args) {

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);

----------------------------------------------------------------------------------------------------||

6) I/P hashmap<String String>{"ram:hari","cisco:barfi","honeywell:cs","cts:hari"};

i/p 2="hari";

o/p string[]={"ram","cts"};

package Set3;

import java.util.*;

import java.util.Map.Entry;

public class ClassSeT06 {


public static void main(String[] args) {

HashMap<String,String> m1=new HashMap<String,String>();

m1.put("ram","hari");

m1.put("cisco","barfi");

m1.put("honeywell","cs");

m1.put("cts","hari");

String s2="hari";

getvalues(m1,s2);

public static void getvalues(HashMap<String, String> m1, String s2) {

ArrayList<String>l1=new ArrayList<String>();

for(Entry<String, String> m:m1.entrySet()){

m.getKey();

m.getValue();

if(m.getValue().equals(s2))

l1.add(m.getKey()); }

String[] op= new String[l1.size()];

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.*;

public class ClassSeT07 {

public static void main(String[] args) {

String[] s1={"abc","da","ram","cat"};
int ip=3;

getStr(s1,ip);

public static void getStr(String[] s1, int ip) {

String op=" ";

String s2=" ";

ArrayList<String> l1=new ArrayList<String>();

for(String s:s1)

if(s.length()==ip)

l1.add(s);

StringBuffer buff=new StringBuffer();

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

INPUT2= 2. delete the char,if rpted twice.

if occurs more than twice,leave the first occurence and delete the duplicate

O/P= helwrd;

package Set3;

public class ClassSeT08 {

public static void main(String[] args) {

String input1="HelloWorld";

int input2=2;

System.out.println(deletingtheCharOccuringTwice(input1,input2));

public static String deletingtheCharOccuringTwice(String input1, int input2) {


StringBuffer sb=new StringBuffer(input1);

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();

----------------------------------------------------------------------------------------------------||

9) String[] input={"100","111","10100","10","1111"} input2="10"

output=2;count strings having prefix"10" but "10" not included in count

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.*;

public class ClassSeT09 {

public static void main(String[] args) {

String[] ip={"100","111","10100","10","1111"};

gteCount(ip);

public static void gteCount(String[] ip) {


int op=0;

ArrayList<String> l1=new ArrayList<String>();

for(String s:ip)

if(s.startsWith("10") || s.startsWith("01") &&(s.length()>2))

l1.add(s);

op=l1.size();

System.out.println(op);

----------------------------------------------------------------------------------------------------||

10) input1=1 ,input2=2 ,input3=3 --- output=6;

input1=1 ,input2=13,input3=3 --- output=1;

input1=13,input2=2 ,input3=8 --- output=8;

if value equal to 13,escape the value '13', as well as the next value to 13.

sum the remaining values

package Set3;

import java.util.*;

public class ClassSeT10 {

public static void main(String[] args) {

int ip1=13,ip2=2,ip3=8;

System.out.println(thirteenLapse(ip1,ip2,ip3));

public static int thirteenLapse(int ip1, int ip2, int ip3) {

List<Integer> l=new ArrayList<Integer>();

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"

output="hlo"; Alternative positions...

package Set3;

public class ClassSeT11 {

public static void main(String[] args) {

String s="Hello";

System.out.println(alternatingChar(s));

public static String alternatingChar(String s){

StringBuffer sb=new StringBuffer();

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

if(i%2==0)

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

return sb.toString();

----------------------------------------------------------------------------------------------------||

12) Input1=”Hello World”; output-------à “dello WorlH”.

package Set3;

public class ClassSeT12 {

public static void main(String[] args) {

String s="Hello World";

System.out.println(reArrangingWord(s));

}
public static String reArrangingWord(String s) {

StringBuffer sb=new StringBuffer();

sb.append(s.substring(s.length()-1));

sb.append(s.substring(1, s.length()-1));

sb.append(s.substring(0, 1));

return sb.toString();

----------------------------------------------------------------------------------------------------||

13) Collect no’s frm list1 which is not present in list2

& Collect no’s frm list2 which is not present in list1

and store it in output1[].

ex: input1={1,2,3,4}; input2={1,2,3,5}; output1={4,5};

package Set3;

import java.util.*;

public class ClassSeT13 {

public static void main(String[] args) {

List<Integer> l1=new ArrayList<Integer>();

l1.add(1);

l1.add(2);

l1.add(3);

l1.add(4);

List<Integer> l2=new ArrayList<Integer>();

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) {

List<Integer> l3=new ArrayList<Integer>();

List<Integer> l4=new ArrayList<Integer>();

l3.addAll(l1);l4.addAll(l2);

l1.removeAll(l2);l4.removeAll(l3);

l1.addAll(l4);

int o[]=new int[l1.size()];

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;

public class ClassSeT14 {

public static void main(String[] args) {

String[] a={"pinky","preethi","puppy","preeth","puppypreethi"};

System.out.println(namesWithPreFixes(a));

public static int namesWithPreFixes(String[] 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;
}

----------------------------------------------------------------------------------------------------||

15) count the number of words in the string

Input string="i work in cognizant.";

output=4;

package Set3;

import java.util.StringTokenizer;

public class ClassSeT15 {

public static void main(String[] args) {

String s="I work for cognizant";

System.out.println(noOfWordsInString(s));

public static int noOfWordsInString(String s) {

StringTokenizer t=new StringTokenizer(s," ");

return t.countTokens();

----------------------------------------------------------------------------------------------------||

16) int[] input={2,1,4,1,2,3,6};

check whether the input has the sequence of "1,2,3". if so-

output=true;

int[] input={1,2,1,3,4,5,8};

output=false

package Set3;

public class ClassSeT16 {

public static void main(String[] args) {

//int[] a={2,1,4,1,2,3,6};

int[] a={1,2,1,3,4,5,8};

System.out.println(sequenceInArray(a));
}

public static boolean sequenceInArray(int[] 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;

----------------------------------------------------------------------------------------------------||

17) input-- String input1="AAA/abb/CCC"

char input2='/'

output-- String[] output1;

output1[]={"aaa","bba","ccc"};

operation-- get the strings from input1 using stringtokenizer

reverse each string

then to lower case

finally store it in output1[] string array

package Set3;

import java.util.*;

public class ClassSeT17 {

public static void main(String[] args) {

String ip1="AAA/abb/CCC";

char ip2='/';

String op[]=loweringCasenReverseofaString(ip1,ip2);

for(String s:op)

System.out.println(s);
}

public static String[] loweringCasenReverseofaString(String ip1, char ip2){

List<String> l=new ArrayList<String>();

StringTokenizer t=new StringTokenizer(ip1,"/");

while(t.hasMoreTokens()){

StringBuffer sb=new StringBuffer(t.nextToken().toLowerCase());

l.add(sb.reverse().toString()); }

String op[]=new String[l.size()];

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

op[i]=l.get(i);

return op;

----------------------------------------------------------------------------------------------------||

18) Input1=”cowboy”; Output1=”cowcow”;

Input1=”so”;output1=”sososo”;

HINT: if they give 3 letter word u have to display 2 time;

package Set3;

public class ClassSeT18 {

public static void main(String[] args) {

String ip1="cowboy";

String ip2="cow";

System.out.println(printingStringDependingOncharCount(ip1,ip2));

public static String printingStringDependingOncharCount(String ip1,String ip2) {

StringBuffer sb=new StringBuffer();

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;

operation--- print the element which is not repeated

if all the inputs r different sum all inputs

input---input1=1;

input2=2;

input3=3;

output1=6;

package Set3;

public class ClassSeT19 {

public static void main(String[] args) {

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));

public static int sumOfNonRepeatedChars(int ip1, int ip2, int ip3){

int n=0;

if(ip1!=ip2 && ip2!=ip3 && ip3!=ip1)

n=ip1+ip2+ip3;

else if(ip1==ip2 && 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}

operation-- In 1st list remove strings starting with 'a' or 'g'

In 2nd list remove strings ending with 'n' or 'e'

Ignore case, return in string array

package Set3;

import java.util.*;

public class ClassSeT20 {

public static void main(String[] args) {

List<String> l1=new ArrayList<String>();

l1.add("apple");

l1.add("orange");

l1.add("grapes");

List<String> l2=new ArrayList<String>();

l2.add("melon");

l2.add("apple");

l2.add("mango");

String[] s2=fruitsList(l1,l2);

for(String s3:s2)
System.out.println(s3);

public static String[] fruitsList(List<String> l1, List<String> l2){

List<String> l3=new ArrayList<String>();

for(int i=0;i<l1.size();i++){

String s1=l1.get(i);

if(s1.charAt(0)!='a' && s1.charAt(0)!='A' && s1.charAt(0)!='g' && s1.charAt(0)!='G')

l3.add(s1); }

for(int i=0;i<l2.size();i++){

String s1=l2.get(i);

if(s1.charAt(s1.length()-1)!='n' && s1.charAt(s1.length()-1)!='N' && s1.charAt(s1.length()-1)!='e' &&


s1.charAt(s1.length()-1)!='E')

l3.add(s1); }

Collections.sort(l3);

String[] s2=new String[l3.size()];

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

s2[i]=l3.get(i);

return s2;

----------------------------------------------------------------------------------------------------||

21) input1-- Hello*world

output-- boolean(true or false)

operation-- if the character before and after * are same return true else false

if there in no star in the string return false(Ignore case)

package Set3;

import java.util.*;

public class ClassSeT21 {

public static void main(String[] args) {

String input="Hello*world";

System.out.println(characterCheck(input));

}
public static boolean characterCheck(String input) {

boolean b=false;

StringTokenizer t=new StringTokenizer(input,"*");

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;

----------------------------------------------------------------------------------------------------||

22) input --String input1 ="xaXafxsd"

output--String output1="aXafsdxx"

operation-- remove the character "x"(only lower case) from string and place at the end

package Set3;

public class ClassSeT22 {

public static void main(String[] args) {

String input="xaXafxsd";

System.out.println(removalOfx(input));

public static String removalOfx(String input) {

StringBuffer sb=new StringBuffer(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();

----------------------------------------------------------------------------------------------------||

23) HashMap<String,Integer> h1={“abc”:50,”efg”:70};

if the mark is less than 60 then put the output in the

HashMap<String,String> h2={“abc”:”fail”,”efg”:”pass”}

package Set3;

import java.util.*;

public class ClassSeT23 {

public static void main(String[] args) {

Map<String, Integer> m1=new HashMap<String, Integer>();

m1.put("abc", 90);

m1.put("efg", 50);

m1.put("mno", 60);

m1.put("rst", 75);

m1.put("xyz", 35);

System.out.println(examResult(m1));

public static Map<String,String> examResult(Map<String, Integer> m1) {

Map<String,String> m2=new HashMap<String, String>();

String s1=new String();

String s2=new String();

int n=0;

Iterator<String> i=m1.keySet().iterator();

while(i.hasNext()){

s1=(String) i.next();

n=m1.get(s1);

if(n>=60)

s2="PASS";

else
s2="FAIL";

m2.put(s1, s2); }

return m2;

----------------------------------------------------------------------------------------------------||

24) String i/p1=2012;

sTRING i/p2=5

IF EXPERIENCE IS GREATER THAN INPUT 2 THEN TRUE;

package Set3;

import java.text.*;

import java.util.*;

public class ClassSeT24 {

public static void main(String[] args) throws ParseException {

String ip1="2012";

String ip2="5";

System.out.println(experienceCalc(ip1,ip2));

public static boolean experienceCalc(String ip1, String ip2) throws ParseException {

boolean b=false;

SimpleDateFormat sdf=new SimpleDateFormat("yyyy");

Date d1=sdf.parse(ip1);

Date d2=new Date();

int n1=d1.getYear();

int n2=d2.getYear();

int n3=Integer.parseInt(ip2);

if((n2-n1)>n3)

b=true;

return b;

}
----------------------------------------------------------------------------------------------------||

25) input string="hello", n=2

output: lolo

package Set3;

public class ClassSeT25 {

public static void main(String[] args) {

String s1="hello";

int n1=2;

System.out.println(formattingOfString(s1,n1));

public static String formattingOfString(String s1, int n1) {

String s2=s1.substring(s1.length()-n1, s1.length());

StringBuffer sb=new StringBuffer();

for(int i=0;i<n1;i++)

sb.append(s2);

return sb.toString();

----------------------------------------------------------------------------------------------------||

26) prove whether a number is ISBN number or not

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

sum%11==0 then it is ISBN number

package Set3;

public class ClassSeT26 {

public static void main(String[] args) {

String ip="0201103311";

boolean b=ISBNnumber(ip);

if(b==true)

System.out.println("valid ISBN number");


else

System.out.println("check ur data");

public static boolean ISBNnumber(String ip) {

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;

----------------------------------------------------------------------------------------------------||

27) Validate Password

validation based on following criteria:

-> minimum length is 8

-> should contain any of these @/_/#

-> should not start with number/special chars(@/#/_)

-> should not end with special chars

-> can contain numbers,letters,special chars

package Set3;

import java.util.*;

public class ClassSeT40 {

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

String s1=s.next();

boolean b=passwordValidation(s1);
if(b==true)

System.out.println("valid password");

else

System.out.println("not a valid password");

public static boolean passwordValidation(String s1) {

boolean b=false,b1=false,b2=false;

if(s1.length()>=8)

if(!Character.isDigit(s1.charAt(0)))

if(s1.charAt(0)!='@' && s1.charAt(0)!='_' && s1.charAt(0)!='#')

if(s1.charAt(s1.length()-1)!='@' && s1.charAt(s1.length()-1)!='_' &&


s1.charAt(s1.length()-1)!='#')

b1=true;

if(b1==true)

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

if(Character.isAlphabetic(s1.charAt(i)) || Character.isDigit(s1.charAt(i)) || s1.charAt(i)=='#' ||


s1.charAt(i)=='@' || s1.charAt(i)=='_')

b2=true;

if(b2==true)

if(s1.contains("#") || s1.contains("@") || s1.contains("_"))

b=true;

return b;

----------------------------------------------------------------------------------------------------||

28) pan card number validation:

all letters shud be in caps,shud be of 8 chars.

first three letters must be alphabets.

next 4 letters shud be digits and last letter shud be an alphabet

package Set3;

import java.util.*;

public class ClassSeT28 {


public static void main(String[] args) {

Scanner s=new Scanner(System.in);

String pan=s.next();

boolean b=panNumberValidation(pan);

if(b==true)

System.out.println("valid Pancard Number");

else

System.out.println("not a valid credential");

public static boolean panNumberValidation(String pan) {

boolean b=false,b1=false,b2=false;

String s1=pan.substring(0, 3);

String s2=pan.substring(3, 7);

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++)

if(Character.isAlphabetic(s1.charAt(i)) && Character.isUpperCase(s1.charAt(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;

}
----------------------------------------------------------------------------------------------------||

29) In a hashmap if key is odd then find average of value as integer

ex: h1={1:4,2:6,4:7,5:9}

output=(4+9)/2

package Set3;

import java.util.*;

public class ClassSeT29 {

public static void main(String[] args) {

Map<Integer, Integer> m1=new HashMap<Integer, Integer>();

m1.put(1, 4);

m1.put(2, 6);

m1.put(4, 7);

m1.put(5, 9);

System.out.println(avgValuesOfOddKeys(m1));

public static int avgValuesOfOddKeys(Map<Integer, Integer> m1) {

int l=0,m=0;

Iterator<Integer> i=m1.keySet().iterator();

while(i.hasNext()){

int n=(Integer) i.next();

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

return -1. Consider case.

Eg: Input = "this was great"

Output= 1
package Set3;

public class ClassSeT30 {

public static void main(String[] args) {

String input="this was great";

System.out.println(checkForFirstAndLastChar(input));

public static int checkForFirstAndLastChar(String input) {

int n=0;

if(input.charAt(0)==input.charAt(input.length()-1))

n=1;

else n=-1;

return n;

----------------------------------------------------------------------------------------------------||

31) concat two string if length of two string is equal.

if length of one string is greater, then remove the character from

largest string and then add. The number of characters removed from

largest string is equal to smallest string's length

for example: input 1="hello";

input 2="helloworld";

output="worldhello";

package Set3;

public class ClassSeT31 {

public static void main(String[] args) {

String ip1="hello";

String ip2="helloworld";

System.out.println(removalOfCharFromLargestString(ip1,ip2));

public static String removalOfCharFromLargestString(String ip1,String ip2){


StringBuffer sb=new StringBuffer();

int n1=ip1.length();

int n2=ip2.length();

if(n1<n2)

sb.append(ip2.substring(n1, n2)).append(ip1);

return sb.toString();

----------------------------------------------------------------------------------------------------||

32) i/p: Honesty is my best policy

o/p: Honesty

Return the maximum word length from the given string.

If there are two words of same length then,

return the word which comes first based on alphabetical order.

package Set3;

import java.util.*;

public class ClassSeT32 {

public static void main(String[] args) {

String s1="is a poppppy preethi";

System.out.println(lengthiestString(s1));

public static String lengthiestString(String s1) {

int max=0;

String s2=new String();

StringTokenizer t=new StringTokenizer(s1," ");

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;

----------------------------------------------------------------------------------------------------||

33) In a string check whether all the vowels are present

if yes return 1 else 2.

ex: String 1="education"

output=1.

package Set3;

public class ClassSeT33 {

public static void main(String[] args) {

String s1="education";

System.out.println(vowelsCheck(s1));

public static boolean vowelsCheck(String 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++;}

if(n1==1 && n2==1 && n3==1 && n4==1 && n5==1)

b=true;

return b;

----------------------------------------------------------------------------------------------------||

34) swap the every 2 chrecters in the given string

If size is odd number then keep the last letter as it is.

Ex:- input: forget

output: ofgrte

Ex:- input : NewYork

output : eNYwrok

package Set3;

public class ClassSet34 {

public static void main(String[] args) {

String s1="newyork";

System.out.println(formattingGivenString(s1));

public static String formattingGivenString(String s1) {

StringBuffer sb=new StringBuffer();

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){

String s2=(s1.substring(i, i+2));

StringBuffer sb1=new StringBuffer(s2);

sb.append(sb1.reverse());}

String s3=new String();

if(s1.length()%2==0)

s3=sb.toString();

else

s3=sb.append(s1.charAt(s1.length()-1)).toString();

return s3;

----------------------------------------------------------------------------------------------------||

35) i/p: bengal

o/p: ceogbl

if z is there replace with a

package Set3;

public class ClassSeT35 {

public static void main(String[] args) {

String s1="bengal";

System.out.println(stringFormatting(s1));

public static String stringFormatting(String s1) {

StringBuffer sb=new StringBuffer();

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();

----------------------------------------------------------------------------------------------------||

36) find the maximum chunk of a given string

i/p: this isssss soooo good

o/p=5

package Set3;

import java.util.*;

public class ClassSeT36 {

public static void main(String[] args) {

String s1="this is sooo good";

System.out.println(maxChunk(s1));

public static int maxChunk(String s1) {

int max=0;

StringTokenizer t=new StringTokenizer(s1," ");

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);

----------------------------------------------------------------------------------------------------||

37) i/p1: new york

i/p2: new jersey

o/p: new y+r+

solution:

package Set3;

public class ClassSeT37 {

public static void main(String[] args) {

String s1="New york";

String s2="New jersey";

System.out.println(commonCharsinAstring(s1,s2));

private static String commonCharsinAstring(String s1, String s2) {

int f;

StringBuffer sb=new StringBuffer();

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};

if odd find square

if even find cube

finally add it

output1=208(4+16+27+125+36)

package Set3;

public class ClassSeT38 {

public static void main(String[] args) {

int a[]={2,4,3,5,6};

System.out.println(summationPattern(a));

public static int summationPattern(int[] 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;

----------------------------------------------------------------------------------------------------||

39) input1="the sun raises in the east";

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.*;

public class ClassSeT39 {

public static void main(String[] args) {

String s1="the sun rises in the east";

System.out.println(wordWithMaxVowelCount(s1));

public static String wordWithMaxVowelCount(String s1) {

int max=0;

String s2="aeiouAEIOU";

String s3=new String();

StringTokenizer t=new StringTokenizer(s1," ");

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;

----------------------------------------------------------------------------------------------------||

40) String format : CTS-LLL-XXXX

ip1: CTS-hyd-1234

ip2: hyderabad

-> LLL must be first 3 letters of ip2.

-> XXXX must be a 4-digit number

package Set3;
import java.util.*;

public class ClassSeT41 {

public static void main(String[] args) {

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

System.out.println("not in required format");

public static boolean formattingString(String s1, String s2) {

String s3=s2.substring(0, 3);

boolean b=false;

StringTokenizer t=new StringTokenizer(s1,"-");

String s4=t.nextToken();

String s5=t.nextToken();

String s6=t.nextToken();

if(s4.equals("CTS") && s5.equals(s3) && s6.length()==4)

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

if(Character.isDigit(s6.charAt(i)))

b=true;

else{

b=false;}}

return b;

----------------------------------------------------------------------------------------------------||

41) ip: "this is sample test case"

op: "this amplec"

remove the duplicates in the given string


package Set3;

import java.util.*;

public class ClassSeT42 {

public static void main(String[] args) {

String s1="this is sample test case";

System.out.println(removeDuplicates(s1));

public static String removeDuplicates(String s1) {

StringBuffer sb=new StringBuffer();

Set<Character> c1=new LinkedHashSet<Character>();

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

c1.add(s1.charAt(i));

for(char c2:c1)

sb.append(c2);

return sb.toString();

----------------------------------------------------------------------------------------------------||

42) input1 is a map<Integer,Float>

{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.

answer should be rounded to two numbers after decimal

eg:- the output number 15.2499999 should be 15.25

package Set3;

import java.util.*;

public class ClassSeT43 {

public static void main(String[] args) {

Map<Integer,Float> m1=new HashMap<Integer, Float>();

m1.put(1, (float) 12.93);

m1.put(2, (float) 15.67);

m1.put(3, (float) 17.27);


m1.put(4, (float) 14.88);

System.out.println(avgOfEvenKeyValues(m1));

public static float avgOfEvenKeyValues(Map<Integer, Float> 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;

----------------------------------------------------------------------------------------------------||

43) Color Code Validation:

String should starts with the Character '#'.

Length of String is 7.

It should contain 6 Characters after '#' Symbol.

It should contain Characters Between 'A-F' and Digits '0-9'.

if String is acceptable then Output1=1

else Output1=-1;

package Set3;

import java.util.*;

public class ClassSeT44 {

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

String s1=s.next();

boolean b=colorCodeValidation(s1);
if(b==true)

System.out.println("valid color code");

else

System.out.println("invalid color code");

public static boolean colorCodeValidation(String s1) {

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!='#'){

if((Character.isAlphabetic(c)&& Character.isUpperCase(c)) || Character.isDigit(c))

b=true;

else{

b=false;

break;}}}

return b;

----------------------------------------------------------------------------------------------------||

44) Find the Maximum span of the given array.

span is the number of elements between the duplicate element

including those 2 repeated numbers.

if the array as only one elemnt,then the span is 1.

input[]={1,2,1,1,3}

output1=4

input[]={1,2,3,4,1,1,5}
output1=6

package Set3;

public class ClassSeT45 {

public static void main(String[] args) {

int[]a={1,2,1,1,3};

System.out.println(maxSpan(a));

public static int maxSpan(int[] a) {

String s2 = null;

int n=0;

StringBuffer sb=new StringBuffer();

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.

Ex: Input: california,3.

output: calnia.

package Set3;
public class ClassSeT46 {

public static void main(String[] args) {

String s1="california";

int n1=3;

System.out.println(subStringOfgivenString(s1,n1));

public static String subStringOfgivenString(String s1, int n1) {

StringBuffer sb=new StringBuffer();

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;

public class ClassSeT46 {

public static void main(String[] args) {

String ip1="aBrd";

String ip2="aqrbA";

int ip3=2;

System.out.println(charCheck(ip1,ip2,ip3));

public static boolean charCheck(String ip1, String ip2, int 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;

----------------------------------------------------------------------------------------------------||

47) Add elements of digits:9999

output:9+9+9+9=3+6=9;

package Set3;

public class ClassSeT47 {

public static void main(String[] args) {

int n=9999;

System.out.println(conversiontoaSingleDigit(n));

public static int conversiontoaSingleDigit(int 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;

----------------------------------------------------------------------------------------------------||

48) leap year or not using API?

package Set3;

import java.util.*;
public class ClassSeT48 {

public static void main(String[] args) {

String s="2013";

System.out.println(leapYear(s));

public static boolean leapYear(String s) {

int n=Integer.parseInt(s);

GregorianCalendar c=new GregorianCalendar();

boolean b=c.isLeapYear(n);

return b;

----------------------------------------------------------------------------------------------------||

49) perfect no or not?

package Set3;

public class ClassSeT49 {

public static void main(String[] args) {

int n=28;

System.out.println(perfectNumber(n));

public static boolean perfectNumber(int 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;

}
}

----------------------------------------------------------------------------------------------------||

50) HashMap<String,String> input1={“mouse”:”100.2”,”speaker”:”500.6”,”Monitor”:”2000.23”};

String[] input2={“speaker”,”mouse”};

Float output=600.80(500.6+100.2);

package Set3;

import java.util.*;

public class ClassSeT50 {

public static void main(String[] args) {

HashMap<String, String> m1=new HashMap<String, String>();

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));

public static float getTheTotalCostOfPheripherals(HashMap<String,String> m1,

String[] s) {

Float f=(float) 0;

Iterator<String> i=m1.keySet().iterator();

while(i.hasNext()){

String s1=(String) i.next();

Float f1=Float.parseFloat(m1.get(s1));

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

if(s[j].equals(s1))

f+=f1; }

return f;

----------------------------------------------------------------------------------------------------||

51) Input1=845.69, output=3:2;


Input1=20.789; output=2:3;

Input1=20.0; output=2:1;

output is in Hashmap format.

Hint: count the no of digits.

package Set3;

import java.util.*;

public class ClassSeT51 {

public static void main(String[] args) {

double d=845.69;

System.out.println(noOfDigits(d));

public static String noOfDigits(double d) {

int n1=0,n2=0;

String s=String.valueOf(d);

StringTokenizer t=new StringTokenizer(s,".");

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;

public class ClassSet1 {

public static int SumOfOddsAndEvens(int n){

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;

public static void main(String[] args) {

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.*;

public class ClassSet2 {

public static String getDay(Date d1){

String s1;

SimpleDateFormat sdf=new SimpleDateFormat("EEEEE");

s1=sdf.format(d1);

return s1;

public static void main(String[] args) {

Date d1=new Date(2012/12/27);

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

2 is the max diff between 4 and 2,return the index of 4(2)

output:2
package Set1;

public class ClassSet3 {

public static int getDiffArray(int[] n1){

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;

public static void main(String[] args) {

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.*;

public class ClassSet4 {

public static int mergeArray(int a[],int b[]){


List<Integer> l1=new ArrayList<Integer>();

List<Integer> l2=new ArrayList<Integer>();

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;

public static void main(String[] args) {

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 {

public static int[] retrievePosition(int[] a,int[] b){

int[] c=new int[a.length];

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;

public static void main(String[] args) {

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);

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------

6. Sum of fibonaaci series upto given input.

input:3

logic:1+1+2

output:4

package Set1;

import java.util.*;
public class ClassSet6 {

public static int sumOfFibonacci(int n){

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;

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

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.*;

public class ClassSet7 {

public static int consecutiveSumSubofOddNos(int n){

List<Integer> l1=new ArrayList<Integer>();

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;

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

int n=s.nextInt();

System.out.println(consecutiveSumSubofOddNos(n));

---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------

8. Given date in dd-MM-yyyy format.return the month in full name format(January)

input:"23-01-2012"

output:January

package Set1;

import java.text.SimpleDateFormat;

import java.util.*;

public class ClassSet8 {

public static String monthDiff(Date d1){

SimpleDateFormat sdf=new SimpleDateFormat("MMMM");

String s=(sdf.format(d1));

return s;

public static void main(String[] args) {


Date d1=new Date(23/01/2012);

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;

public class ClassSet9 {

public static int monthDiff(String s1,String s2) throws ParseException{

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

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;

public static void main(String[] args) throws ParseException {

String s1=new String("2013-12-01");

String s2=new String("2012-01-03");

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.*;

public class ClassSet10 {

public static String retrieveMaxScoredStudent(String[] s1){

Map<String, Integer> m1=new HashMap<String, Integer>();

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

String s2=s1[i];

StringTokenizer t=new StringTokenizer(s2,"#");

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;

String m=new String();

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;

public static void main(String[] args) {

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.*;

public class ClassSet11 {

public static void main(String[] args) {

String[] s1={"good","yMe","awe"};
String s2="awe";

System.out.println(stringRetrieval(s1,s2));

public static int stringRetrieval(String[] s1, String s2){

ArrayList<String> l1=new ArrayList<String>();

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.*;

public class ClassSet12 {

public static boolean hourFormat(String s) throws ParseException{

boolean b=false;

StringTokenizer st=new StringTokenizer(s," ");

String s1=st.nextToken();

String s2=st.nextToken();

StringTokenizer st1=new StringTokenizer(s1,":");

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;

public static void main(String[] args) throws ParseException {

String s="19:36 am";

boolean b=hourFormat(s);

if(b==true)

System.out.println("the time is in 12 hr format");

else

System.out.println("the time is in 24 hr format");

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------

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.*;

public class ClassSet13 {

public static int sumOfPalindromeNos(int n1,int n2){

List<Integer> l1=new ArrayList<Integer>();

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;

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

System.out.println("enter the range:");

int n1=s.nextInt();

int n2=s.nextInt();

System.out.println("sum of palindrome nos.within given range is:"+sumOfPalindromeNos(n1,n2));

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------

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

input:"hello how are you aaaaa"

output:hello(length-5)

package Set1;

import java.util.*;

public class ClassSet14 {

public static String lengthiestString(String s1){

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;

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

System.out.println("enter the String:");

String s1=s.nextLine();

System.out.println("the lengthiest string is:"+lengthiestString(s1));

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------

15. Get a input string. reverse it and parse it with '-'.

input:computer

output:r-e-t-u-p-m-o-c

package Set1;

import java.util.Scanner;

public class ClassSet15 {

public static String reversedAndParsedString(String s1){

StringBuffer sb=new StringBuffer(s1);

sb.reverse();

StringBuffer sb1=new StringBuffer();


for(int i=0;i<(2*s1.length())-1;i++)

if(i%2!=0)

sb1=sb.insert(i, '-');

return sb1.toString();

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

System.out.println("enter the String:");

String s1=s.next();

System.out.println("the formatted string is:"+reversedAndParsedString(s1));

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------

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}

output:avg of(90+90) =90

package Set1;

import java.util.*;

public class ClassSet16 {

public static int averageOfMarks(Map<Integer,Integer> m1){

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) {

Map<Integer,Integer> m1=new HashMap<Integer,Integer>();

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.*;

public class ClassSet16 {

public static int averageOfMarks(Map<Integer,Integer> m1){

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) {


Map<Integer,Integer> m1=new HashMap<Integer,Integer>();

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.*;

public class ClassSet18 {

public static String concatStrings(String s1,String s2){

StringBuffer sb=new StringBuffer();

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();

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

String s1=s.next();

String s2=s.next();

System.out.println(concatStrings(s1,s2));

---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------

19.accept a string and find if it is of date format "dd/mm/yyyy".

input:01/13/2012

output:false

package Set1;

import java.util.StringTokenizer;

public class ClassSet19 {

public static boolean formattingDate(String s){

boolean b1=false;

StringTokenizer t=new StringTokenizer(s,"/");

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;

public static void main(String[] args) {

String s="31/5/2012";

boolean b=formattingDate(s);

if(b==true)

System.out.println("date is in dd/MM/yyyy format");

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}

logic:3+4+6+8(the indeces are prime numbers)

output:21

package Set1;

import java.util.*;

public class ClassSet20 {

public static int sumOfPrimeIndices(int[] a,int n){

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;

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

System.out.println("enter the array limit:");

int n=s.nextInt();

System.out.println("enter the array elements:");

int[] a=new int[n];


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

a[i]=s.nextInt();

System.out.println(sumOfPrimeIndices(a,n));

---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------

21.Find the extension of a given string file.

input: "hello.jpeg"

output: "jpeg"

package Set1;

import java.util.*;

public class ClassSet21 {

public static String extensionString(String s1){

StringTokenizer t=new StringTokenizer(s1,".");

t.nextToken();

String s2=t.nextToken();

return s2;

public static void main(String[] args) {

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;

public class ClassSet22 {

public static int commonElements(int[] a,int[] b){

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);

public static void main(String[] args){

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--"

output: true(false otherwise)


package Set1;

public class ClassSet23 {

public static boolean stringPattern(String s1,String s2){

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;

public static void main(String[] args) {

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;

public class ClassSet24 {

public static int squaringAndCubingOfElements(int[] a){

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);

public static void main(String[] args) {

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"

output: false(no 2 diff vowels)

package Set1;

public class ClassSet25 {


public static boolean palindromeAndVowelCheck(String s){

boolean b=true;

int c=0;

String s1="aeiou";

StringBuffer sb=new StringBuffer(s);

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;

public static void main(String[] args) {

String s="deed";

System.out.println(palindromeAndVowelCheck(s));

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------

26. Find no of characters in a given string which are not repeated.

input: "hello"

output: 3
package Set1;

public class ClassSet26 {

public static int noOfnonRepeatedCharacters(String s1){

StringBuffer sb=new StringBuffer(s1);

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();

public static void main(String[] args) {

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.*;

public class ClassSet27 {

public static int negativeString(String s1){

int n1=0;

if(s1.startsWith("-")){

int n=Integer.parseInt(s1);

if(n<0)

n1=Math.abs(n);}

else

n1=-1;

return n1;

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

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 {

public static int StringsNotOfGivenLength(List<String> l1,String s1){

int n1=s1.length();

int c=0;

for(int i=0;i<l1.size();i++){

int n2=l1.get(i).length();

if(n1!=n2)

c++;

return c;

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

System.out.println("enter the no.of elements:");

int n=s.nextInt();

List<String> l1=new ArrayList<String>();

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

l1.add(s.next());

System.out.println("enter the input string:");

String s1=s.next();

System.out.println(StringsNotOfGivenLength(l1,s1));

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------

29.An array of integers is given.The given element is removed new array is returned.

input1:{10,10,20,30,76}

output: {20,20,76}(10 is asked to remove)


package Set1;

import java.util.*;

public class ClassSet29 {

public static int[] removalOfGivenElementFromArray(int[] a,int c){

List<Integer> l1=new ArrayList<Integer>();

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

if(a[i]!=c)

l1.add(a[i]);

int b[]=new int[l1.size()];

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

b[i]=l1.get(i);

return b;

public static void main(String[] args) {

int a[]={10,10,20,30,40,50};

int c=10;

int[] b=removalOfGivenElementFromArray(a,c);

for(int d:b)

System.out.println(d);

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------

30. Find the number of days between two input dates.

package Set1;

import java.text.*;

import java.util.*;

public class ClassSet30 {

public static int dateDifference(String s1,String s2) throws ParseException{

SimpleDateFormat sd=new SimpleDateFormat("dd/MM/yyyy");

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();

int n=Math.abs((int) ((d1-d2)/(1000*3600*24)));

return n;

public static void main(String[] args) throws ParseException {

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.*;

public class ClassSet31 {

public static String retrieveName(String s1){

StringTokenizer t=new StringTokenizer(s1," ");

String s2=t.nextToken();

String s3=t.nextToken();

StringBuffer sb=new StringBuffer(s2);

sb.append(',').append(s3.charAt(0));

return sb.toString();

public static void main(String[] args) {

String s1="Bhavane Raghupathi";

System.out.println(retrieveName(s1));

}
}

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------

32.Write a Program that accepts a string and removes the duplicate characters.

package Set1;

public class ClassSet32 {

public static String removalOfDuplicateCharacters(String s1){

StringBuffer sb=new StringBuffer(s1);

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();

public static void main(String[] args) {

String s1="bhavane";

System.out.println(removalOfDuplicateCharacters(s1));

---------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------------------------

33.validate a password

i) there should be atleast one digit

ii) there should be atleast one of '#','@' or '$' .

iii)the password should be of 6 to 20 characters

iv) there should be more uppercase letter than lower case.

v) should start with an upper case and end with lower case
package Set1;

import java.util.*;

public class ClassSet33 {

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

String st=s.next();

boolean b=validatingPassword(st);

if(b==true)

System.out.println("valid password");

else

System.out.println("Invalid Password");

public static boolean validatingPassword(String st) {

boolean b1=false,b2=false;

if(Character.isUpperCase(st.charAt(0)))

if(Character.isLowerCase(st.charAt(st.length()-1)))

if(st.length()>=6 && st.length()<=20)

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

{ char c = st.charAt(i);

if(Character.isDigit(c)){

b1=true; break; } }

int x=0,y=0;

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

if(Character.isUpperCase(st.charAt(i)))

x++;

else if(Character.isLowerCase(st.charAt(i)))

y++;

if(b1==true)

if(x>y)

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

{ 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.*;

public class ClassSet34 {

public static void main(String[] args) {

int[] a={10,54,23,14,32,45};

System.out.println(avgOfMaxandMinNoinArray(a));

public static int avgOfMaxandMinNoinArray(int[] a) {

Arrays.sort(a);

int b=a[0];

int c=a[a.length-1];

return (b+c)/2;

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------

35.validate the ip address in the form a.b.c.d

where a,b,c,d must be between 0and 255

if validated return 1 else return 2


package Set1;

import java.util.*;

public class ClassSet35 {

public static void main(String[] args) {

String ipAddress="010.230.110.160";

boolean b=validateIpAddress(ipAddress);

if(b==true)

System.out.println("valid ipAddress");

else

System.out.println("not a valid ipAddress");

public static boolean validateIpAddress(String ipAddress) {

boolean b1=false;

StringTokenizer t=new StringTokenizer(ipAddress,".");

int a=Integer.parseInt(t.nextToken());

int b=Integer.parseInt(t.nextToken());

int c=Integer.parseInt(t.nextToken());

int d=Integer.parseInt(t.nextToken());

if((a>=0 && a<=255)&&(b>=0 && b<=255)&&(c>=0 && c<=255)&&(d>=0 && d<=255))

b1=true;

return b1;

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------

36. find the three consecutive characters in a string. if the string consists any three

consecutive characters return 1 else return -1

like AAAxyzaaa will return true.


package Set1;

public class ClassSet36 {

public static void main(String[] args) {

String s1="aaaaxyzAAA";

boolean b=consecutiveCharactersCheck(s1);

if(b==true)

System.out.println("presence of consecutive characters");

else

System.out.println("absence of consecutive characters");

public static boolean consecutiveCharactersCheck(String s1) {

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),

leave the even index as such. return the encrypted string.


package Set1;

public class ClassSet37 {

public static void main(String[] args) {

String s="preethi";

System.out.println(oddEncryptionOfString(s));

public static String oddEncryptionOfString(String s) {

StringBuffer sb=new StringBuffer();

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();

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------

38. Retrieve the max from array which is in a odd-index

package Set1;

import java.util.*;

public class ClassSet38 {

public static void main(String[] args) {

int[] a={10,23,45,54,32,14,55,65,56};

System.out.println(retrieveMaxFromOddIndex(a));

public static int retrieveMaxFromOddIndex(int[] a) {

List<Integer> l=new ArrayList<Integer>();

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++){

int c=(Integer) l.get(i);

if(c>b)

b=c; }

return b;

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------

39.GIVEN A STRING 555-666-1234

DISPLAY AS 55-56-661-234?

package Set1;

import java.util.StringTokenizer;

public class ClassSet39 {

public static void main(String[] args) {

String s="555-666-1234";

System.out.println(display(s));

public static String display(String s) {

StringTokenizer t=new StringTokenizer(s,"-");

String s1=t.nextToken();

String s2=t.nextToken();

String s3=t.nextToken();

StringBuffer sb=new StringBuffer();

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;

public class ClassSet40 {

public static void main(String[] args) {

String input1="Rajasthan";

int input2=2, input3=5;

System.out.println(retrieveString(input1,input2,input3));

public static String retrieveString(String input1, int input2, int input3) {

StringBuffer sb=new StringBuffer(input1);

sb.reverse();

String output=sb.substring(input2, input3);

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.*;

public class ClassSet41 {

public static void main(String[] args) {

int[] a={1,2,3,4,5};

int[] b={0,2,4,6,8};

Scanner s=new Scanner(System.in);

int c=s.nextInt();

int d[]=arrayFunctions(a,b,c);

for(int e:d)

System.out.println(e);

public static int[] arrayFunctions(int[] a, int[] b, int c) {

List<Integer> l1=new ArrayList<Integer>();


List<Integer> l2=new ArrayList<Integer>();

List<Integer> l3=new ArrayList<Integer>();

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;

int[] d=new int[l3.size()];

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

d[i]=l3.get(i);

return d;

---------------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------
42. input1=commitment;

output=cmmitmnt;

c be the first index position

remove even vowels from the string

package Set1;

public class ClassSet42 {

public static void main(String[] args) {

String s1="cOmmitment";

System.out.println(removeEvenElements(s1));

public static String removeEvenElements(String s1) {

StringBuffer sb1=new StringBuffer();

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

if((i%2)==0)

sb1.append(s1.charAt(i));

else if((i%2)!=0)

if(s1.charAt(i)!='a' && s1.charAt(i)!='e' && s1.charAt(i)!='i' && s1.charAt(i)!='o' &&


s1.charAt(i)!='u')

if(s1.charAt(i)!='A' && s1.charAt(i)!='E' && s1.charAt(i)!='I' && s1.charAt(i)!='O'


&& s1.charAt(i)!='U')

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;

public class ClassSet43 {

public static void main(String[] args) {

int[] a={5,1,6,2,9,4,3,7,8};

System.out.println("Sum Of Odd Position Elements Multiplied With Their Index Is:");

System.out.println(retrievalOfOddPositionElements(a));

public static int retrievalOfOddPositionElements(int[] 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.*;

public class ClassSet44 {

public static void main(String[] args){

String s1="02/2011";

System.out.println(noOfDaysInAmonth(s1));

public static int noOfDaysInAmonth(String s1){

int n=0;

StringTokenizer r=new StringTokenizer(s1,"/");

int n1=Integer.parseInt(r.nextToken());

int n2=Integer.parseInt(r.nextToken());

if(n1==1 || n1==3 || n1==5 ||n1==7 || n1==8 || n1==10 || n1==12)

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.*;

public class ClassSet45 {

public static void main(String[] args) {

int i=20,j=40;

System.out.println("sum of non-prime nos. is:"+additionOfnonPrimeNos(i,j));

public static int additionOfnonPrimeNos(int i, int j){

int k=0;

List<Integer> l1=new ArrayList<Integer>();

List<Integer> l2=new ArrayList<Integer>();

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;

public class ClassSet46 {

public static void main(String[] args) {

int[] a={23,35,11,66,14,32,65,56,55,99};

int b=37;

System.out.println(additionOfRetrievedElements(a,b));

public static int additionOfRetrievedElements(int[] a, int 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.*;

public class ClassSet47 {

public static void main(String[] args) {

Map<Integer, String> m1=new HashMap<Integer, String>();

m1.put(24, "preethi");

m1.put(32, "bhanu");

m1.put(25, "menu");

m1.put(31, "priya");

System.out.println(fetchingKeysDivisibleByFour(m1));

public static int fetchingKeysDivisibleByFour(Map<Integer, String> 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;

1) compare two strings, if the characters in string 1 are present in

string 2, then it should be put as such in output, else '+' should be

put in output...ignore case difference.

input 1:"New York"

input 2:"NWYR"
output:N+w+Y+r+

package Set2;

public class ClassSET1 {

public static void main(String[] args) {

String s1="New York";

String s2="NWYR";

System.out.println(StringFormatting(s1,s2));

public static String StringFormatting(String s1, String s2) {

StringBuffer s4=new StringBuffer();

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:

Return 1 if s2 comes before s3 in searchstring else return 2


package Set2;

public class ClassSET2 {

public static void main(String[] args) {

String srch="MaanVeerSinghKhurana";

String s1="Veer";

String s2="Singh";

int n=searchString(srch,s1,s2);

if(n==1)

System.out.println(s1+" comes before "+s2);

else

System.out.println(s2+" comes before "+s1);

public static int searchString(String srch, String s1, String s2) {

int n=0;

int n1=srch.indexOf(s1);

int n2=srch.indexOf(s2);

if(n1<n2)

n=1;

else

n=2;

return n;

----------------------------------------------------------------------------------------------------------||

3) months between two dates

package Set2;

import java.text.*;
import java.util.*;

public class ClassSET3 {

public static void main(String[] args) throws ParseException {

String s1="30/05/2013";

String s2="01/06/2013";

System.out.println(monthsBetweenDates(s1,s2));

public static int monthsBetweenDates(String s1, String s2) throws ParseException {

SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");

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;

public class ClassSET4 {

public static void main(String[] args) {

String s1="xyzwabcd";

int n1=2,n2=4;

System.out.println(retrievalOfString(s1,n1,n2));

public static String retrievalOfString(String s1, int n1, int n2) {

StringBuffer sb=new StringBuffer(s1);

sb.reverse();

String s2=sb.substring(n1, n1+n2);

return s2;

--------------------------------------------------------------------------------------------------------||

5) Given integer array

input :int[] arr={2,3,5,4,1,6,7,7,9};

Remove the duplicate elements and print sum of even numbers in the array..

print -1 if arr contains only odd numbers

package Set2;

import java.util.*;

public class ClassSET5 {

public static void main(String[] args) {


int a[]={2,3,5,4,1,6,7,7,9};

System.out.println(sumOfEvenNos(a));

public static int sumOfEvenNos(int[] a) {

List<Integer> l1=new ArrayList<Integer>();

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

l1.add(a[i]);

List<Integer> l2=new ArrayList<Integer>();

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

here "abc**" refers to customer id.

12345 refers to last month eb reading and 12660 refers to this month eb reading

find the difference between two readings and multiply it by input3


ie., output=(12660-12345)*4

package Set2;

public class ClassSET6 {

public static void main(String[] args) {

String input1="abc2012345";

String input2="abc2112660";

int input3=4;

System.out.println(meterReading(input1,input2,input3));

public static int meterReading(String input1, String input2, int input3) {

int n1=Integer.parseInt(input1.substring(5, input1.length()));

int n2=Integer.parseInt(input2.substring(5, input2.length()));

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;

public class ClassSET7 {

public static void main(String[] args) {

int a[]={2,3,5};

System.out.println(sumOfElementsWrtIndices(a));

public static int sumOfElementsWrtIndices(int[] 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.

if condn satisfied print 1 else -1.

Input:{"123","23.14","522"}

output:1

Input1:{"asd","123","42.20"}

output:-1

package Set2;

public class ClassSET8 {

public static void main(String[] args) {

String[] input1={"123","23.14","522"};

//String[] input1={"asd","123","42.20"};

System.out.println(stringOfDigits(input1));
}

public static int stringOfDigits(String[] 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}

find the difference b/w max and min values in array

output:35-2=33.

package Set2;

import java.util.Arrays;

public class ClassSET9 {

public static void main(String[] args) {

int a[]={12,14,2,26,35};

System.out.println(diffBwMaxAndMin(a));

public static int diffBwMaxAndMin(int[] 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)

find their sum.

a[]={1,4,2,1,4,1,5}

Largest span=5

package Set2;

public class ClassSET10 {

public static void main(String[] args) {

int a[]={1,4,2,1,4,1,5};

System.out.println("sum of largest span elements:"+largestSpan(a));

public static int largestSpan(int[] a) {

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

ie,if string elements are nos,add it.

input={"a","b"}

output=-1;

package Set2;

public class ClassSET11 {

public static void main(String[] args) {

String s[]={"1","2","3","4"};

//String s[]={"a","b","3","4"};

System.out.println(checkForStringElements(s));

public static int checkForStringElements(String[] 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;

-----------------------------------------------------------------------------------------------------------||

12) arraylist1={ 1,2,3,4,5}

arraylist2={ 6,7,8,9,10}

size of both list should be same

output={6,2,8,4,10}

package Set2;

public class ClassSET12 {

public static void main(String[] args) {

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);
}

public static int[] alternativeIndicesElements(int[] a, int[] b){

int c[]=new int[a.length];

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

input1=hai hello hai where hai Hai;

input2=what hai

output=3;

package Set2;

import java.util.StringTokenizer;

public class ClassSET13 {

public static void main(String[] args) {

String input1="hai hello how are you?? hai hai";

String input2="what hai";

System.out.println(stringOccurance(input1,input2));

}
public static int stringOccurance(String input1, String input2){

int count=0;

StringTokenizer t1=new StringTokenizer(input2," ");

String s1=t1.nextToken();

String s2=t1.nextToken();

StringTokenizer t2=new StringTokenizer(input1," ");

while(t2.hasMoreTokens()){

if(t2.nextToken().equals(s2))

count++; }

return count;

------------------------------------------------------------------------------------------------------------||

14) find the no.of charcters,that has repeated 3 consecutive times

input1:"aaabbccc"

ouput1=2;

package Set2;

public class ClassSET14 {

public static void main(String[] args) {

String input1="aaabbccc";

System.out.println(consecutiveRepeatitionOfChar(input1));

public static int consecutiveRepeatitionOfChar(String 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;

-----------------------------------------------------------------------------------------------------------||

15)What will be the DAY of current date in next year

package Set2;

import java.text.SimpleDateFormat;

import java.util.*;

public class ClassSet15 {

public static void main(String[] args) {

Date d=new Date();

System.out.println(sameDayOnUpcomingYear(d));

public static String sameDayOnUpcomingYear(Date d) {

Date d1=new Date();

d1.setYear(d.getYear()+1);

SimpleDateFormat sdf=new SimpleDateFormat("EEEE");

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;

public class ClassSET16 {

public static void main(String[] args) {

String s="1234gif";

System.out.println(summationOfNosInaString(s));

public static int summationOfNosInaString(String 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}

sort the given array

reverse the given array

if user input is 1 it should give oth element of an reversed array.


package Set2;

import java.util.*;

public class ClassSET17 {

public static void main(String[] args) {

String[] s={"red","green","blue","ivory","yellow"};

int n=1;

System.out.println(retrievingRequiredColor(s,n));

public static String retrievingRequiredColor(String[] s, int n) {

String s1=new String();

List<String> l=new ArrayList<String>();

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;

--------------------------------------------------------------------------------------------------------||

18)String a="a very fine day"

output:A Very Fine Day


package Set2;

import java.util.StringTokenizer;

public class ClassSET18 {

public static void main(String[] args){

String s1="its a very fine day";

System.out.println(capsStart(s1));

public static String capsStart(String s1){

StringBuffer s5=new StringBuffer();

StringTokenizer t=new StringTokenizer(s1," ");

while(t.hasMoreTokens()){

String s2=t.nextToken();

String s3=s2.substring(0,1);

String s4=s2.substring(1, s2.length());

s5.append(s3.toUpperCase()).append(s4).append(" "); }

return s5.toString();

--------------------------------------------------------------------------------------------------------||

19)Take the word with a max length in the given sentance

in that check for vowels if so count the no.of occurances !

Input 1="Bhavane is a good girl"

Output =3

Input 1="Bhavanee is a good girl"

Output =4

package Set2;

import java.util.StringTokenizer;
public class ClassSET19 {

public static void main(String[] args) {

String s1="Bhavane is a good girl";

System.out.println(countVowelsInMaxLengthString(s1));

public static int countVowelsInMaxLengthString(String s1) {

int n1=0, max=0;

String s4="AEIOUaeiou";

String s3=new String();

StringTokenizer t=new StringTokenizer(s1," ");

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;

public class ClassSET20 {

public static void main(String[] args) {

String s1="sumithra";

System.out.println(printingSubstringOfMiddleChars(s1));

public static String printingSubstringOfMiddleChars(String s1) {

String s2=s1.substring((s1.length()/2)-1, (s1.length()/2)+1);

return s2;

--------------------------------------------------------------------------------------------------------||

21) Given an array int a[]. Add the sum at even indexes.do the same with odd indexes.

if both the sum is equal return 1 or return -1.

package Set2;

public class ClassSET21 {

public static void main(String[] args) {

int a[]={9,8,5,3,2,6,4,7,5,1};

System.out.println(oddEvenIndicesCount(a));

public static int oddEvenIndicesCount(int[] 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;

-------------------------------------------------------------------------------------------------------||

22)no of days in a month in specific year

package Set2;

import java.util.*;

public class ClassSET22 {

public static void main(String[] args){

Calendar ca=new GregorianCalendar(2013,Calendar.FEBRUARY,03);

System.out.println(noOfDaysInaMonth(ca));

public static int noOfDaysInaMonth(Calendar 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)

Note in the above array 12 must not considered as such

i.e,it must be considered as 1,2


package Set3;

public class ClassSeT01 {

public static void main(String[] args) {

String[] s1={"2AA","12","A2C","C5a"};

getSum(s1); }

public static void getSum(String[] 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

Input:{“goa”,”kerala”,”gujarat”} [string array]

Output:{{GOA,goa},{KER,kerala},{GUJ,Gujarat}} [hashmap]

package Set3;

import java.util.*;

public class ClassSeT02 {

public static void main(String[] args) {

String[] s1={"goa","kerala","gujarat"};

putvalues(s1);

public static void putvalues(String[] s1) {

ArrayList<String> l1=new ArrayList<String>();


HashMap<String,String> m1=new HashMap<String,String>();

ArrayList<String> l2=new ArrayList<String>();

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]

expected output String: "Vikas,Lokesh,Ashok"

package Set3;

public class ClassSeT03 {

public static void main(String[] args) {

String[] ip={"Vikas","Lokesh","Ashok"};

System.out.println(getTheNamesinGivenFormat(ip));

public static String getTheNamesinGivenFormat(String[] ip) {

StringBuffer sb=new StringBuffer();

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;

2)@ & . should not be repeated;

3)there should be five charcters between @ and .;

4)there should be atleast 3 characters before @ ;

5)the end of mail id should be .com;

package Set3;

import java.util.*;

public class ClassSeT04 {

public static void main(String[] args) {

String ip="[email protected]";

boolean b=emailIdValidation(ip);

if(b==true)

System.out.println("valid mail Id");

else

System.out.println("not a valid Id");

public static boolean emailIdValidation(String ip) {

int i=0;

boolean b=false;

StringTokenizer t=new StringTokenizer(ip,"@");

String s1=t.nextToken();

String s2=t.nextToken();

StringTokenizer t1=new StringTokenizer(s2,".");

String s3=t1.nextToken();

String s4=t1.nextToken();

if(ip.contains("@") && ip.contains("."))

i++;

if(i==1)

if(s3.length()==5)

if(s1.length()>=3)
if(s4.equals("com"))

b=true;

return b;

----------------------------------------------------------------------------------------------------||

5) Square root calculation of

((x1+x2)*(x1+x2))+((y1+y2)*(y1+y2))

o/p should be rounded of to int;

package Set3;

public class ClassSeT05 {

public static void main(String[] args) {

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);

----------------------------------------------------------------------------------------------------||

6) I/P hashmap<String String>{"ram:hari","cisco:barfi","honeywell:cs","cts:hari"};

i/p 2="hari";

o/p string[]={"ram","cts"};

package Set3;

import java.util.*;

import java.util.Map.Entry;

public class ClassSeT06 {


public static void main(String[] args) {

HashMap<String,String> m1=new HashMap<String,String>();

m1.put("ram","hari");

m1.put("cisco","barfi");

m1.put("honeywell","cs");

m1.put("cts","hari");

String s2="hari";

getvalues(m1,s2);

public static void getvalues(HashMap<String, String> m1, String s2) {

ArrayList<String>l1=new ArrayList<String>();

for(Entry<String, String> m:m1.entrySet()){

m.getKey();

m.getValue();

if(m.getValue().equals(s2))

l1.add(m.getKey()); }

String[] op= new String[l1.size()];

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.*;

public class ClassSeT07 {

public static void main(String[] args) {

String[] s1={"abc","da","ram","cat"};
int ip=3;

getStr(s1,ip);

public static void getStr(String[] s1, int ip) {

String op=" ";

String s2=" ";

ArrayList<String> l1=new ArrayList<String>();

for(String s:s1)

if(s.length()==ip)

l1.add(s);

StringBuffer buff=new StringBuffer();

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

INPUT2= 2. delete the char,if rpted twice.

if occurs more than twice,leave the first occurence and delete the duplicate

O/P= helwrd;

package Set3;

public class ClassSeT08 {

public static void main(String[] args) {

String input1="HelloWorld";

int input2=2;

System.out.println(deletingtheCharOccuringTwice(input1,input2));

public static String deletingtheCharOccuringTwice(String input1, int input2) {


StringBuffer sb=new StringBuffer(input1);

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();

----------------------------------------------------------------------------------------------------||

9) String[] input={"100","111","10100","10","1111"} input2="10"

output=2;count strings having prefix"10" but "10" not included in count

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.*;

public class ClassSeT09 {

public static void main(String[] args) {

String[] ip={"100","111","10100","10","1111"};

gteCount(ip);

public static void gteCount(String[] ip) {


int op=0;

ArrayList<String> l1=new ArrayList<String>();

for(String s:ip)

if(s.startsWith("10") || s.startsWith("01") &&(s.length()>2))

l1.add(s);

op=l1.size();

System.out.println(op);

----------------------------------------------------------------------------------------------------||

10) input1=1 ,input2=2 ,input3=3 --- output=6;

input1=1 ,input2=13,input3=3 --- output=1;

input1=13,input2=2 ,input3=8 --- output=8;

if value equal to 13,escape the value '13', as well as the next value to 13.

sum the remaining values

package Set3;

import java.util.*;

public class ClassSeT10 {

public static void main(String[] args) {

int ip1=13,ip2=2,ip3=8;

System.out.println(thirteenLapse(ip1,ip2,ip3));

public static int thirteenLapse(int ip1, int ip2, int ip3) {

List<Integer> l=new ArrayList<Integer>();

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"

output="hlo"; Alternative positions...

package Set3;

public class ClassSeT11 {

public static void main(String[] args) {

String s="Hello";

System.out.println(alternatingChar(s));

public static String alternatingChar(String s){

StringBuffer sb=new StringBuffer();

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

if(i%2==0)

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

return sb.toString();

----------------------------------------------------------------------------------------------------||

12) Input1=”Hello World”; output-------à “dello WorlH”.

package Set3;

public class ClassSeT12 {

public static void main(String[] args) {

String s="Hello World";

System.out.println(reArrangingWord(s));

}
public static String reArrangingWord(String s) {

StringBuffer sb=new StringBuffer();

sb.append(s.substring(s.length()-1));

sb.append(s.substring(1, s.length()-1));

sb.append(s.substring(0, 1));

return sb.toString();

----------------------------------------------------------------------------------------------------||

13) Collect no’s frm list1 which is not present in list2

& Collect no’s frm list2 which is not present in list1

and store it in output1[].

ex: input1={1,2,3,4}; input2={1,2,3,5}; output1={4,5};

package Set3;

import java.util.*;

public class ClassSeT13 {

public static void main(String[] args) {

List<Integer> l1=new ArrayList<Integer>();

l1.add(1);

l1.add(2);

l1.add(3);

l1.add(4);

List<Integer> l2=new ArrayList<Integer>();

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) {

List<Integer> l3=new ArrayList<Integer>();

List<Integer> l4=new ArrayList<Integer>();

l3.addAll(l1);l4.addAll(l2);

l1.removeAll(l2);l4.removeAll(l3);

l1.addAll(l4);

int o[]=new int[l1.size()];

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;

public class ClassSeT14 {

public static void main(String[] args) {

String[] a={"pinky","preethi","puppy","preeth","puppypreethi"};

System.out.println(namesWithPreFixes(a));

public static int namesWithPreFixes(String[] 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;
}

----------------------------------------------------------------------------------------------------||

15) count the number of words in the string

Input string="i work in cognizant.";

output=4;

package Set3;

import java.util.StringTokenizer;

public class ClassSeT15 {

public static void main(String[] args) {

String s="I work for cognizant";

System.out.println(noOfWordsInString(s));

public static int noOfWordsInString(String s) {

StringTokenizer t=new StringTokenizer(s," ");

return t.countTokens();

----------------------------------------------------------------------------------------------------||

16) int[] input={2,1,4,1,2,3,6};

check whether the input has the sequence of "1,2,3". if so-

output=true;

int[] input={1,2,1,3,4,5,8};

output=false

package Set3;

public class ClassSeT16 {

public static void main(String[] args) {

//int[] a={2,1,4,1,2,3,6};

int[] a={1,2,1,3,4,5,8};

System.out.println(sequenceInArray(a));
}

public static boolean sequenceInArray(int[] 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;

----------------------------------------------------------------------------------------------------||

17) input-- String input1="AAA/abb/CCC"

char input2='/'

output-- String[] output1;

output1[]={"aaa","bba","ccc"};

operation-- get the strings from input1 using stringtokenizer

reverse each string

then to lower case

finally store it in output1[] string array

package Set3;

import java.util.*;

public class ClassSeT17 {

public static void main(String[] args) {

String ip1="AAA/abb/CCC";

char ip2='/';

String op[]=loweringCasenReverseofaString(ip1,ip2);

for(String s:op)

System.out.println(s);
}

public static String[] loweringCasenReverseofaString(String ip1, char ip2){

List<String> l=new ArrayList<String>();

StringTokenizer t=new StringTokenizer(ip1,"/");

while(t.hasMoreTokens()){

StringBuffer sb=new StringBuffer(t.nextToken().toLowerCase());

l.add(sb.reverse().toString()); }

String op[]=new String[l.size()];

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

op[i]=l.get(i);

return op;

----------------------------------------------------------------------------------------------------||

18) Input1=”cowboy”; Output1=”cowcow”;

Input1=”so”;output1=”sososo”;

HINT: if they give 3 letter word u have to display 2 time;

package Set3;

public class ClassSeT18 {

public static void main(String[] args) {

String ip1="cowboy";

String ip2="cow";

System.out.println(printingStringDependingOncharCount(ip1,ip2));

public static String printingStringDependingOncharCount(String ip1,String ip2) {

StringBuffer sb=new StringBuffer();

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;

operation--- print the element which is not repeated

if all the inputs r different sum all inputs

input---input1=1;

input2=2;

input3=3;

output1=6;

package Set3;

public class ClassSeT19 {

public static void main(String[] args) {

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));

public static int sumOfNonRepeatedChars(int ip1, int ip2, int ip3){

int n=0;

if(ip1!=ip2 && ip2!=ip3 && ip3!=ip1)

n=ip1+ip2+ip3;

else if(ip1==ip2 && 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}

operation-- In 1st list remove strings starting with 'a' or 'g'

In 2nd list remove strings ending with 'n' or 'e'

Ignore case, return in string array

package Set3;

import java.util.*;

public class ClassSeT20 {

public static void main(String[] args) {

List<String> l1=new ArrayList<String>();

l1.add("apple");

l1.add("orange");

l1.add("grapes");

List<String> l2=new ArrayList<String>();

l2.add("melon");

l2.add("apple");

l2.add("mango");

String[] s2=fruitsList(l1,l2);

for(String s3:s2)
System.out.println(s3);

public static String[] fruitsList(List<String> l1, List<String> l2){

List<String> l3=new ArrayList<String>();

for(int i=0;i<l1.size();i++){

String s1=l1.get(i);

if(s1.charAt(0)!='a' && s1.charAt(0)!='A' && s1.charAt(0)!='g' && s1.charAt(0)!='G')

l3.add(s1); }

for(int i=0;i<l2.size();i++){

String s1=l2.get(i);

if(s1.charAt(s1.length()-1)!='n' && s1.charAt(s1.length()-1)!='N' && s1.charAt(s1.length()-1)!='e' &&


s1.charAt(s1.length()-1)!='E')

l3.add(s1); }

Collections.sort(l3);

String[] s2=new String[l3.size()];

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

s2[i]=l3.get(i);

return s2;

----------------------------------------------------------------------------------------------------||

21) input1-- Hello*world

output-- boolean(true or false)

operation-- if the character before and after * are same return true else false

if there in no star in the string return false(Ignore case)

package Set3;

import java.util.*;

public class ClassSeT21 {

public static void main(String[] args) {

String input="Hello*world";

System.out.println(characterCheck(input));

}
public static boolean characterCheck(String input) {

boolean b=false;

StringTokenizer t=new StringTokenizer(input,"*");

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;

----------------------------------------------------------------------------------------------------||

22) input --String input1 ="xaXafxsd"

output--String output1="aXafsdxx"

operation-- remove the character "x"(only lower case) from string and place at the end

package Set3;

public class ClassSeT22 {

public static void main(String[] args) {

String input="xaXafxsd";

System.out.println(removalOfx(input));

public static String removalOfx(String input) {

StringBuffer sb=new StringBuffer(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();

----------------------------------------------------------------------------------------------------||

23) HashMap<String,Integer> h1={“abc”:50,”efg”:70};

if the mark is less than 60 then put the output in the

HashMap<String,String> h2={“abc”:”fail”,”efg”:”pass”}

package Set3;

import java.util.*;

public class ClassSeT23 {

public static void main(String[] args) {

Map<String, Integer> m1=new HashMap<String, Integer>();

m1.put("abc", 90);

m1.put("efg", 50);

m1.put("mno", 60);

m1.put("rst", 75);

m1.put("xyz", 35);

System.out.println(examResult(m1));

public static Map<String,String> examResult(Map<String, Integer> m1) {

Map<String,String> m2=new HashMap<String, String>();

String s1=new String();

String s2=new String();

int n=0;

Iterator<String> i=m1.keySet().iterator();

while(i.hasNext()){

s1=(String) i.next();

n=m1.get(s1);

if(n>=60)

s2="PASS";

else
s2="FAIL";

m2.put(s1, s2); }

return m2;

----------------------------------------------------------------------------------------------------||

24) String i/p1=2012;

sTRING i/p2=5

IF EXPERIENCE IS GREATER THAN INPUT 2 THEN TRUE;

package Set3;

import java.text.*;

import java.util.*;

public class ClassSeT24 {

public static void main(String[] args) throws ParseException {

String ip1="2012";

String ip2="5";

System.out.println(experienceCalc(ip1,ip2));

public static boolean experienceCalc(String ip1, String ip2) throws ParseException {

boolean b=false;

SimpleDateFormat sdf=new SimpleDateFormat("yyyy");

Date d1=sdf.parse(ip1);

Date d2=new Date();

int n1=d1.getYear();

int n2=d2.getYear();

int n3=Integer.parseInt(ip2);

if((n2-n1)>n3)

b=true;

return b;

}
----------------------------------------------------------------------------------------------------||

25) input string="hello", n=2

output: lolo

package Set3;

public class ClassSeT25 {

public static void main(String[] args) {

String s1="hello";

int n1=2;

System.out.println(formattingOfString(s1,n1));

public static String formattingOfString(String s1, int n1) {

String s2=s1.substring(s1.length()-n1, s1.length());

StringBuffer sb=new StringBuffer();

for(int i=0;i<n1;i++)

sb.append(s2);

return sb.toString();

----------------------------------------------------------------------------------------------------||

26) prove whether a number is ISBN number or not

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

sum%11==0 then it is ISBN number

package Set3;

public class ClassSeT26 {

public static void main(String[] args) {

String ip="0201103311";

boolean b=ISBNnumber(ip);

if(b==true)

System.out.println("valid ISBN number");


else

System.out.println("check ur data");

public static boolean ISBNnumber(String ip) {

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;

----------------------------------------------------------------------------------------------------||

27) Validate Password

validation based on following criteria:

-> minimum length is 8

-> should contain any of these @/_/#

-> should not start with number/special chars(@/#/_)

-> should not end with special chars

-> can contain numbers,letters,special chars

package Set3;

import java.util.*;

public class ClassSeT40 {

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

String s1=s.next();

boolean b=passwordValidation(s1);
if(b==true)

System.out.println("valid password");

else

System.out.println("not a valid password");

public static boolean passwordValidation(String s1) {

boolean b=false,b1=false,b2=false;

if(s1.length()>=8)

if(!Character.isDigit(s1.charAt(0)))

if(s1.charAt(0)!='@' && s1.charAt(0)!='_' && s1.charAt(0)!='#')

if(s1.charAt(s1.length()-1)!='@' && s1.charAt(s1.length()-1)!='_' &&


s1.charAt(s1.length()-1)!='#')

b1=true;

if(b1==true)

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

if(Character.isAlphabetic(s1.charAt(i)) || Character.isDigit(s1.charAt(i)) || s1.charAt(i)=='#' ||


s1.charAt(i)=='@' || s1.charAt(i)=='_')

b2=true;

if(b2==true)

if(s1.contains("#") || s1.contains("@") || s1.contains("_"))

b=true;

return b;

----------------------------------------------------------------------------------------------------||

28) pan card number validation:

all letters shud be in caps,shud be of 8 chars.

first three letters must be alphabets.

next 4 letters shud be digits and last letter shud be an alphabet

package Set3;

import java.util.*;

public class ClassSeT28 {


public static void main(String[] args) {

Scanner s=new Scanner(System.in);

String pan=s.next();

boolean b=panNumberValidation(pan);

if(b==true)

System.out.println("valid Pancard Number");

else

System.out.println("not a valid credential");

public static boolean panNumberValidation(String pan) {

boolean b=false,b1=false,b2=false;

String s1=pan.substring(0, 3);

String s2=pan.substring(3, 7);

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++)

if(Character.isAlphabetic(s1.charAt(i)) && Character.isUpperCase(s1.charAt(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;

}
----------------------------------------------------------------------------------------------------||

29) In a hashmap if key is odd then find average of value as integer

ex: h1={1:4,2:6,4:7,5:9}

output=(4+9)/2

package Set3;

import java.util.*;

public class ClassSeT29 {

public static void main(String[] args) {

Map<Integer, Integer> m1=new HashMap<Integer, Integer>();

m1.put(1, 4);

m1.put(2, 6);

m1.put(4, 7);

m1.put(5, 9);

System.out.println(avgValuesOfOddKeys(m1));

public static int avgValuesOfOddKeys(Map<Integer, Integer> m1) {

int l=0,m=0;

Iterator<Integer> i=m1.keySet().iterator();

while(i.hasNext()){

int n=(Integer) i.next();

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

return -1. Consider case.

Eg: Input = "this was great"

Output= 1
package Set3;

public class ClassSeT30 {

public static void main(String[] args) {

String input="this was great";

System.out.println(checkForFirstAndLastChar(input));

public static int checkForFirstAndLastChar(String input) {

int n=0;

if(input.charAt(0)==input.charAt(input.length()-1))

n=1;

else n=-1;

return n;

----------------------------------------------------------------------------------------------------||

31) concat two string if length of two string is equal.

if length of one string is greater, then remove the character from

largest string and then add. The number of characters removed from

largest string is equal to smallest string's length

for example: input 1="hello";

input 2="helloworld";

output="worldhello";

package Set3;

public class ClassSeT31 {

public static void main(String[] args) {

String ip1="hello";

String ip2="helloworld";

System.out.println(removalOfCharFromLargestString(ip1,ip2));

public static String removalOfCharFromLargestString(String ip1,String ip2){


StringBuffer sb=new StringBuffer();

int n1=ip1.length();

int n2=ip2.length();

if(n1<n2)

sb.append(ip2.substring(n1, n2)).append(ip1);

return sb.toString();

----------------------------------------------------------------------------------------------------||

32) i/p: Honesty is my best policy

o/p: Honesty

Return the maximum word length from the given string.

If there are two words of same length then,

return the word which comes first based on alphabetical order.

package Set3;

import java.util.*;

public class ClassSeT32 {

public static void main(String[] args) {

String s1="is a poppppy preethi";

System.out.println(lengthiestString(s1));

public static String lengthiestString(String s1) {

int max=0;

String s2=new String();

StringTokenizer t=new StringTokenizer(s1," ");

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;

----------------------------------------------------------------------------------------------------||

33) In a string check whether all the vowels are present

if yes return 1 else 2.

ex: String 1="education"

output=1.

package Set3;

public class ClassSeT33 {

public static void main(String[] args) {

String s1="education";

System.out.println(vowelsCheck(s1));

public static boolean vowelsCheck(String 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++;}

if(n1==1 && n2==1 && n3==1 && n4==1 && n5==1)

b=true;

return b;

----------------------------------------------------------------------------------------------------||

34) swap the every 2 chrecters in the given string

If size is odd number then keep the last letter as it is.

Ex:- input: forget

output: ofgrte

Ex:- input : NewYork

output : eNYwrok

package Set3;

public class ClassSet34 {

public static void main(String[] args) {

String s1="newyork";

System.out.println(formattingGivenString(s1));

public static String formattingGivenString(String s1) {

StringBuffer sb=new StringBuffer();

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){

String s2=(s1.substring(i, i+2));

StringBuffer sb1=new StringBuffer(s2);

sb.append(sb1.reverse());}

String s3=new String();

if(s1.length()%2==0)

s3=sb.toString();

else

s3=sb.append(s1.charAt(s1.length()-1)).toString();

return s3;

----------------------------------------------------------------------------------------------------||

35) i/p: bengal

o/p: ceogbl

if z is there replace with a

package Set3;

public class ClassSeT35 {

public static void main(String[] args) {

String s1="bengal";

System.out.println(stringFormatting(s1));

public static String stringFormatting(String s1) {

StringBuffer sb=new StringBuffer();

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();

----------------------------------------------------------------------------------------------------||

36) find the maximum chunk of a given string

i/p: this isssss soooo good

o/p=5

package Set3;

import java.util.*;

public class ClassSeT36 {

public static void main(String[] args) {

String s1="this is sooo good";

System.out.println(maxChunk(s1));

public static int maxChunk(String s1) {

int max=0;

StringTokenizer t=new StringTokenizer(s1," ");

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);

----------------------------------------------------------------------------------------------------||

37) i/p1: new york

i/p2: new jersey

o/p: new y+r+

solution:

package Set3;

public class ClassSeT37 {

public static void main(String[] args) {

String s1="New york";

String s2="New jersey";

System.out.println(commonCharsinAstring(s1,s2));

private static String commonCharsinAstring(String s1, String s2) {

int f;

StringBuffer sb=new StringBuffer();

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};

if odd find square

if even find cube

finally add it

output1=208(4+16+27+125+36)

package Set3;

public class ClassSeT38 {

public static void main(String[] args) {

int a[]={2,4,3,5,6};

System.out.println(summationPattern(a));

public static int summationPattern(int[] 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;

----------------------------------------------------------------------------------------------------||

39) input1="the sun raises in the east";

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.*;

public class ClassSeT39 {

public static void main(String[] args) {

String s1="the sun rises in the east";

System.out.println(wordWithMaxVowelCount(s1));

public static String wordWithMaxVowelCount(String s1) {

int max=0;

String s2="aeiouAEIOU";

String s3=new String();

StringTokenizer t=new StringTokenizer(s1," ");

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;

----------------------------------------------------------------------------------------------------||

40) String format : CTS-LLL-XXXX

ip1: CTS-hyd-1234

ip2: hyderabad

-> LLL must be first 3 letters of ip2.

-> XXXX must be a 4-digit number

package Set3;
import java.util.*;

public class ClassSeT41 {

public static void main(String[] args) {

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

System.out.println("not in required format");

public static boolean formattingString(String s1, String s2) {

String s3=s2.substring(0, 3);

boolean b=false;

StringTokenizer t=new StringTokenizer(s1,"-");

String s4=t.nextToken();

String s5=t.nextToken();

String s6=t.nextToken();

if(s4.equals("CTS") && s5.equals(s3) && s6.length()==4)

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

if(Character.isDigit(s6.charAt(i)))

b=true;

else{

b=false;}}

return b;

----------------------------------------------------------------------------------------------------||

41) ip: "this is sample test case"

op: "this amplec"

remove the duplicates in the given string


package Set3;

import java.util.*;

public class ClassSeT42 {

public static void main(String[] args) {

String s1="this is sample test case";

System.out.println(removeDuplicates(s1));

public static String removeDuplicates(String s1) {

StringBuffer sb=new StringBuffer();

Set<Character> c1=new LinkedHashSet<Character>();

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

c1.add(s1.charAt(i));

for(char c2:c1)

sb.append(c2);

return sb.toString();

----------------------------------------------------------------------------------------------------||

42) input1 is a map<Integer,Float>

{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.

answer should be rounded to two numbers after decimal

eg:- the output number 15.2499999 should be 15.25

package Set3;

import java.util.*;

public class ClassSeT43 {

public static void main(String[] args) {

Map<Integer,Float> m1=new HashMap<Integer, Float>();

m1.put(1, (float) 12.93);

m1.put(2, (float) 15.67);

m1.put(3, (float) 17.27);


m1.put(4, (float) 14.88);

System.out.println(avgOfEvenKeyValues(m1));

public static float avgOfEvenKeyValues(Map<Integer, Float> 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;

----------------------------------------------------------------------------------------------------||

43) Color Code Validation:

String should starts with the Character '#'.

Length of String is 7.

It should contain 6 Characters after '#' Symbol.

It should contain Characters Between 'A-F' and Digits '0-9'.

if String is acceptable then Output1=1

else Output1=-1;

package Set3;

import java.util.*;

public class ClassSeT44 {

public static void main(String[] args) {

Scanner s=new Scanner(System.in);

String s1=s.next();

boolean b=colorCodeValidation(s1);
if(b==true)

System.out.println("valid color code");

else

System.out.println("invalid color code");

public static boolean colorCodeValidation(String s1) {

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!='#'){

if((Character.isAlphabetic(c)&& Character.isUpperCase(c)) || Character.isDigit(c))

b=true;

else{

b=false;

break;}}}

return b;

----------------------------------------------------------------------------------------------------||

44) Find the Maximum span of the given array.

span is the number of elements between the duplicate element

including those 2 repeated numbers.

if the array as only one elemnt,then the span is 1.

input[]={1,2,1,1,3}

output1=4

input[]={1,2,3,4,1,1,5}
output1=6

package Set3;

public class ClassSeT45 {

public static void main(String[] args) {

int[]a={1,2,1,1,3};

System.out.println(maxSpan(a));

public static int maxSpan(int[] a) {

String s2 = null;

int n=0;

StringBuffer sb=new StringBuffer();

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.

Ex: Input: california,3.

output: calnia.

package Set3;
public class ClassSeT46 {

public static void main(String[] args) {

String s1="california";

int n1=3;

System.out.println(subStringOfgivenString(s1,n1));

public static String subStringOfgivenString(String s1, int n1) {

StringBuffer sb=new StringBuffer();

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;

public class ClassSeT46 {

public static void main(String[] args) {

String ip1="aBrd";

String ip2="aqrbA";

int ip3=2;

System.out.println(charCheck(ip1,ip2,ip3));

public static boolean charCheck(String ip1, String ip2, int 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;

----------------------------------------------------------------------------------------------------||

47) Add elements of digits:9999

output:9+9+9+9=3+6=9;

package Set3;

public class ClassSeT47 {

public static void main(String[] args) {

int n=9999;

System.out.println(conversiontoaSingleDigit(n));

public static int conversiontoaSingleDigit(int 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;

----------------------------------------------------------------------------------------------------||

48) leap year or not using API?

package Set3;

import java.util.*;
public class ClassSeT48 {

public static void main(String[] args) {

String s="2013";

System.out.println(leapYear(s));

public static boolean leapYear(String s) {

int n=Integer.parseInt(s);

GregorianCalendar c=new GregorianCalendar();

boolean b=c.isLeapYear(n);

return b;

----------------------------------------------------------------------------------------------------||

49) perfect no or not?

package Set3;

public class ClassSeT49 {

public static void main(String[] args) {

int n=28;

System.out.println(perfectNumber(n));

public static boolean perfectNumber(int 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;

}
}

----------------------------------------------------------------------------------------------------||

50) HashMap<String,String> input1={“mouse”:”100.2”,”speaker”:”500.6”,”Monitor”:”2000.23”};

String[] input2={“speaker”,”mouse”};

Float output=600.80(500.6+100.2);

package Set3;

import java.util.*;

public class ClassSeT50 {

public static void main(String[] args) {

HashMap<String, String> m1=new HashMap<String, String>();

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));

public static float getTheTotalCostOfPheripherals(HashMap<String,String> m1,

String[] s) {

Float f=(float) 0;

Iterator<String> i=m1.keySet().iterator();

while(i.hasNext()){

String s1=(String) i.next();

Float f1=Float.parseFloat(m1.get(s1));

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

if(s[j].equals(s1))

f+=f1; }

return f;

----------------------------------------------------------------------------------------------------||

51) Input1=845.69, output=3:2;


Input1=20.789; output=2:3;

Input1=20.0; output=2:1;

output is in Hashmap format.

Hint: count the no of digits.

package Set3;

import java.util.*;

public class ClassSeT51 {

public static void main(String[] args) {

double d=845.69;

System.out.println(noOfDigits(d));

public static String noOfDigits(double d) {

int n1=0,n2=0;

String s=String.valueOf(d);

StringTokenizer t=new StringTokenizer(s,".");

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;

Wrapper Class – Integer I


 
This program is to illustrate Integer Wrapper class.
 
Write a program that accepts a “Integer” class type value as input and invokes some of the methods
defined in the Integer Wrapper class.
 
Refer sample input and output. All functions should be performed using the methods defined in the
Integer class.
 
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 and Output :
Enter an integer
540
The binary equivalent of 540 is 1000011100
The hexadecimal equivalent of 540 is 21c
The octal equivalent of 540 is 1034
Byte value of 540 is 28
Short value of 540 is 540
Long value of 540 is 540
Float value of 540 is 540.0
Double value of 540 is 540.0

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

 Input and Output Format:

There is no input to this program.


Refer sample output for formatting specifications.

 Sample Output:
Maximum exponent :127
Maximum value :3.4028235E38
Number of bits :32

public class Main {


public static void main(String[] args) {
System.out.println("Maximum exponent :"+Float.MAX_EXPONENT+" ");
System.out.println("Maximum value :"+Float.MAX_VALUE+" ");
System.out.println("Number of bits :"+Float.SIZE );
}
}

Converting a String to Double


Many a times we receive the input in String and convert it into other data types (Double / Integer).
Lets practice this simple exercise. Get the input amount as string and parse it using
'valueOf/parseDouble' method.
 
Create a main class "Main.java". 
 
Create another class file "BillHeader.java" with the following private members
Data Type Variable name
Date issueDate
Date dueDate
Double originalAmount
Double amountOutstanding
Include appropriate getters and setters.
 
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 the issue date as dd/MM/yyyy
12/07/2015
Enter the due date as dd/MM/yyyy
21/08/2015
Enter the original amount
2000
Enter amount paid so far
1000
Issue date: 12/07/2015
Due Date: 21/08/2015
Original amount Rs.2000.0
Amount outstanding Rs.1000.0

import java.util.Date;
import java.util.Scanner;
import java.io.IOException;
import java.text.*;

public class Main {


public static void main(String[] args) throws IOException, ParseException {

Scanner sc = new Scanner(System.in);

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

System.out.println("Enter the issue date as dd/MM/yyyy");

Date issueDate = formatter.parse(sc.nextLine());

System.out.println("Enter the due date as dd/MM/yyyy");


Date dueDate = formatter.parse(sc.nextLine());

System.out.println("Enter the original amount");


Double originalAmount = Double.parseDouble(sc.nextLine());

System.out.println("Enter amount paid so far");


Double paidAmount = Double.parseDouble(sc.nextLine());

Double amountOutstanding = originalAmount - paidAmount;

BillHeader billHeader = new BillHeader();

billHeader.setIssueDate(issueDate);
billHeader.setDueDate(dueDate);
billHeader.setOriginalAmount(originalAmount);
billHeader.setAmountOutstanding(amountOutstanding);

//System.out.println("Issue date: " + formatter.format(billHeader.getIssueDate()) + "\nDue Date: " +


formatter.format(billHeader.getDueDate()) + "\nOriginal amount Rs." + billHeader.getOriginalAmount() + "\nAmount
outstanding Rs." + billHeader.getAmountOutstanding());
System.out.println(billHeader);
}
}
import java.util.Date;
import java.text.*;
public class BillHeader {
private Date issueDate;
private Date dueDate;
private Double originalAmount;
private Double amountOutstanding;

public BillHeader() {
}

public BillHeader(Date issueDate, Date dueDate, Double originalAmount, Double amountOutstanding) {


super();
this.issueDate = issueDate;
this.dueDate = dueDate;
this.originalAmount = originalAmount;
this.amountOutstanding = amountOutstanding;
}

public Date getIssueDate() {


return issueDate;
}

public void setIssueDate(Date issueDate) {


this.issueDate = issueDate;
}

public Date getDueDate() {


return dueDate;
}

public void setDueDate(Date dueDate) {


this.dueDate = dueDate;
}

public Double getOriginalAmount() {


return originalAmount;
}

public void setOriginalAmount(Double originalAmount) {


this.originalAmount = originalAmount;
}

public Double getAmountOutstanding() {


return amountOutstanding;
}

public void setAmountOutstanding(Double amountOutstanding) {


this.amountOutstanding = amountOutstanding;
}

@Override
public String toString() {

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");


//return "Issue date: " + issueDate + "\nDue Date: " + dueDate + "\nOriginal amount Rs." +
originalAmount + "\nAmount outstanding Rs." + amountOutstanding;
return "Issue date: " + formatter.format(getIssueDate()) + "\nDue Date: " + formatter.format(getDueDate()) +
"\nOriginal amount Rs." + getOriginalAmount() + "\nAmount outstanding Rs." + getAmountOutstanding();
}
}
String Reversal
Write a program to reverse a given string.
 
Input and Output Format:
Input consists of a string.
 
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.
 
Sample Input and Output:
Enter a string to reverse
Punitha
Reverse of entered string is : ahtinuP

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);

System.out.println("Enter a string to reverse");


String str = sc.nextLine();
StringBuffer sbr = new StringBuffer(str);

// To reverse the string


System.out.println("Reverse of entered string is : " + sbr.reverse());

}
}

String API : startsWith() : Illustration


Write a program to illustrate the use of the method startsWith() defined in the string API.
 
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 and Output 1:
Enter the string
Ampphisoft
Enter the start string
Amphi
"Ampphisoft" does not start with "Amphi"
 
Sample Input and Output 2:
Enter the string
Amphisoft
Enter the start string
Amphi
"Amphisoft" starts with "Amphi"
 

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+'"');
}
}
}

String API : split() : Illustration


This program is to illustrate the use of the method split() defined in the string API.
Write a program to split a string based on spaces (There may be multiple spaces too) and returns the
tokens in the form of an array.
 
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 and Output :
Enter the string
Amphisoft Technologies is             a                  private     organization
The words in the string are
Amphisoft
Technologies
is
a
private
organization
 

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());
}
}
}

Customer Address Using String Builder


We know that Strings are immutable and are placed in a common pool called String Pool. It is always
suggested that if the value of a string variable changes quite often, then the string pool would keep
creating new strings and is considered as a bad practice. In these cases, the alternate way is to use
StringBuilder & StringBuffer.

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

// fill your code here

public class Address {


private String line1;
private String line2;
private String city;
private String country;
private int zipCode;

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;
}

public String getLine1() {


return line1;
}

public void setLine1(String line1) {


this.line1 = line1;
}

public String getLine2() {


return line2;
}

public void setLine2(String line2) {


this.line2 = line2;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

public String getCountry() {


return country;
}

public void setCountry(String country) {


this.country = country;
}

public int getZipCode() {


return zipCode;
}

public void setZipCode(int zipCode) {


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

Scanner sc = new Scanner(System.in);


System.out.println("Enter Address Details :\nEnter Line 1 :");
String line1 = sc.nextLine();
System.out.println("Enter Line 2 :");
String line2 = sc.nextLine();
System.out.println("Enter City :");
String city = sc.nextLine();
System.out.println("Enter Country :");
String country = sc.nextLine();
System.out.println("Enter Zip Code :");
int zipCode = sc.nextInt();

Address address = new Address(line1, line2, city, country, zipCode);


System.out.println(address.toString());
}
}

String API : endsWith() : Illustration


Write a program to illustrate the use of the method endsWith() defined in the string API.
 
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 and Output 1:
Enter the string
Ampphisoft
Enter the end string
softi
"Ampphisoft" does not end with "softi"
 
Sample Input and Output 2:
Enter the string
Amphisoft
Enter the end string
soft
"Amphisoft" ends with "soft"

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();

if( str.endsWith( strEnd ) ) {


System.out.println( "\"" + str + "\"" + " ends with \"" + strEnd + "\"" );
} else {
System.out.println( "\"" + str + "\"" + " does not end with \"" + strEnd + "\"" );
}

}
}

Wrapper Class – Integer II


This program is to illustrate the parseInt() method defined in the Integer Wrapper class.
 
Write a program that accepts 3 String values as input and invokes some of the methods defined in the
Integer Wrapper class.
 
Refer sample input and output. All functions should be performed using the methods defined in the
Integer class.
 
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 and Output :
Enter the binary number
111
Enter the octal number
11
Enter the hexadecimal number
1F
The integer value of the binary number 111 is 7
The integer value of the octal number 11 is 9
The integer value of the hexadecimal number 1F is 31
 

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("Enter the octal number");


String octalNo = scnr.next();

System.out.println("Enter the hexadecimal number");


String hexaDecimalNo = scnr.next();

int binNo = Integer.parseInt(binaryNo,2);


int octNo = Integer.parseInt(octalNo,8);
int hexNo = Integer.parseInt(hexaDecimalNo,16);

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);

}
}

String API : replace() : Illustration


Write a program to illustrate the use of the method replace() defined in the string API.
Two companies enter into a Marketing Agreement and they prepare an Agreement Draft. After that
one of the companies changes its name. The name changes need to be made in the Agreement Draft
as well. Write a program to perform the name changes in the agreement draft.
 
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 and Output :
Enter the content of the document
Amphi is a private organisation. Amphi is a product based company. EBox is a Amphi product
Enter the old name of the company
Amphi
Enter the new name of the company
Amphisoft
The content of the modified document is
Amphisoft is a private organisation. Amphisoft is a product based company. EBox is a Amphisoft
product

Equals & == in String


One important property of String literals are that - All String literals are placed in a common pool
called String pool. If I create two string literals with the same content, both will point to the same
object. Moreover, If i reassign the variable to another value, a new space is created and the existing
space is left with the same value. Once a value is assigned or allocated it is never modified until its
destroyed. This is why strings are called immutable.
"==" operator compares address, but since string literals point to the same location (if values are
same) it returns true.
"equals" operator compares the content of the two strings.

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 ].
 

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 First Customer Details :
Enter Customer Name :
Roger
Enter Customer Email :
[email protected]
Enter Second Customer Details :
Enter Customer Name :
Lee
Enter Customer Email :
[email protected]
The Email ids of Roger and Lee are not equal
Comparing without considering the cases :
The Email ids of Roger and Lee are Equal

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

Create table building (id integer,owner_name varchar2(100),address varchar2(100),building_type_id


integer,contact_number varchar2(100),email_address varchar2(100));

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.

Alter table building add description varchar(255) not null;

Remove column from b

...

Alter table building drop column address;

Change column type i.


alter table building modify owner_name varchar2(500);

Table building_type insert

Q15

Select variance(payable_amount)”variance_payable_amount” from Bill where payment_Date Like ‘%ocy%’;

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 and Output:


Enter branding expenses
20000
Enter travel expenses
40000
Enter food expenses
15000
Enter logistics expenses
25000
Total expenses : Rs.100000.00
Branding expenses percentage : 20.00%
Travel expenses percentage : 40.00%
Food expenses percentage : 15.00%
Logistics expenses percentage : 25.00%
Additional Sample TestCases
Sample Input and Output 1 :
Enter branding expenses
855
Enter travel expenses
877779
Enter food expenses
5544
Enter logistics expenses
2256
Total expenses : Rs.886434.00
Branding expenses percentage : 0.10%
Travel expenses percentage : 99.02%
Food expenses percentage : 0.63%
Logistics expenses percentage : 0.25%

"Fantasy Kingdom" is a brand new import java.util.*;


T Amusement park that is going to be import java.io.*;
H
R inaugurated shortly in the City and is
class Main{
I promoted as the place for breath-taking
L charm. The theme park has more than 30 public static void main(String[] args) throws Exception{
L
R
exhilarating and thrilling rides and as a Scanner sc=new Scanner(System.in);
I special feature of the park, the park int age=sc.nextInt();
D Authorities have placed many Booking if((age<15)||(age>60)){
E System.out.println("Not Allowed");
Kiosks at the entrance which would }else{
facilitate the public to purchase their
entrance tickets and ride tickets. System.out.println("Allowed");}
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

Write a program to generate a rectangular import java.util.*;


C pattern of stars. import java.io.*;
H
A *
class Main{
R ** public static void main(String[] args) throws Exception{
A *** Scanner sc=new Scanner(System.in);
C
T **** int n=sc.nextInt();
E ***** for(int i=1;i<=n;i++){
R   for(int j=1;j<=i;j++){
P System.out.print("*");
A }
Input and Output Format:
T System.out.println();
T Input consists of a single integer that }
E corresponds to n, the number of rows. }
R   }
N

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 System.out.println("Enter the subject5 mark");
H sub5 = scan.nextInt();
exam.
I if(sub1==5||sub2==5||sub3==5||sub4==5||sub5==5)
P Student should not have fail any of {
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)
System.out.println("Yes");
he/she is excellent in some of the subjects. else
 He/She must have a grade point 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
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 and Output 1:


Enter the item type name
Catering
Enter the cost per day
25000.00
Enter the deposit
10000.50
Item type details
Name : Catering
CostPerDay : 25000.00
Deposit : 10000.50
 

Little App helps you discover great places import java.util.Scanner;


C to eat around or de-stress in all major import java.text.DecimalFormat;
O cities across 20000+ merchants. Explore class Main {
M restaurants, spa & salons and activities to public static void main(String[] args) {
P
find your next fantastic deal. The DecimalFormat df = new DecimalFormat("0.00");
A
R development team of Little App seeks your Scanner sc = new Scanner(System.in);
E help to find the duplication of user System.out.println("Enter branding expenses");
int branding = sc.nextInt();
accounts.  System.out.println("Enter travel expenses");
P int travel = sc.nextInt();
H Write a Java program to get two users System.out.println("Enter food expenses");
O details and display whether their phone int food = sc.nextInt();
N numbers are same or not with the System.out.println("Enter logistics expenses");
E following class and methods. int logistics = sc.nextInt();
N
double totalexpense = branding+food+travel+logistics;
U [Note : Strictly adhere to the object-oriented
M double brandingper=branding*100/totalexpense;
specifications given as a part of the problem
B double travelingper=travel*100/totalexpense;
statement.
E Follow the naming conventions as double foodper=food*100/totalexpense;
R mentioned. Create separate classes in double logisticsper=logistics*100/totalexpense;
- separate files.] System.out.println("Total expenses :
J   Rs."+df.format(totalexpense));
A
V
Create a class named User with the System.out.println("Branding expenses percentage :
following private attributes/variables. "+df.format(brandingper)+"%");
A
Date Type Variable //System.out.print("% \n");
System.out.println("Travel expenses percentage : "
String name +df.format(travelingper)+"%");
String username//cimalFormat df1 = new DecimalFormat("#.##");
String passwordSystem.out.println("Food expenses percentage :
long phoneNo "+df.format(foodper)+"%");
Include appropriate getters and setters. System.out.println("Logistics expenses percentage : "
+df.format(logisticsper)+"%");
Include four-argument  constructor with
}
parameters in the following order, }
public User(String name, String username,
String password, long phoneNo)

Include the following method in User class.


Method
public boolean comparePhoneNumber(User user)

Create another class Main and write a


main method to test the above class.

Input and Output Format


Refer sample input and output for
formatting specifications.
All text in bold corresponds to the input
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

"Fantasy Kingdom" is a brand new import java.util.*;


T Amusement park that is going to be import java.io.*;
H
R inaugurated shortly in the City and is
class Main{
I promoted as the place for breath-taking
L charm. The theme park has more than 30 public static void main(String[] args) throws Exception{
L
R
exhilarating and thrilling rides and as a Scanner sc=new Scanner(System.in);
I special feature of the park, the park int age=sc.nextInt();
D Authorities have placed many Booking if((age<15)||(age>60)){
E System.out.println("Not Allowed");
Kiosks at the entrance which would }else{
facilitate the public to purchase their
entrance tickets and ride tickets. System.out.println("Allowed");}
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

Write a program to generate a rectangular import java.util.*;


C pattern of stars. import java.io.*;
H
A *
class Main{
R ** public static void main(String[] args) throws Exception{
A *** Scanner sc=new Scanner(System.in);
C
T **** int n=sc.nextInt();
E ***** for(int i=1;i<=n;i++){
R   for(int j=1;j<=i;j++){
P System.out.print("*");
A }
Input and Output Format:
T System.out.println();
T Input consists of a single integer that }
E corresponds to n, the number of rows. }
R   }
N

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.

Hence create a class named Fraction with the following method.


 

Method Name Description

This method should display


void printValue(int,int)                                   
the fraction in simplest form.

 
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;

public class Fraction {

public void printValue(int a, int b) {

int fraction = a / b;

String str1 = Integer.toString(a);

String str2 = Integer.toString(b);

BigInteger big1 = new BigInteger(str1);

BigInteger big2 = new BigInteger(str2);

BigInteger bigVal = big1.gcd(big2);

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;

System.out.printf("%d %d/%d", ans, rem, b);

import java.util.*;

public class Main{

public static void main(String args[]){

//get inputs

Scanner sc=new Scanner(System.in);

int num=sc.nextInt();

int den=sc.nextInt();

Fraction fraction=new Fraction();

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.

Note : Rows and columns are numbered starting from 1.

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;

public class Main {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

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");

Inheritance - Aircraft Seat- Business Class Seat 


 
A passenger can travel in flight in the normal aircraft seat or the Business class seat. Business class of service offers significantly
more comfort and amenities than standard Economy. While in-flight amenities, service and entertainment available in Business Class
are often comparable across airline carriers, the type of seat offered can vary significantly. Business Class seats can be categorized
by one of the following types: 
1.Recliner Seats 
2.Angle Lie-Flat Seats 
3.Flat Bed Seats 
4.Suites 
They are often provided with a Larger personal TV screens and more viewing options that could provide news, sports and
entertainment channels. 
 
Create a class AircraftSeat with the following private variables: 
Variable Name Data Type
String aircraftName
Int seatId
String travelClassid
Include getters and setters method in the AircraftSeat class. 
Create a class BusinessClassSeat(which should inherit AircraftSeat)  with the following private variables: 
Variable Name Data Type
int businessClassSeatid
String seatType
String tvChannelpreferences
  
Include getters and setters method in the BusinessClassSeat class. 
Create a method  void displayDetails() in the BusinessClassSeat class. This method should display the client details along with the
agent details. 
 
Sample input and output: 
Enter the aircraft name 
lufthansa 
Enter the seat id 
24 
Enter the travelClassid 

Enter the seat Type 
Recliner seat 
Enter the businessClassSeatid 
12 
Enter the TV Channel preferences 
Entertainment 
Aircraft details 
Aircraft name : lufthansa 
Seat Id : 24 
Travelclass id : B 
Seat type : Recliner seat 
Business Class seat id : B12 
TV Channel preferences : Entertainment 
 
public class AircraftSeat {

private String aircraftName;

private int seatId;

private String travelClassid;

public String getAircraftName() {

return aircraftName;

public void setAircraftName(String aircraftName) {

this.aircraftName = aircraftName;

public int getSeatId() {

return seatId;

public void setSeatId(int seatId) {

this.seatId = seatId;

public String getTravelClassid() {

return travelClassid;

public void setTravelClassid(String travelClassid) {

this.travelClassid = travelClassid;

public class BusinessClassSeat extends AircraftSeat {

private int businessClassSeatid;

private String seatType;

private String tvChannelpreferences;

public int getBusinessClassSeatid() {


return businessClassSeatid;

public void setBusinessClassSeatid(int businessClassSeatid) {

this.businessClassSeatid = businessClassSeatid;

public String getSeatType() {

return seatType;

public void setSeatType(String seatType) {

this.seatType = seatType;

public String getTvChannelpreferences() {

return tvChannelpreferences;

public void setTvChannelpreferences(String tvChannelpreferences) {

this.tvChannelpreferences = tvChannelpreferences;

public void displayDetails()

{ System.out.println("Aircraft details ");

System.out.println("Aircraft name : "+getAircraftName());

System.out.println("Seat Id : "+getSeatId());

System.out.println("Travelclass id : "+getTravelClassid());

System.out.println("Seat type : "+getSeatType());

System.out.println("Business Class seat id : "+getTravelClassid()+getBusinessClassSeatid());

System.out.println("TV Channel preferences : "+getTvChannelpreferences());

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;
public class Main {

public static void main(String args[]) throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

BusinessClassSeat c = new BusinessClassSeat();

System.out.println("Enter the aircraft name");

c.setAircraftName(br.readLine());

System.out.println("Enter the seat id");

int seatId=Integer.parseInt(br.readLine());

c.setSeatId(seatId);

System.out.println("Enter the travelClassid");

c.setTravelClassid(br.readLine());

System.out.println("Enter the seat Type");

c.setSeatType(br.readLine());

System.out.println("Enter the businessClassSeatid");

int businessClassSeatid=Integer.parseInt(br.readLine());

c.setBusinessClassSeatid(businessClassSeatid);

System.out.println("Enter the TV Channel preferences");

c.setTvChannelpreferences(br.readLine());

c.displayDetails();

Abstract Classes - Booking Tickets


[Adhere to the OOPs specifications specified here. Follow the naming conventions for getters and setters.] 
Create an abstract class named Aircraft with the following private attributes / member variables. 
 Data Type Variable Name 
String aircraftName
String Source
String Destination
 Include appropriate getters and setters. 
Include a 3-argument constructor, the order of the arguments is aircraftName, source,destination. 
Include an abstract method named displayDetails(), The return type of this method is void. 
 
Create a class named PublicAircraft . The class PublicAircraft  is a derived class of Booking. Include the following private attributes /
member variables. 
Data Type Variable Name 
Boolean checkinbeforetwohours
int noOfKgsallowed
float additionalFeeperkg
Here checkinbeforetwohours is a Boolean value that says whether the passenger should check in before two hours or not.
 This flag is false in case of PrivateAircraft. 
 Include appropriate getters and setters. 
Include a 6-argument constructor, the order of the arguments is aircraftName, source,destination, checkinbeforetwohours,
pilotPreference, purpose
Override the abstract method displayDetails() defined in the Aircraft class, this method prints the booking details as entered by the
passenger (refer sample input and output). 
Create a class named PrivateAircraft . The class PrivateAircraft  is a derived class of Booking. Include the following private
attributes / member variables. 
Data Type Variable Name 
Boolean checkinbeforetwohours
String pilotPreference
String purpose
 Include appropriate getters and setters. 
Include a 6-argument constructor, the order of the arguments is aircraftName, source,destination, checkinbeforetwohours,
pilotPreference., purpose
Override the abstract method displayDetails() defined in the Aircraft class, this method prints the booking details as entered by the
passenger (refer sample input and output). 
 
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 1: 
Enter the name of the Aircraft 
Jet Airways 
Enter the source 
Bangalore 
Enter the destination 
Chennai
Enter the type of Flight 
1.Public Aircraft
2.Private Aircraft

Is the flight check in before two hours
Yes
Enter the number of kgs allowed per person
15
Enter the additional fee charged for extra baggage per Kg
750.00
Flight Details :
Private Aircraft
Aircraft Name : Jet Airways 
Source : Bangalore 
Destination : Chennai
Flight check in before two hours : Yes
Number of kgs allowed per person : 15
Additional fee charged for extra baggage per Kg : 750.00

Sample Input and Output 2 :


Enter the name of the Aircraft
Jet Airways
Enter the source
Chennai
Enter the destination
Bangalore
Enter the type of Flight
1.Public Aircraft
2.Private Aircraft
2
Is the flight check in before two hours
No
Enter the name of the pilot choosed
Akilan
Enter the Purpose of your flight
Medical
Flight Details :
Private Aircraft:
Aircraft Name : Jet Airways
Source : Chennai
Destination : Bangalore
Flight check in before two hours : No
Pilot choosed : Akilan
Purpose of the flight :  Medical
 
 

public abstract class Aircraft {

private String aircraftName;

private String source;

private String destination;

public Aircraft(String aircraftName, String source, String destination) {

super();

this.aircraftName = aircraftName;

this.source = source;

this.destination = destination;

public String getAircraftName() {

return aircraftName;

public void setAircraftName(String aircraftName) {

this.aircraftName = aircraftName;

public String getSource() {

return source;

public void setSource(String source) {

this.source = source;

}
public String getDestination() {

return destination;

public void setDestination(String destination) {

this.destination = destination;

@Override

public String toString() {

return "Aircraft [aircraftName=" + aircraftName + ", source=" + source + ", destination=" + destination

+ ", getAircraftName()=" + getAircraftName() + ", getSource()=" + getSource() + ",


getDestination()="

+ getDestination() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()="

+ super.toString() + "]";

public abstract void displayDetails();

public class PrivateAircraft extends Aircraft {

private Boolean checkinbeforetwohours;

private String pilotPreference;

private String purpose;

public PrivateAircraft(String aircraftName, String source, String destination, Boolean checkinbeforetwohours,

String pilotPreference, String purpose) {

super(aircraftName, source, destination);

this.checkinbeforetwohours = checkinbeforetwohours;

this.pilotPreference = pilotPreference;

this.purpose = purpose;

public Boolean getCheckinbeforetwohours() {

return checkinbeforetwohours;
}

public void setCheckinbeforetwohours(Boolean checkinbeforetwohours) {

this.checkinbeforetwohours = checkinbeforetwohours;

public String getPilotPreference() {

return pilotPreference;

public void setPilotPreference(String pilotPreference) {

this.pilotPreference = pilotPreference;

public String getPurpose() {

return purpose;

public void setPurpose(String purpose) {

this.purpose = purpose;

@Override

public void displayDetails() {

System.out.println("Aircraft Name : "+getAircraftName());

System.out.println("Source : "+getSource());

System.out.println("Destination : "+getDestination());

System.out.println("Flight check in before two hours :"+getCheckinbeforetwohours());

System.out.println("Pilot choosed :"+getPilotPreference() );

System.out.println("Purpose of the flight : "+getPurpose());

public class PublicAircraft extends Aircraft {

private Boolean checkinbeforetwohours;


private int noOfKgsallowed;

private float additionalFeeperkg;

public PublicAircraft(String aircraftName, String source, String destination,

int noOfKgsallowed, float additionalFeeperkg,Boolean b1) {

super(aircraftName, source, destination);

this.checkinbeforetwohours = checkinbeforetwohours;

this.noOfKgsallowed = noOfKgsallowed;

this.additionalFeeperkg = additionalFeeperkg;

public Boolean getCheckinbeforetwohours() {

return checkinbeforetwohours;

public void setCheckinbeforetwohours(Boolean checkinbeforetwohours) {

this.checkinbeforetwohours = checkinbeforetwohours;

public int getNoOfKgsallowed() {

return noOfKgsallowed;

public void setNoOfKgsallowed(int noOfKgsallowed) {

this.noOfKgsallowed = noOfKgsallowed;

public float getAdditionalFeeperkg() {

return additionalFeeperkg;

public void setAdditionalFeeperkg(float additionalFeeperkg) {

this.additionalFeeperkg = additionalFeeperkg;

@Override

public void displayDetails() {

System.out.println("Aircraft Name : "+getAircraftName());

System.out.println("Source : "+getSource());

System.out.println("Destination : "+getDestination());
System.out.println("Flight check in before two hours :"+checkinbeforetwohours);

System.out.println("Number of kgs allowed per person : "+getNoOfKgsallowed() );

System.out.println("Additional fee charged for extra baggage per Kg : "+getAdditionalFeeperkg());

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class Main {

public static void main(String args[]) throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the name of the Aircraft");

String aircraftName=br.readLine();

System.out.println("Enter the source");

String source=br.readLine();

System.out.println("Enter the destination");

String destination = br.readLine();

System.out.println("Enter the type of Flight\n1.Public Aircraft\n2.Private Aircraft");

int choice=Integer.parseInt(br.readLine());

if(choice==1)

{
System.out.println("Is the flight check in before two hours");

String ans = br.readLine();

Boolean b1;

if(ans.equals("yes"))

b1=true;

else

b1=false;

System.out.println("Enter the number of kgs allowed per person");

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("Flight Details :");

System.out.println("Public Aircraft:");

b.displayDetails();

if(choice==2)

System.out.println("Is the flight check in before two hours");

Boolean ans = Boolean.parseBoolean(br.readLine());

System.out.println("Enter the name of the pilot choosed");

String pilotPreference=br.readLine();

System.out.println("Enter the Purpose of your flight");


String purpose=br.readLine();

Aircraft b = new PrivateAircraft(aircraftName,source,destination,ans,pilotPreference,purpose);

System.out.println("Flight Details :");

System.out.println("Private Aircraft:");

b.displayDetails();

Extra Passengers list


 
Air India allows the passengers to book the tickets for festive time with special offers.
Due to the Increased booking to travel from Bangalore to Chennai, the Air craft that
could accomodate larger number of passengers  which was alloted for the passengers
travelling from Chennai to Coimbatore has been rescheduled to Bangalore to Chennai
location. So the passengers travelling from Chennai to Coimbatore were alloted with a
smaller size Air craft. Write a program to find out the passengers who has been left out
without seats in Chennai to Coimbatore travel. 
Create a list that holds the booked passenger names. Display the passengers who has
been left out without seats.
 
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 and Output :

Enter the number of passengers Booked


8
Enter the passenger's name who Booked
Thara
Shanmathi
Raghul
Haritha
madhu
Praveen
Jimesh
Krishna
Enter the number of seats available
5
Extra Passengers list
[Praveen, Jimesh, Krishna]

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 class Book with following variables/ attributes.


Data Type Variable
String Code
String Title
String Author
double Price
Include appropriate getters and setters.
Include default and parameterized constructor with parameters in the following order
public Book(String code, String title, String author, String price)
Override toString() method to display the book details.

Create a class named as BookBO, which contains following methods,


Method  Description
In this method, create a book object. Validate the book code with the
following conditions.
1. The book code should always start with the starting character of the book
name (case insensitive).
public Book 2. Next two character should be equal to the first two characters of author
createBook(String details) name(case insensitive).
3. Next set of characters should be integers.

If the book code fails any condition throw InvalidBookException, else


create and return the book object.

Create a custom exception class InvalidBookException which extends Exception class.

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.

Input and Output Format


Refer sample input and output for formatting specifications.
All text in bold corresponds to the input and the rest corresponds to output.

Sample Input and Output 1:


Enter the book details(code,title,author,price)
CMA001,Clean Code,Martin,2000
Book details: 
Code: CMA001
Title: Clean Code
Author: Martin
Price: 2000.00
 
Sample Input and Output 2:
Enter the book details(code,title,author,price)
COM1F,Code Complete,McConnell,1500
InvalidBookException: Invalid book code

public class Book {

private String code;

private String title;

private String author;

private double price;

public String getCode() {

return code;

public void setCode(String code) {

this.code = code;

public String getTitle() {

return title;

public void setTitle(String title) {

this.title = title;

public String getAuthor() {

return author;
}

public void setAuthor(String author) {

this.author = author;

public double getPrice() {

return price;

public void setPrice(double price) {

this.price = price;

//fill your code here

public String toString() {

//fill your code here

public class BookBO {

public Book createBook(String details) {


Book b;
b=new Book();
char arr[]=details.toCharArray();
return null;
//fill your code here
}
}

public class InvalidBookException extends Exception{

//fill your code here

public class Main {


public static void main(String[] args) throws Exception{

//fill your code here

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 a class named ItemType with the following private member variables / attributes.


Data Type Variable
String name
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 method

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.

Example of getters and setters

private String name;

public String getName( ) {


        return name;
}

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 and Output 1:


Enter the item type name
Catering
Enter the cost per day
25000.00
Enter the deposit
10000.50
Item type details
Name : Catering
CostPerDay : 25000.00
Deposit : 10000.50
 

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)

Include the following method in User class.


Method Description
public boolean comparePhoneNumber(User user) In this method, compare the phone number of the two user an

Create another class Main and write a main method to test the above class.

Input and Output Format


Refer sample input and output for formatting specifications.
All text in bold corresponds to the input 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

import java.text.DecimalFormat;

public class ItemType {

private String name;

private double costPerDay,deposit;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public double getCostPerDay() {

return costPerDay;

public void setCostPerDay(double costPerDay) {

this.costPerDay = costPerDay;

public double getDeposit() {

return deposit;

public void setDeposit(double deposit) {

this.deposit = deposit;

public void display(){


DecimalFormat df=new DecimalFormat("0.00");

System.out.println("Item type details");

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{

public static void main(String[] args) throws Exception {

ItemType i = new ItemType();

Scanner sc = new Scanner(System.in);

System.out.println("Enter the item type name");

i.setName(sc.nextLine());

System.out.println("Enter the cost per day");

i.setCostPerDay(sc.nextDouble());

System.out.println("Enter the deposit");

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 a class named Rectangle with the following private member variables / attributes.


Data Type Variable
int length
int width

Include appropriate getters and setters.


Include 2 argument constructor. The order in which the argument should be passed is Rectangle(int
length, int width)

In the Rectangle class include the following methods.


Method Description
int area( )  This method computes the area of the rectange and returns it.
 This method displays the length and width of the rectangle. Display the st
void display( )
dimensions.
Rectangle dimensionChange(int
 This method changes the rectangle dimension by increasing the length an
d)

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).]

Input and Output Format:


Refer sample input and output for formatting specifications.
[All text in bold correspondstoinput and the rest corresponds to output.]

Sample Input and Output 1:


Enter the length of the rectangle
5
Enter the width of the rectangle
6
Rectangle Dimension
Length:5
Width:6
Area of the Rectangle:30
Enter the new dimension
2
Rectangle Dimension
Length:10
Width:12
Area of the Rectangle:120

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.
 

Sample Input and Output


Enter the first string : 
Amphisoft
Enter the second string : 
TECHNOLOGIES
Substring : hisoft
Character at 3rd position is : H
Is str1 and str2 equal : false
Concatenated string : AmphisoftTECHNOLOGIES
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 Input and Output 1:


Enter n :
3
Enter numbers : 
100
23
15
Enter strings : 
hi
hello
welcome
Displaying numbers
100
23
15
Displaying strings
hi
hello
welcome
 

Command Line Argument - Count


Write a program to accept strings as command line argument and print the number of arguments
entered.

Sample Input (Command Line Argument) 1:


Command Arguments

Sample Output 1:
Arguments :
Command
Arguments
Number of arguments is 2

Sample Input (Command Line Argument) 1:


Commands

Sample Output 2:
Arguments :
Commands
Number of arguments is 1

public class Main{

public static void main(String[] args){

int count=0;

System.out.println("Arguments :");

for(int a=0;a<args.length;a++)

System.out.println(args[a]);

count++;

System.out.println("Number of arguments is "+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)

The Article class includes the following methods


Method Description
void This method counts the number of articles in a given line
run() and stores the value in the count variable.

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.

Input and Output format:


Refer to sample Input and Output for formatting specifications.
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input and Output:
Enter the number of lines
3
Enter line 1
An article is a word used to modify a noun, which is a person, place, object, or idea.
Enter line 2
Technically, an article is an adjective, which is any word that modifies a noun.
Enter line 3
There are two different types of articles.
There are 7 articles in the given input

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Article extends Thread {

String line;

int count;

public Article() {

super();

public Article(String line) {

super();
this.line = line;

public String getLine() {

return line;

public void setLine(String line) {

this.line = line;

public int getCount() {

return count;

public void setCount(int count) {

this.count = count;

@Override

public void run() {

Matcher m = Pattern.compile("(?i)\\b((a)|(an)|(the))\\b").matcher(this.getLine());

while (m.find()) {

this.count++;

import java.util.Scanner;

public class Main {

public static void main(String[] args) throws InterruptedException{

Scanner sc = new Scanner(System.in);


System.out.println("Enter the number of lines");

int n = sc.nextInt();

int count = 0;

sc.nextLine();

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

Article a = new Article();

System.out.println("Enter line "+(i+1));

a.setLine(sc.nextLine());

a.start();

a.join();

count +=a.getCount();

System.out.println("There are "+count+" articles in the given input");

}
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.

Include following methods.


Override run() method which displays event name along with their status (i.e) Profit or Loss. 
If  (seats booked / hall capacity) * 100 >= 60 then it is a profit else loss .

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:

The first line of input corresponds to the number of events 'n'.


The next 'n' line of input corresponds to the event details in CSV format of (Event Name,Hall
Name,Cost,Hall Capacity,Seats Booked).
Refer to sample input for formatting specifications.

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".

Sample Input and Output 1:


[All text in bold corresponds to input and rest corresponds to output]

Enter the number of events


4
Enter event details in CSV
Party,Le Meridian,12000,400,250
Wedding,MS mahal,500000,1000,400
Alumni meet,Ramans,10000,600,300
Plaza party,Rizzodous,30000,1200,1000
Party yields profit
Wedding yields loss
Alumni meet yields loss
Plaza party yields profit

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class Event {


private String name;
private HallBooking hallBooking;

public Event() {
}

public Event(String name, HallBooking hallBooking) {


this.name = name;
this.hallBooking = hallBooking;
}

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}

public HallBooking getHallBooking() {


return hallBooking;
}

public void setHallBooking(HallBooking hallBooking) {


this.hallBooking = hallBooking;
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class ComputeStatus implements Runnable {


List<Event> eventList;

public List<Event> getEventList() {


return eventList;
}

public void setEventList(List<Event> eventList) {


this.eventList = eventList;
}

@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(String hallName, Double cost, Integer hallCapacity, Integer seatsBooked) {


this.hallName = hallName;
this.cost = cost;
this.hallCapacity = hallCapacity;
this.seatsBooked = seatsBooked;
}

public HallBooking() {
}

public String getHallName() {


return hallName;
}

public void setHallName(String hallName) {


this.hallName = hallName;
}

public Double getCose() {


return cost;
}

public void setCose(Double cose) {


this.cost = cose;
}

public Integer getHallCapacity() {


return hallCapacity;
}

public void setHallCapacity(Integer hallCapacity) {


this.hallCapacity = hallCapacity;
}

public Integer getSeatsBooked() {


return seatsBooked;
}

public void setSeatsBooked(Integer seatsBooked) {


this.seatsBooked = seatsBooked;
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of events");
int noOfEvents = Integer.parseInt(scanner.nextLine());
if (noOfEvents > 0 && noOfEvents % 2 == 0) {
System.out.println("Enter event details in CSV");
String eventDetail = "";
List<Event> eventList = new ArrayList<Event>();
ComputeStatus computeStatus = new ComputeStatus();
// computeStatus.setEventList(eventList);
ThreadGroup threadGroup = new ThreadGroup("TG1");
Thread t1 = new Thread(threadGroup, computeStatus, "T1");
Thread t2 = new Thread(threadGroup, computeStatus, "T2");
for (int i = 0; i < noOfEvents; i++) {
eventDetail = scanner.nextLine();
String[] details = eventDetail.split(",");
HallBooking hallBooking = new HallBooking(details[1],
Double.parseDouble(details[2]),
Integer.parseInt(details[3]),
Integer.parseInt(details[4]));
Event event = new Event(details[0], hallBooking);
eventList.add(event);
computeStatus.setEventList(eventList);
if (i + 1 == noOfEvents / 2) {
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
eventList.clear();
}
if (i + 1 == noOfEvents) {
t2.start();
}
}
} else {
System.out.println("Invalid Input");
}
}
}
Multi-Threading
To illustrate the creation of multiple threads in a program performing concurrent operations, let us
consider the processing of the following mathematical equation:
p = sin (x) + cos (y) + tan (z)
As these trigonometric functions are independent operations without any dependencies between
them, they can be executed concurrently. After that their results can be combined to produce the
final result.

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.

Input & Output Format:


Refer sample Input and Output for formatting specifications.

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));

Sample Input and Output :


Enter the Degree for Sin :
45
Enter the Degree for Cos :
30
Enter the Degree for Tan :
30
Sum of sin, cos, tan = 2.15
 
public class CosClass extends Thread {
double value;
double cos;

public CosClass(double cos) {


// TODO Auto-generated constructor stub
this.cos = cos;
}

@Override
public void run() {

double b = Math.toRadians(cos);
value = Math.cos(b);

}
public double getValue() {

return value;
}

public class SineClass extends Thread {


double value;
double sins;

public SineClass(double sins) {


this.sins = sins;
}

@Override
public void run() {
double b = Math.toRadians(sins);
value = Math.sin(b);

public double getValue() {

return value;
}

public class TanClass extends Thread {


double value;
double tan;

public TanClass(double tan) {


// TODO Auto-generated constructor stub
this.tan = tan;
}

@Override
public void run() {

double b = Math.toRadians(tan);

value = Math.tan(b);

public double getValue() {

return value;
}

import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {


// TODO Auto-generated method stub
DecimalFormat df = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Degree for Sin : ");
double sins = sc.nextDouble();
System.out.println("Enter the Degree for Cos : ");
double coss = sc.nextDouble();
System.out.println("Enter the Degree for Tan : ");
double tans = sc.nextDouble();

SineClass s = new SineClass(sins);


CosClass c = new CosClass(coss);
TanClass t = new TanClass(tans);

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();
}

System.out.println("Sum of sin, cos, tan = " + df.format(s.getValue() + t.getValue() + c.getValue()));

}
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.

 Method Method Description


This method accepts an integer 'n' as an argument and
long calculateFactorial(int n)
returns the factorial of the number 'n'.
 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 FactorialJUnit and include the following test methods to test
the calculateFactorial method in the above code specifications.

 Test Case Method Name Method Description


This method is used to test the factorial
Test case 1 testFactorial
values.

Write a createBoInstance method used to create the object for FactorialBO class


 

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));
}
}

Email domain validation


 

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]

DomainValidationBO class contains the following method.


 

Method Method Description


This method accepts an email id as argument and returns
String
"Valid email address" if the mail id is valid else return "Invalid
validateMailDomain(String mail)
email address".
 

 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.

 Test Case Method Name Method Description


Test case 1 testValidDomain This method is used to test valid mail id scenarios.
Test case 2 testInvalidDomain This method is used to test invalid mail id scenarios.
 

Write a createBoInstance method used to create the object for DomainValidationBO class


 

public class DomainValidationBO {


public String validateMailDomain(String mail) {
String domain = (mail.substring(mail.lastIndexOf('.') + 1));
if(domain.equals("com") || domain.equals("in") || domain.equals("org") || domain.equals("net"))
return "Valid email address";
return "Invalid email address";
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the email address");
String mail = br.readLine();
System.out.println(new DomainValidationBO().validateMailDomain(mail));
}
}
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class DomainValidationJUnit {
DomainValidationBO domainValidation;
@Before
public void createBoInstance() {
domainValidation = new DomainValidationBO();
}
@Test
public void testValidDomain() {
assertEquals("Valid email address", domainValidation.validateMailDomain("[email protected]"));
}
@Test
public void testInvalidDomain() {
assertEquals("Invalid email address", domainValidation.validateMailDomain("[email protected]"));
}
}
Arithmetic Exception
 

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).

CalculateBO class contains the following method.


 Method Method Description
double calculateCost(Integer cost, This method will get the cost and days, then calculate the
Integer days) cost per day return the value(cost per day = cost/days).
 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 CalculateJUnit and include the following test methods to test
the calculateCost method in the above code specifications.

 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.
 

Write a createBoInstance method used to create the object for CalculateBO class

import static org.junit.Assert.assertEquals;

import org.junit.Before;

import org.junit.Test;

public class CalculateJUnit {


@Before

public void createBoInstance() {

//fill the code

CalculateBO cbo=new CalculateBO();

//@SuppressWarnings("deprecation")

@Test

public void testCalculateCost() {

CalculateBO cbo=new CalculateBO();

assertEquals(20.0,cbo.calculateCost(100, 5),0.0);

//fill the code

@Test(expected=ArithmeticException.class)

public void testCalculateCostException() {

//fill the code

CalculateBO cbo=new CalculateBO();

cbo.calculateCost(10, 0);

//assertEquals(message,m);

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class Main {

public static void main(String[] args)throws IOException {


BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the cost of the item for n days");

Integer cost=Integer.parseInt(br.readLine());

System.out.println("Enter the value of n");

Integer n=Integer.parseInt(br.readLine());

double costPerDay;

try{

costPerDay = new CalculateBO().calculateCost(cost, n);

System.out.println("Cost per day of the item is "+costPerDay);

catch(ArithmeticException e){

System.out.println(e);

public class CalculateBO {

public double calculateCost(Integer cost, Integer days) throws ArithmeticException {

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.

Create following methods in DateFormatBO class,


 

Method Method Description


String This method accepts a String with "MM-dd-yyyy" format and
convertToFormat1(String converts it into a String of "EEE, MMM d, yy" format and returns the
value) value.
String This method accepts a String with "MM-dd-yyyy" format and
convertToFormat2(String converts it into a String of "dd.MM.yyyy" format and returns the
value) value.
String This method accepts a String with "MM-dd-yyyy" format and
convertToFormat3(String converts it into a String of "dd/MM/yyyy" format and returns the
value) value.
 

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 static org.junit.Assert.assertThat;

import org.hamcrest.CoreMatchers;

import org.junit.Test;

public class DateFormatJUnit {

@Test

public void createBoInstance() {

//fill the code

DateFormatBO dbo1=new DateFormatBO();

@Test

public void testConvertToFormat1() {

DateFormatBO dbo1=new DateFormatBO();

assertThat("Thu, Dec 12, 91",CoreMatchers.equalTo(dbo1.convertToFormat1("12-12-1991")));

// assertThat("12.12.1991",equalsTo(dbo1.convertToFormat1("12-12-1991")))

@Test
public void testConvertToFormat2() {

//fill the code

DateFormatBO dbo1=new DateFormatBO();

assertThat("12.12.1991",CoreMatchers.equalTo(dbo1.convertToFormat2("12-12-1991")));

@Test

public void testConvertToFormat3() {

//fill the code

DateFormatBO dbo1=new DateFormatBO();

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;

public class Main {

public static void main(String []args) throws IOException, ParseException {

BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the date to be formatted:(MM-dd-yyyy)");

String value = buff.readLine();

DateFormatBO boIns = new DateFormatBO();

System.out.println("Date Format with EEE, MMM d, yy : " + boIns.convertToFormat1(value));

System.out.println("Date Format with dd.MM.yyyy : " + boIns.convertToFormat2(value));

System.out.println("Date Format with dd dd/MM/yyyy : " + boIns.convertToFormat3(value));

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

public class DateFormatBO {


public String convertToFormat1(String value) {

SimpleDateFormat s1 = new SimpleDateFormat("MM-dd-yyyy");

SimpleDateFormat s2 = new SimpleDateFormat("EEE, MMM d, yy");

Date d1;

try { d1 = s1.parse(value); }

catch (ParseException e) { d1 = new Date(); }

return s2.format(d1);

public String convertToFormat2(String value) {

SimpleDateFormat s1 = new SimpleDateFormat("MM-dd-yyyy");

SimpleDateFormat s2 = new SimpleDateFormat("dd.MM.yyyy");

Date d1;

try { d1 = s1.parse(value); }

catch (ParseException e) { d1 = new Date(); }

return s2.format(d1);

public String convertToFormat3(String value) {

SimpleDateFormat s1 = new SimpleDateFormat("MM-dd-yyyy");

SimpleDateFormat s2 = new SimpleDateFormat("dd/MM/yyyy");

Date d1;

try { d1 = s1.parse(value); }

catch (ParseException e) { d1 = new Date(); }

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.

SquareBO class contains the following method.


Method Method Description
Integer findSquareValue(Integer This method will get an Integer as argument and return the
n) square of the 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.

Write a createBoInstance method used to create the object for SquareBO class

Create  a class named SquareChecker extending TypeSafeMatcher, override the appropriate


methods and display the custom error message as shown below if the computed square is wrong.
java.lang.AssertionError:  Expected: Expected was: <10> but:  was <11>

import org.junit.Before;

import static org.junit.Assert.*;

import static org.hamcrest.CoreMatchers.*;

import org.junit.Before;

import org.junit.Test;

public class SquareJUnit {

SquareBO sb;

@Before

public void createBoInstance() {


sb=new SquareBO();

@Test

public void testFindSquareValue() {

sb=new SquareBO;

assertThat(9,SquareChecker.checkSquare(9))

class SquareChecker extends TypeSafeMatcher

public static Matcher<Integer> checkSquare(final Integer value) {

return new TypeSafeMatcher<Integer>() {

@Override

public void describeTo(Description description) {

description.appendText(""+value+"");

protected boolean matchesSafely(Integer n) {

return (value==n);

public void describeMismatchSafely(final Integer n, final Description mismatchDescription) {

mismatchDescription.appendText("java.lang.AssertionError: Expected:"

+ "Expected was: <"+n+"> but: was <" + (n+1)+ ">");

};

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(new SquareBO().findSquareValue(n));

public class SquareBO {

public Integer findSquareValue(Integer 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 class ItemType with the following private attributes


Attribute Datatype
id Long
name String
deposit Double
costPerDay Double
Generate appropriate Getters and Setters
Generate default and parameterized constructors
The parameterized constructor should be in the following format ItemType(Long id, String name,
Double deposit, Double costPerDay)

Create a class ItemTypeDAO with the following methods


Method  Description
This function finds all records of the ItemType table.
public List<ItemType> getAllItemTypes()
It returns the ItemType objects in a List.

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;

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 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.

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
The parameterized constructor should be in the following format. User(Long id,String name, String
contactDetail, String username, String password)
 
Create a class UserDAO with the following methods
Method  Description
public List<User> getAllUsers() This function finds all records of the User table and returns the User objects in a L
 

Create a driver class Main to display a List of objects in the following format.


NOTE : Use System.out.format("%-5s %-5s %-15s %-10s %s\n","Id","Name","Contact
Detail","Username","Password") to display user details.

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;

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
 
Note: 

while retrieving data from table sort by id.


Use PreparedStatement for queries.
System.out.format("%-5s %-10s %-15s %-10s %s\n","Id","Name","Contact
Detail","Username","Password");
 
 
Sample Input and Output:
[All text in bold corresponds to the input and rest corresponds to the output]
 
Enter the user detail in CSV format
Antony,9873216540,Antonie,an@987
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
6     Antony     9873216540      Antonie    an@987

Insert with User identification


 

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 class User with the following private attributes,


Attributes Datatype
id Long
name String
mobileNumber String
username String
password String
Add appropriate getter/setter, default and parameterized constructor.
The parameterized constructor format User(Long id, String name, String mobileNumber, String
username, String password)
 
Create a class Hall with the following private attributes,
Attributes Datatype
id Long
name String
contactNumber String
costPerDay Double
owner User
Add appropriate getter/setter, default and parameterized constructor.
The parameterized constructor format Hall(String name, String contactNumber, Double
costPerDay,User owner)
Override toString() and print the details in the tabular form.
    
Create a class UserDAO with the following methods,
Method Description
This method gets the user details from the user table whose username is passed as
User getUser(String username) It creates a user object from those details and returns the object.
If the user with that username not available, it returns null.
 

Create a class HallDAO with the following methods,


Method Description
void saveHall(Hall hall) This method gets the hall object as an argument and inserts it into the hall table.
List<Hall> getAllHall() Returns the list of halls from database.
 

Create a class DbConnection with the following static methods,


Method Description
This method uses "mysql.properties" file as a resource file and
static Connection getConnection()
gets a connection object for the MySQL database and returns the connection ob
 

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;
 

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_id NUMBER(19) NOT NULL,
foreign key(owner_id) references "user"(id),
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
 

Download the oracle jar file in the below link.


Oracle jar

Input and Output format:


The first line is the hall details in the CSV format(name, contact, cost per day).
The next line of input is the username.
If the username doesn’t exist, then display Username seems to be wrong!! Enter the correct
username:
Otherwise, display the hall details of the corresponding owner.
Refer to Sample Input and Output for further details and format of the output.
Use "%-15s%-15s%-15s%-15s" while displaying hall objects in tabular form.

[All Texts in bold corresponds to the input and rest are output]
Sample Input and Output 1:

Enter the details of hall in csv format:


Ball Room,1234567890,15000
Enter the username:
jim
Username seems to be wrong!! Enter the correct username:
johny
The hall details are:
Name           Mobile         Cost           Owner          
Party hall     9874653201     5000.0         John           
Dining Hall    9876541230     3000.0         Peter          
Disco Hall     9871234560     8000.0         Adam           
Conference Hall7891236540     7500.0         Linda          
Meeting Hall   8974102365     9000.0         Tony           
Ball Room      1234567890     15000.0        John        
 

Update User Detail


      
There was a small error in the user enrollment application. The mobile numbers of the users got
interchanged unexpectedly. Hence create a console application to update the mobile number of the
user by obtaining input from the console. If the username is present in the User table, get the
contactDetail and update it. Otherwise, Display "No such user is present".

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)
 

Create a class UserDAO with the following methods


Method  Description
public List<User> getAllUsers() This function finds all records of the User table and ret
This function accepts username as an argument and fin
public User findUserByUsername(String username)
returns the User object.
public void updateUser(User user) This function accepts the User object as an argument an
 

Create a driver class Main to display a list of objects in the following format.

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

Input and Output format:


Display all the user details from the user table as the specified format.
Use System.out.format("%-5s %-5s %-15s %-10s %s\n","Id","Name","Contact
Detail","Username","Password") to display user details.
Then the input is the username of the user.
Display the details of the corresponding user. If the username is not in the table, then display “No
such user is present”
Then the input is a mobile number to be updated for the particular user.
 
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input and Output 1:
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
Enter the username:
johny
Id Name Contact Detail Username Password
1 John 9876543210 johny 12345
Enter the mobile number to be updated:
9477885140
Id Name Contact Detail Username Password
1 John 9477885140 johny 12345
 

Sample Input and Output 2:


 

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
Enter the username:
admin
No such user is present
Delete based on condition
Write a program to get the username and delete the user from the user table in the database.

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 Data type
id Long
name String
mobileNumber String
username String
password String
Add appropriate getter/setter, default and parameterized constructor.
Override toString() and print the details in the tabular form.

Create a class UserDAO with the following methods,


Method Description
this method gets the user details from the user table and
List<User> getAllUser() create user objects using the details and
add the user objects in a list and returns the list.
this method gets username as the argument and deletes the use
Boolean deleteUser(String username) with the given username from the table and returns true.
If the user with the given username is not available it returns fa

Create a class DbConnection with the following static methods,


Method Description
static Connection this method uses "oracle.properties" file as a resource file and gets connection ob
getConnection() and return the connection object.
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;

The class DbConnection use the following resource bundle access,


        ResourceBundle rb = ResourceBundle.getBundle("oracle");
        String url = rb.getString("db.url");
        String username = rb.getString("db.username");
        String password = rb.getString("db.password");

And the oracle.properties file has following data,


       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

Input and Output format:


Display the user details from the user table as the specified format.
Use "%-15s%-15s%-15s%-15s" while displaying hall objects in tabular form.
Then the input is the username of the user to be deleted from the user table.
Print "User not found" if the method deleteUser returns false, else print "User deleted successfully"
in main.
Then display the user details after deletion from the user table.
Refer to sample input and output for further details and format of the output.

[All Texts in bold corresponds to the input and rest are output]
Sample Input and Output 1:

Name           Mobile         Username       Password       


John           9876543210     johny          12345          
Peter          9873216540     peterey        pet123         
Adam           9871236504     adamanta       ad@123         
Linda          8794561320     lindahere      abcd           
Tony           7894561230     tonii          abc123         
Enter the username to be deleted:
Jim
User not found
Name           Mobile         Username       Password       
John           9876543210     johny          12345          
Peter          9873216540     peterey        pet123         
Adam           9871236504     adamanta       ad@123         
Linda          8794561320     lindahere      abcd           
Tony           7894561230     tonii          abc123         

Sample Input and Output 2:

Name           Mobile         Username       Password       


John           9876543210     johny          12345          
Peter          9873216540     peterey        pet123         
Adam           9871236504     adamanta       ad@123         
Linda          8794561320     lindahere      abcd           
Tony           7894561230     tonii          abc123         
Enter the username to be deleted:
lindahere
User deleted successfully
Name           Mobile         Username       Password       
John           9876543210     johny          12345          
Peter          9873216540     peterey        pet123         
Adam           9871236504     adamanta       ad@123         
Tony           7894561230     tonii          abc123         
List of Stalls 
 
Now we are gonna get the details of a table with the id of another table. There are many exhibitions
in our application and each exhibition has booked many stalls. So we want a consolidated record of it
from our table. So write a program to get all the stalls booked for the given exhibition.

Create a class Exhibition with the following private attributes,


Attributes Data type
id Long
name String
stallList List<Stall>
Add appropriate getter/setter, default and parameterized constructor.

Create a class Stall with the following private attributes,


Attributes Data type
 id Long
name String
detail String
owner String
exhibition Exhibition
Add appropriate getter/setter, default and parameterized constructor.

Create a class ExhibitionDAO with following methods,


Method Description
This method takes exhibition name as an argument,
retrieves the exhibition detail from the exhibition table and
Exhibition getExhibition(String name)
get all the stalls corresponding to the exhibition and
stores it in the exhibition object and returns the object.
 

Create a class DbConnection with the following static methods,


Method Description
this method uses "oracle.properties" file as a resource file and
static Connection getConnection()
gets connection object for the MySQL database and returns the connec
 

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;
 

The class DbConnection use the following resource bundle access,


        ResourceBundle rb = ResourceBundle.getBundle("oracle");
        String url = rb.getString("db.url");
        String username = rb.getString("db.username");
        String password = rb.getString("db.password");

And the oracle.properties file has following data,


       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

Input and Output format:


The input is the exhibition name.
If the entered exhibition name is not in the table, then display “Enter the correct exhibition name:”
Otherwise, display the stall details corresponding to the given exhibition.
Use "%-20s%-20s%-15s" as formatting to display the stall list in tabular format.
 Refer to sample input/output for further details and format of the output.

[All Texts in bold corresponds to the input and rest are output]
Sample Input and Output 1:

Enter the exhibition name:


Exhibition 1
Stall Name          Detail              Owner name     
Chocolate stall     chocolate shop      John           
HiFi electronics    mobile shop         Adam           
Snack seeker        shop for snacks     Mark           
Display Items by Category
 
The Sample data for the Items and ItemTypes are updated by the organizers. There is a need for a
feature that would fetch the Items that belong to a particular ItemType from the database and display
it to the users. Thus compiled a list of items would be used for advertisements of the exhibitions.
Hence write a console application to display the specified information.

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)
 

Create a class ItemTypeDAO with the following methods


Method  Description
This function finds all records of the ItemType table and
public List<ItemType> getAllItemTypes()
returns the ItemType objects in a List.
 
Create a class ItemDAO with the following methods
Method  Description
This function accepts category as an argumen
public List<Item> findItemsByCategory(String category) finds the records that match the given categor
returns the Item objects in a List.
 
Create a driver class Main to display a List of objects in the following format.

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;
 

CREATE  TABLE item(


id number(19) NOT NULL,
name VARCHAR2(255) NOT NULL,
vendor VARCHAR2(255) NOT NULL,
type_id number(19) NULL,
foreign key(type_id) references item_type(id),
PRIMARY KEY (id));
CREATE SEQUENCE item_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
 
Output format:
Use System.out.format("%-5s %-15s %-12s %s\n","ID","Name","Deposit","Cost per day") to display
ItemType details.
Use System.out.format("%-5s %-15s %-12s %s\n","ID","Name","Item Type","Vendor") to display
Item details.
 
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input and Output 1:
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
Enter the category:
Food
ID Name Item Type  vendor
1 Chocolate Food Foodies Court
2 Lollypop Food Foodies Court
 

Sample Input and Output 2:


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
Enter the category:
Mobiles
No such category is present
 
Update timings
The event organizers had requested a feature for updating the Event details if any changes occur in
the feature. Hence as a prototype, write a program for a console application that could prompt for
the event timings and updates the respective timing changes in the database.   
 
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 Event with the following private attributes.
Attributes Datatype
id Long
name String
detail String
startDate java.util.date
endDate java.util.date
organizer String
Generate getters and setters.
Generate Default and two parameterized constructors.
Format for Parameterized constructors are
Event(String name, String detail, Date startDate, Date endDate,String organizer)
Event(Long id, String name, String detail, Date startDate,Date endDate, String organizer)
 

Create a class called EventDAO with following methods


Method  Description
This method accepts an id of Event as the argument and
public Event getEventById(Long id) fetches the Event detail with the corresponding id.
Then returns the Event details in an Event object.
public void updateEvent(Event e) This method accepts the Event object as an argument and
updates the Event details present in the object to the row that has the E
as that of the id present in the object
This method retrieves all the Event details from the event table,
public List<Event> getAllEvents()
stores the details in list of Event objects, and returns the list.

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;

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

Input and Output format:


While retrieving data from table sort by id.
System.out.format ("%-5s %-10s %-15s %-20s %-20s %s\n","Id","Event name","Detail","Start
date","End date","Organizer");
Then the input is event id to update the particular event details. If the event id is not present in the
table then display “Id not found” and terminate the process.
Then the input is startdate and end date of the events to be updated.
Then display all the event details after updation.
 
 
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input/Output:
 
Id    Event name Detail          Start date           End date             Organizer
1     Event 1    event 1         2018-01-01 12:00:00  2018-02-01 12:00:00  John
2     Event 2    event 2         2018-02-15 18:00:00  2018-03-20 15:00:00  Peter
3     Event 3    event 3         2018-03-01 15:00:00  2018-04-01 00:00:00  Mark
4     Event 4    event 4         2018-03-01 12:00:00  2018-03-10 18:00:00  Stephen
5     Event 5    event 5         2018-11-11 00:00:00  2018-12-01 12:00:00  Charles
Enter the id of the event to be updated
1
Enter the start and end date
2018-01-02 12:00:00
2018-01-03 12:00:00
Id    Event name Detail          Start date           End date             Organizer
1     Event 1    event 1         2018-01-02 12:00:00  2018-01-03 12:00:00  John
2     Event 2    event 2         2018-02-15 18:00:00  2018-03-20 15:00:00  Peter
3     Event 3    event 3         2018-03-01 15:00:00  2018-04-01 00:00:00  Mark
4     Event 4    event 4         2018-03-01 12:00:00  2018-03-10 18:00:00  Stephen
5     Event 5    event 5         2018-11-11 00:00:00  2018-12-01 12:00:00  Charles
Hall insert
When the number of rows to insert into the table increases, we can opt for multiple insert using batch
queries. Hence instead of adding single row at a time, we can insert multiple rows at the same time which
increases performance considerably. To get acquainted in batch query, obtain multiple input from the user
and use Batch query for inserting mulitple hall details in this exercise.
 

Create a class called Hall with the following private attributes


 
Attributes Datatype
id Long
name String
contactDetail String
costPerDay Double
owner String

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

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 text in bold corresponds to the input and rest corresponds to the output]
Sample Input/Output:
 
Enter the number of hall details:
2
Enter hall 1 detail in CSV format
HH Hall,9985471320,15000,Ram
Enter hall 2 detail in CSV format
RR Hall,9876543210,1000,Mahesh
Id    Hall name       Contact detail  Cost per day    Organizer
7     RR Hall         9876543210      1000.0          Mahesh
2     Dining Hall     9876541230      3000.0          Peter
1     Party hall      9874653201      5000.0          John
4     Conference Hall 7891236540      7500.0          Linda
3     Disco Hall      9871234560      8000.0          Adam
5     Meeting Hall    8974102365      9000.0          Tony
6     HH Hall         9985471320      15000.0         Ram
 

File handling introduction


File handling is an important technique that you need to accustom to it. File reading and writing are
types of handling. Let's practice file reading for now. There is a Class called FileReader that will help
us with file reading. You'll be provided with a file that contains the data in CSV format. Using
FileReader, read the file and parse the data contained in it to below specified format.
Provided "input.csv" which have User details. Read all the user information stored in CSV format and
create a user object by parsing the line. Add all the user objects to the ArrayList. At last, display the
user list.

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 following private attributes


Attributes Datatype
name String
email String
username String
password String

Include getters and setters.


Create a default constructor and parameterized constructor.
Format for the parameterized constructor is User(String name, String email, String username, String
password)

Create UserBO class with following methods


Method  Description
This method accepts the BufferedReader object as input
public List<User> readFromFile(BufferedReader br)
in the file to User objects and adds them to a list. Finally
This method accepts a list of User objects and displays th
public void display(List<User> list)
Use "%-15s %-20s %-15s %s\n" to print the details.

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.

Note : Use BufferedReader br=new BufferedReader(new FileReader("input.csv")) for file reading.

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 Input: (input.csv)


 

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() {
}

public User(String name, String email, String username, String password) {


super();
this.name = name;
this.email = email;
this.username = username;
this.password = password;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getUsername() {


return username;
}

public void setUsername(String username) {


this.username = username;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

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 {

public static void main(String[] args) throws IOException {


BufferedReader br = new BufferedReader(new FileReader("input.csv"));
UserBO userBO = new UserBO();
List<User> userList = userBO.readFromFile(br);
if (userList.isEmpty()) {
System.out.println("The list is empty");
} else {
String name="Name", email="Email", username="Username", password="Password" ;
System.out.printf("%-15s %-20s %-15s %s\n", name, email, username, password);
userBO.display(userList);
}
}
}

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();

} catch (IOException ex) {


ex.printStackTrace();
}
return userList;
}

public void display(List<User> list) {


for (User user : list) {
System.out.printf("%-15s %-20s %-15s %s\n", user.getName(), user.getEmail(), user.getUsername(), user.getPassword());
}
}
}

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 class User with the following attributes, 


Attribute Data type
name String
mobileNumber String
username String
password String
 
Create a class UserBO with the following methods,
Method Description
This method gets a list of the user as
public static void writeFile(ArrayList<User> userList, BufferedWriter bw)
writes all the user details in the list i

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]

Enter the number of users:


3
Enter the details of user :1
Jane,1234,jane,jane
Enter the details of user :2
John,5678,john,john
Enter the details of user :3
Jill,1357,jill,jill
 

Sample Output: (output.csv)

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

public static void main(String[] args) throws Exception {


ArrayList<User> userList = new ArrayList<>();
Scanner s = new Scanner(System.in);
System.out.println("Enter No of User");
int no = s.nextInt();
s.nextLine();
User user = null;

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


System.out.println("Enter the details of user:" + (i + 1));
String input = s.nextLine();
String[] elements = input.split(",");
user = new User();
user.setName(elements[0]);
user.setMobileNumber(elements[1]);
user.setUsername(elements[2]);
user.setPassword(elements[3]);

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;

public class UserBO {

public static void writeFile(ArrayList<User>userList, BufferedWriter bw) throws Exception {

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();
}
}

public class User {


String name;
String mobileNumber;
String username;
String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

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 a class Hall with the following private attributes,


Attributes Datatype
name String
contact String
costPerDay Double
owner String

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)

Read a list of halls and write the hall details to the hall.csv file.

Create a driver class Main to test the above classes.

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.

[All text in bold corresponds to input and rest corresponds to output]


Sample Input:
Enter the number of halls:
3
Party hall,9876543210,4000.0,Jarviz
Disco hall,9876543201,5000.0,Starc
Dining hall,9873216540,3000.0,Chris

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;

public class Hall {


private String name;
private String contact;
private double costPerDay;
private String owner;

public Hall(String name, String contact, double costPerDay, String owner) {


super();
this.name = name;
this.contact = contact;
this.costPerDay = costPerDay;
this.owner = owner;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getContact() {


return contact;
}

public void setContact(String contact) {


this.contact = contact;
}

public double getCostPerDay() {


return costPerDay;
}

public void setCostPerDay(double costPerDay) {


this.costPerDay = costPerDay;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
/**
* n this method, get the list of hall details as parameters. write the hall
* details to hall.csv file as comma-separated in the given order,
* (name,contact,costPerDay,owner)
*
* @param halls
* @throws IOException
*/
public static void writeHallDetails(List<Hall> halls) throws IOException {
FileWriter fi = new FileWriter("hall.csv", false);
for (Hall s : halls) {
fi.write(s.getName() + "," + s.getContact() + "," + s.getCostPerDay() + "," + s.getOwner());
fi.write("\n");
}
fi.close();
}
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

public static void main(String[] args) throws IOException {


List<Hall> hallsList = new ArrayList<Hall>();
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of halls:");
int no = s.nextInt();
s.nextLine();
Hall hall = null;
for (int i = 0; i < no; i++) {
String input = s.nextLine();
String[] elements = input.split(",");
hall = new Hall(elements[0], elements[1], Double.parseDouble(elements[2]), elements[3]);
hallsList.add(hall);
hall = null;
}

Hall.writeHallDetails(hallsList);
}

Fixed Length format


 
There are many types of files available, each has its own advantages and disadvantages of using. In
this problem, we are gonna use Fixed Length Format files. In these files, each field has a fixed length.
If a variable of the field is shorter than its size, it is filled with space so that all variables of a particular
field is of the same size. By this, we can get all the variables of the field
using substring() and trim() methods.

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.

Create a class Event with the following private attributes,


Attribute Data type
name String
detail String
type String
organiser String
attendeesCont Integer
projectedExpense Double
 
Include appropriate getter/setter, default constructor and parameterized constructor.

Override toString() and print the details in the tabular form.

Create a class EventBO with the following public static methods,


Method Description
ArrayList<Event>
this method reads the lines from the file and stores it as ArrayList of Event Object
readFile(BufferedReader 
It returns the ArrayList
br)
ArrayList<Event>
eventsByPerson(ArrayList this method takes the list of events and organizer name
<Event> eventList, It returns a list of events that are organized by that organizer.
String organiser)
 
Create a driver class Main and use the main method to get the file and details from the user.

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.

Sample Input file: (input.csv)


[All Texts in bold corresponds to the input and rest are output]
Sample Input and Output 1:

Enter the name of the person whose events to be shown:


Jane
Name           Detail              Type           Attendees CountProjected Expense
Magic Show     Magicwithoutlogicstageshow      1000           10000.0        
Marathon       Run for a cause    sportsmeet     500            25000.0        
Do you want to continue?(y/n)
y
Enter the name of the person whose events to be shown:
Jack
Name           Detail              Type           Attendees CountProjected Expense
Book Fair      @5% discount        exhibition     5000           15000.0        
Do you want to continue?(y/n)
y
Enter the name of the person whose events to be shown:
Jim
The given person has no upcoming events
Do you want to continue?(y/n)
n
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws Exception {
//write your code here
Scanner sc = new Scanner(System.in);
String ch = null;
BufferedReader br = new BufferedReader(new FileReader("input.csv"));
ArrayList<Event> e = EventBO.readFile(br);
do {
System.out.println("Enter the name of the person whose events to be shown:");
String s = sc.nextLine();
ArrayList<Event> e1 = EventBO.eventsByPerson(e, s);
if(e1.isEmpty()) {
System.out.println("The given person has no upcoming events");
}else {
String name ="Name",detail="Detail",type="Type",attendees="Attendees
Count",cpe="Projected Expense";
System.out.printf("%-15s%-20s%-15s%-15s%-15s\n" ,name,detail,type,attendees,cpe);
for(int i=0;i<e1.size();i++) {
System.out.print(e1.get(i).toString());
}
}

System.out.println("Do you want to continue?(y/n)");


ch = sc.nextLine();
}while(ch.equals("y"));

}
}

public class Event {


//write your code here
String name;
String detail;
String type;
String organiser;
int attendeesCont;
double projectedExpense;

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;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getDetail() {


return detail;
}

public void setDetail(String detail) {


this.detail = detail;
}

public String getType() {


return type;
}

public void setType(String type) {


this.type = type;
}

public String getOrganiser() {


return organiser;
}

public void setOrganiser(String organiser) {


this.organiser = organiser;
}

public int getAttendeesCont() {


return attendeesCont;
}

public void setAttendeesCont(int attendeesCont) {


this.attendeesCont = attendeesCont;
}
public double getProjectedExpense() {
return projectedExpense;
}

public void setProjectedExpense(double projectedExpense) {


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;

public class EventBO {

public static ArrayList<Event> readFile(BufferedReader br) throws Exception {


ArrayList<Event> e = new ArrayList<Event>();
Event event;
String line;
while ((line = br.readLine()) != null) {
String name = line.substring(0, 19).trim();
String detail = line.substring(19, 39).trim();
String type = line.substring(39, 51).trim();
String organiser = line.substring(51, 61).trim();
String attendeesCont = line.substring(61, 67).trim();
String projectedExpense = line.substring(67, 74).trim();
event = new Event(name, detail, type, organiser, Integer.parseInt(attendeesCont),
Double.parseDouble(projectedExpense));
e.add(event);
}
br.close();
return e;
//write your code here
}

public static ArrayList<Event> eventsByPerson(ArrayList<Event> eventList,String organiser) {


ArrayList<Event> e = new ArrayList<Event>();
for(int i=0;i<eventList.size();i++) {
if(eventList.get(i).getOrganiser().equals(organiser)) {
e.add(eventList.get(i));
}
}
return e;
//write your code here
}
}

ItemType details in a file


 

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 an ItemTypeBO class with the following methods


Method  Description
This method accepts the BufferedReader object as i
public List<ItemType> readFromFile(BufferedReader br)
in the file to ItemType objects and adds them to a li
This method accepts a list of ItemType objects and
public List<ItemType> depositList(List<ItemType> list)
deposit amount greater than 2000
This method accepts a list of ItemType objects and
public void display(List<ItemType> list)
Refer to the sample Output for the formatting specif

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 :

Item type       Deposit         Cost per day


Electrical      2100.0          500.0
Construction    5000.0          1000.0
 import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;
import java.util.List;

public class Main {

public static void main(String[] args) throws IOException{

BufferedReader br = new BufferedReader(new FileReader("input.txt"));

ItemTypeBO it = new ItemTypeBO();

List<ItemType> itList = it.readFromFile(br);

List<ItemType> itList1 = it.depositList(itList);

if(itList1.isEmpty()) {

System.out.println("No item type has deposit more than 2000");

}else {

String type ="Item type",dep="Deposit",cost="Cost per day";

System.out.printf("%-15s %-15s %s\n" ,type,dep,cost);

it.display(itList1);

public class ItemType {


//Your code here
String name;
double deposit;
double costPerDay;

public ItemType() {
super();
}

public ItemType(String name, double deposit, double costPerDay) {


super();
this.name = name;
this.deposit = deposit;
this.costPerDay = costPerDay;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getDeposit() {


return deposit;
}

public void setDeposit(double deposit) {


this.deposit = deposit;
}

public double getCostPerDay() {


return costPerDay;
}

public void setCostPerDay(double costPerDay) {


this.costPerDay = costPerDay;
}

Electronics 1000 200


Chemicals 500 100
Electrical 2100 500
Construction 5000 1000

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ItemTypeBO {


//Your code here
public List<ItemType> readFromFile(BufferedReader br){
List<ItemType> itList = new ArrayList<ItemType>();
ItemType it;
try {
String line;
while ((line = br.readLine()) != null) {
String sp[] = line.split("\\s+");
it = new ItemType(sp[0], Double.parseDouble(sp[1]), Double.parseDouble(sp[2]));
itList.add(it);
}
br.close();

} catch (IOException ex) {


ex.printStackTrace();
}
return itList;

public List<ItemType> depositList(List<ItemType> list){


List<ItemType> itList = new ArrayList<ItemType>();
for(int i =0;i<list.size();i++) {
if(list.get(i).getDeposit()>2000) {
itList.add(list.get(i));
}
}
return itList;

public void display(List<ItemType> 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".

Sample Input: (input.txt)

Sample Output: (output.txt)


Item Count
We have got ourselves into a situation here. We have the item list in a fixed-length format file. But
for manipulation and record maintenance we want it as objects. So we need a program that can read
the file and create the item with the itemtype that we already have. We want the list in the file in a
consolidated form that gives only the itemtype and count of items with that itemtype. So write a
program to do the requirement and hard code the itemtype list.

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.

Create a class Item with the following attributes,


Attribute Data type
number String
itemType ItemType
vendor String

Create a class ItemType with the following attributes,


Attribute Data type
name String
deposit Double
costPerDay Double

Include appropriate getter/setter, default constructor and parameterized constructor. Prefill ItemType


with some data.

Create a class with ItemBO with the following public static methods,


Method Description
This method
ArrayList<Item> readFile(BufferedReader br,ArrayList<ItemType> typeList) then reads th
returns the l
This method
return a map
TreeMap<String,Integer> listItem(ArrayList<Item> itemList,ArrayList<ItemType> itemTypeList)
items
which belon
 
Create a driver class Main and use the main method to get the file and details from the user.

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:

The item types along with count of each:


Decorations--2
Electronics--3
Furniture--2
 
Item Details
 
File reading and writing skills are indispensable for a programmer. Your skills will increase in file
handling as you progress through this module and learn about the essence of file handling. In this
example, read the given file and process the information present in it. The input consists of item
details, you have to display the details in tabular format.

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 Item with the following private attributes


Attributes Datatype
itemNumber Integer
vendor String
itemType ItemType
Include appropriate getters and setters
Create default constructor and a parameterized constructor with arguments in order Item(Integer
itemNumber, String vendor,ItemType itemType).

Create a class ItemType with following private attributes


Attributes Datatype
itemTypeName String
cost Double
Include appropriate getters and setters
Create a default constructor and a parameterized constructor with arguments in
order ItemType(String itemTypeName, Double cost).

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.

Create a driver class named Main to test the above class.


 
Input Format:
It reads details from "input.csv"
Refer to sample input for formatting specifications.

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 Input : (input.csv)


input.csv
1,Martin,Leather,2000
15,Louis,Mud,1300.50
23,Jaques kallis,Electronics,100
38,McCullum,Wood,3000.4

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

IO - Simple File Write


 
Write a Java program to record the airport details into the file. Get the airport details name, cityName
and countryCode from the user and write that information in a comma-separated format in a file
(CSV).
 
Below is the format of the output file.
<name>,<cityName>,<countryCode>
eg: Cochin International Airport,Cochin,IN
 
Create a main class "Main.java"
 
Input and Output Format:
Get the airport details name, cityName and country code from the user.
Print the airport details in the output file airport.csv
 
Sample Input :
[All text in bold corresponds to input and the rest corresponds to output]
 
Enter the name of the airport
Cochin International Airport
Enter the city name
Cochin
Enter the country code
IN

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
 

Create an interface named MaintenanceCharge with the following method


Method Description
float calculateMaintancecharge(float no of This method is used to calculate the maintenance
years) charge

Create a class named CurrentAccount which implements MaintenanceCharge interface


Create a class named SavingsAccount which implements MaintenanceCharge interface
Create an another class named Main with main( ) method to test the above classes.
In Savings Account the maintenance amount will be 2*m*n+50.
In Current Account, the maintenance amount will be m*n+200.
where m is the maintenance charge per year and n is the number of years.
Maintenance charge Rs.50  for saving account and 100 for the Current account.
 

Note: Refere sample input and output for the specifications.


All text in bold corresponds to the input and remaining text corresponds to output.
Sample input and output 1:
1.Current Account
2.Savings Account
1
Name
SB
Account Number
12345
Account Balance
5000
Enter the Start Date(yyyy-mm-dd)
2013-04-22
Enter the Years
2
Maintenance Charge For Current Account 400.00
Sample input and output 2:
1.Current Account
2.Savings Account
2
Name
SB
Account Number
54321
Account Balance
3000
Enter the Start Date(yyyy-mm-dd)
2014-04-12
Enter the Years
5
Maintenance Charge For Savings Account 550.00

public class CurrentAccount implements MaintainanceCharge {

@Override

public float calculateMaintanceCharge(int noOfYear) {

return (100 * noOfYear) + 200;

class Account {

String name;

String accountNumber;

double balance;

String startDate;

public Account(String name, String accountNumber, double balance, String startDate) {

super();

this.name = name;

this.accountNumber = accountNumber;

this.balance = balance;
this.startDate = startDate;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getAccountNumber() {

return accountNumber;

public void setAccountNumber(String accountNumber) {

this.accountNumber = accountNumber;

public double getBalance() {

return balance;

public void setBalance(double balance) {

this.balance = balance;

public String getStartDate() {

return startDate;

public void setStartDate(String startDate) {


this.startDate = startDate;

public interface MaintainanceCharge{

float calculateMaintanceCharge(int noOfYear);

class SavingsAccount implements MaintainanceCharge {

@Override

public float calculateMaintanceCharge(int noOfYear) {

return (2 * 50 * noOfYear) + 50;

import java.text.DecimalFormat;

import java.util.*;

public class Main {

public static void main(String args[]) {

Scanner s = new Scanner(System.in);

String name, sdate, account;

double accountBalance;

int years;

System.out.println("1.Current Account");

System.out.println("2.Savings Account");

int n = s.nextInt();

DecimalFormat df = new DecimalFormat("0.00");

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();

System.out.println("Enter the Start Date(yyyy-mm-dd)");

sdate = s.nextLine();

System.out.println("Enter the Years");

years = s.nextInt();

Account a = new Account(name, account, accountBalance, sdate);

CurrentAccount c = new CurrentAccount();

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();

System.out.println("Enter the Start Date(yyyy-mm-dd)");

sdate = s.nextLine();

System.out.println("Enter the Years");

years = s.nextInt();

Account a1 = new Account(name, account, accountBalance, sdate);

SavingsAccount sa = new SavingsAccount();

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.

Create an interface Stall  with the following method


Method Description
void display() abstract method.

Create a class GoldStall which implements Stall interface with the following private attributes


Attribute Datatype
stallName String
cost Integer
ownerName String
tvSet Integer
Create default constructor and a parameterized constructor with arguments in order GoldStall(String
stallName, Integer cost, String ownerName, Integer tvSet).
Include appropriate getters and setters.

Include the following method in the class GoldStall


Method Description
void display() To display the stall name, cost of the stall, owner name and the number of tv sets.
Create a class PremiumStall which implements Stall interface with following private attributes
Attribute Datatype
stallName String
cost Integer
ownerName String
projector Integer
Create default constructor and a parameterized constructor with arguments in
order PremiumStall(String stallName, Integer cost, String ownerName, Integer projector).
Include appropriate getters and setters.

Include the following method in the class PremiumStall.


Method Description
void display() To display the stall name, cost of the stall, owner name and the number of projectors.

Create a class ExecutiveStall which implements Stall interface with following private attributes


Attribute Datatype
stallName String
cost Integer
ownerName String
screen Integer
Create default constructor and a parameterized constructor with arguments in
order ExecutiveStall(String stallName, Integer cost, String ownerName, Integer screen).
Include appropriate getters and setters.

Include the following method in the class ExecutiveStall.


Method Description
void display() To display the stall name, cost of the stall, owner name and the number of screens.

Create a driver class named Main to test the above class.

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

Sample Input and Output 1:

Choose Stall Type


1)Gold Stall
2)Premium Stall
3)Executive Stall
1
Enter Stall details in comma separated(Stall Name,Stall Cost,Owner Name,Number of TV sets)
The Mechanic,120000,Johnson,10
Stall Name:The Mechanic
Cost:120000.Rs
Owner Name:Johnson
Number of TV sets:10

Sample Input and Output 2:

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

Sample Input Output 3:

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

Sample Input Output 4:

ChooseStall Type
1)Gold Stall
2)Premium Stall
3)Executive Stall
4
Invalid Stall Type

public class PremiumStall implements Stall {


private String stallName;
private Integer cost;
private String ownerName;
private Integer projector;

public PremiumStall(String stallName, Integer cost, String ownerName, Integer projector) {


this.stallName = stallName;
this.cost = cost;
this.ownerName = ownerName;
this.projector = projector;
}

public PremiumStall() {

public void display() {


System.out.println("Stall Name:" + stallName + "\nCost:" + cost + ".Rs\nOwner Name:"
+ ownerName
+ "\nNumber of Projectors:" + projector);
}

public String getStallName() {


return stallName;
}

public void setStallName(String stallName) {


this.stallName = stallName;
}

public Integer getCost() {


return cost;
}

public void setCost(Integer cost) {


this.cost = cost;
}

public String getOwnerName() {


return ownerName;
}

public void setOwnerName(String ownerName) {


this.ownerName = ownerName;
}

public Integer getProjector() {


return projector;
}
public void setProjector(Integer projector) {
this.projector = projector;
}
}
public class ExecutiveStall implements Stall {

private String stallName;


private Integer cost;
private String ownerName;
private Integer screen;

public ExecutiveStall(String stallName, Integer cost, String ownerName, Integer screen) {


this.stallName = stallName;
this.cost = cost;
this.ownerName = ownerName;
this.screen = screen;
}

public ExecutiveStall() {

public void display() {


System.out.println("Stall Name:" + stallName + "\nCost:" + cost + ".Rs\nOwner Name:"
+ ownerName
+ "\nNumber of Screens:" + screen);
}

public String getStallName() {


return stallName;
}

public void setStallName(String stallName) {


this.stallName = stallName;
}

public Integer getCost() {


return cost;
}

public void setCost(Integer cost) {


this.cost = cost;
}

public String getOwnerName() {


return ownerName;
}

public void setOwnerName(String ownerName) {


this.ownerName = ownerName;
}

public Integer getScreen() {


return screen;
}

public void setScreen(Integer screen) {


this.screen = screen;
}
}
public interface Stall {
void display();

}
import java.util.Scanner;

public class Main {


public static void main(String[] args) throws Exception {

// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String[] arr = new String[3];


String stallDetails = "";

System.out.println("Choose Stall Type\n1)Gold Stall\n2)Premium Stall\n3)Executive


Stall");

Scanner scan = new Scanner(System.in);


int n = scan.nextInt();

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(",");

int cost = Integer.parseInt(arr[1]);


int num = Integer.parseInt(arr[3]);

GoldStall gStall = new GoldStall(arr[0], cost, arr[2], num);


gStall.display();

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]);

PremiumStall pStall = new PremiumStall(arr[0], cost, arr[2], num);


pStall.display();
break;
case 3:
scan.nextLine();
System.out.println(
"Enter Stall details in comma separated(Stall Name,Stall
Cost,Owner Name,Number of Screens)");

stallDetails = scan.nextLine();

arr = stallDetails.split(",");
cost = Integer.parseInt(arr[1]);
num = Integer.parseInt(arr[3]);

ExecutiveStall eStall = new ExecutiveStall(arr[0], cost, arr[2], num);


eStall.display();
break;
default:
System.out.println("Invalid Stall Type");

}
}
public class GoldStall implements Stall {

private String stallName;


private Integer cost;
private String ownerName;
private Integer tvSet;

public GoldStall(String stallName, Integer cost, String ownerName, Integer tvSet) {


this.stallName = stallName;
this.cost = cost;
this.ownerName = ownerName;
this.tvSet = tvSet;
}
public GoldStall() {

public void display() {


System.out.println("Stall Name:" + stallName + "\nCost:" + cost + ".Rs\nOwner Name:"
+ ownerName
+ "\nNumber of TV sets:" + tvSet);
}

public String getStallName() {


return stallName;
}

public void setStallName(String stallName) {


this.stallName = stallName;
}

public Integer getCost() {


return cost;
}

public void setCost(Integer cost) {


this.cost = cost;
}

public String getOwnerName() {


return ownerName;
}

public void setOwnerName(String ownerName) {


this.ownerName = ownerName;
}

public Integer getTvSet() {


return tvSet;
}

public void setTvSet(Integer tvSet) {


this.tvSet = tvSet;
}

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

Create a class BankFactory with two methods


Method Description
This method is used to return the object for ICICI
public Icici getIcici( )
class
public Hdfc This method is used to return the object for HDFC
getHdfc( ) class
Create the Main class with main( ) method to test the above class.

Input and Output format:


The first integer corresponds to select the bank, the next integer corresponds to the type of the
notification.
If there is no valid input then display 'Invalid input'.
 

[Note: All text in bold corresponds to the input and remaining text corresponds to output]

Sample Input and Output 1:

Welcome to Notification Setup


Please select your bank:
1)ICICI
2)HDFC
1
Enter the type of Notification you want to enter
1)SMS
2)Mail
3)Courier
1
ICICI - Notification By SMS

Sample Input and Output 2:

Welcome to Notification Setup


Please select your bank:
1)ICICI
2)HDFC
2
Enter the type of Notification you want to enter
1)SMS
2)Mail
3)Courier
3
HDFC - Notification By Courier

Sample Input and Output 3:

Welcome to Notification Setup


Please select your bank:
1)ICICI
2)HDFC
3
Invalid Input

public class ICICI implements Notification {

@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 void notificationBySms();

public void notificationByEmail();

public void notificationByCourier();

}
public class BankFactory {

public ICICI getIcici() {


ICICI icici = new ICICI();
return icici;
}

public HDFC getHdfc() {


HDFC hdfc = new HDFC();
return hdfc;
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Main {

public static void main(String[] args) throws IOException {


Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Notification Setup");
System.out.println("Please select your bank:\n1)ICICI\n2)HDFC");
int bank = sc.nextInt();
switch (bank) {
case 1:
System.out.println("Enter the type of Notification you want to enter\n1)SMS\n2)Mail\n3)Courier");
int msg = sc.nextInt();
BankFactory b = new BankFactory();
ICICI c = b.getIcici();
switch (msg) {
case 1:
c.notificationBySms();
break;
case 2:
c.notificationByEmail();
break;
case 3:
c.notificationByCourier();
break;
default:
System.out.println("Invalid Input");
break;
}
break;
case 2:
System.out.println("Enter the type of Notification you want to enter\n1)SMS\n2)Mail\n3)Courier");
int msg1 = sc.nextInt();
BankFactory b1 = new BankFactory();
HDFC h = b1.getHdfc();
switch (msg1) {
case 1:
h.notificationBySms();
break;
case 2:
h.notificationByEmail();
break;
case 3:
h.notificationByCourier();
break;
default:
System.out.println("Invalid Input");
break;
}
break;
default:
System.out.println("Invalid Input");
break;
}
}
}
Static Inner Class
Write a program to calculate the area of the rectangle and triangle using the static inner class concept
in java.

Create an outer class Shape with the following public static attributes


Attribute Datatyp
s e
value1 Double
value2 Double
 

Create a static inner class Rectangle which have the outer class Shape.


Include the following method in the Rectangle class
Method Name Description
Here Calculate and return the area of the rectangle by accessing the attributes
public Double
value1(length) & value2(breadth) of Shape class.
computeRectangleArea()
Area of the rectangle = (length * breadth)

Create a static inner class Triangle which have the outer class Shape.


Include the following method in the Triangle class
Method Name Description
Here Calculate and return the area of the triangle by accessing the attributes
public Double
value1(base) & value2(height) of Shape class.
computeTriangleArea()
Area of the triangle = (1/2) * (base * height)

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.

Create a driver class Main to test the above classes.

[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.

[All text in bold corresponds to input and rest corresponds to output]


Sample Input/Output 1:
Enter the shape
1.Rectangle
2.Triangle
1
Enter the length and breadth:
10
25
Area of rectangle is 250.00

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

public class Shape {


public static Double value1;
public static Double value2;

public static class Rectangle {


public Double computeRectangleArea() {
return (value1 * value2);
}
}

public static class Triangle {


public Double computeTriangleArea() {
return ((0.5) * (value1 * value2));
}
}
}
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {


public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the shape\r\n1.Rectangle\r\n2.Triangle");
int ch = sc.nextInt();
DecimalFormat df = new DecimalFormat("0.00");
switch (ch) {
case 1:
System.out.println("Enter the length and breadth:");
Shape.value1 = sc.nextDouble();
Shape.value2 = sc.nextDouble();
Shape.Rectangle r = new Shape.Rectangle();
Double rectangle = r.computeRectangleArea();
System.out.println("Area of rectangle is " + df.format(rectangle));
break;
case 2:
System.out.println("Enter the base and height:");
Shape.value1 = sc.nextDouble();
Shape.value2 = sc.nextDouble();
Shape.Triangle t = new Shape.Triangle();
Double triangle = t.computeTriangleArea();
System.out.println("Area of triangle is " + df.format(triangle));
break;
default:
System.out.println("Invalid choice");
break;
}
}
}

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 Person with the following private data members.                           


Data Type     Data Member   
String name
String dateOfBirth
String gender
String mobileNumber
String bloodGroup

Include appropriate getters and setters.

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.

The class Donor should have the following method


Method Member Function 
This method displays the donation details.
public void displayDonationDetails( )
Display the statement ‘Donation Details :’ inside this method

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.

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 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
 

class Donor extends Person{

private String bloodBankName;

private String donorType;


private String donationDate;

public Donor() {

public String getBloodBankName() {

return bloodBankName;

public void setBloodBankName(String bloodBankName) {

this.bloodBankName = bloodBankName;

public String getDonorType() {

return donorType;

public void setDonorType(String donorType) {

this.donorType = donorType;

public String getDonationDate() {


return donationDate;

public void setDonationDate(String donationDate) {

this.donationDate = donationDate;

public void displayDonationDetails( ) {

System.out.println("Donation Details :");

System.out.println("Name : "+getName());

System.out.println("Date Of Birth : "+getDateOfBirth());

System.out.println("Gender : "+getGender());

System.out.println("Mobile Number : "+getMobileNumber());

System.out.println("Blood Group : "+getBloodGroup());

System.out.println("Blood Bank Name : "+getBloodBankName());

System.out.println("Donor Type : "+getDonorType());

System.out.println("Donation Date : "+getDonationDate());

//Fill your code here

class Person{

private String name;

private String dateOfBirth;

private String gender;

private String mobileNumber;

private String bloodGroup;

Person(){
}

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getDateOfBirth() {

return dateOfBirth;

public void setDateOfBirth(String dateOfBirth) {

this.dateOfBirth = dateOfBirth;

public String getGender() {

return gender;

}
public void setGender(String gender) {

this.gender = gender;

public String getMobileNumber() {

return mobileNumber;

public void setMobileNumber(String mobileNumber) {

this.mobileNumber = mobileNumber;

public String getBloodGroup() {

return bloodGroup;

public void setBloodGroup(String bloodGroup) {

this.bloodGroup = bloodGroup;

}
import java.util.Scanner;

public class Main {

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

Donor d = new Donor();

System.out.println("Enter the name :");

d.setName(sc.nextLine());

System.out.println("Enter Date of Birth :");

d.setDateOfBirth(sc.nextLine());

System.out.println("Enter Gender :");

d.setGender(sc.nextLine());

System.out.println("Enter Mobile Number :");

d.setMobileNumber(sc.nextLine());

System.out.println("Enter Blood Group :");

d.setBloodGroup(sc.nextLine());

System.out.println("Enter Blood Bank Name :");

d.setBloodBankName(sc.nextLine());

System.out.println("Enter Donor Type :");

d.setDonorType(sc.nextLine());

System.out.println("Enter Donation Date :");


d.setDonationDate(sc.nextLine());

d.displayDonationDetails();

//Fill your code here

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.
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

Create a class HPVISACard which extends VISACard class and overrides the following method.


Method Description
public double computeRewardPoints(String type, double amount) In this method, calculate the reward points fro

Hint:
Use super keyword to calculate reward points from base class.

Create Main class with main method, get the transaction details as a comma separated values.


(Transaction type, amount, card type)

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).

Input and Output Format


Refer sample input and output for formatting specifications.
All text in bold corresponds to the input and the rest corresponds to output.

Sample Input and Output :


Enter the transaction detail
Shopping,5000,VISA card
Total reward points earned in this transaction is 50.00
Do you want to continue?(Yes/No)
Yes
Enter the transaction detail
Fuel,5000,HIVISA card
Invalid data
Do you want to continue?(Yes/No)
Yes
Enter the transaction detail
Fuel,5000,HPVISA card
Total reward points earned in this transaction is 60.00
Do you want to continue?(Yes/No)
No
 

public class VISACard {

public double computeRewardPoints(String type, double amount) {

return amount * 0.01;

}
class HPVISACard extends VISACard{

public double computeRewardPoints(String type, double amount){

double total=super.computeRewardPoints(type, amount);

if(type.equalsIgnoreCase("Fuel")) {

total=total+10;

return total;

}else{

return total;

import java.io.*;

import java.util.*;

import java.text.DecimalFormat;

public class Main {

public static void main(String[] args) {

String tDetails = null;

String transactionType = null;

double amount = 0;

String cardType = null;

String flag = null;

VISACard v = new VISACard();

HPVISACard h = new HPVISACard();

Scanner sc = new Scanner(System.in);

do {

System.out.println("Enter the transaction detail");

tDetails = sc.nextLine();

String dSplit[] = tDetails.split(",");

transactionType = dSplit[0];

amount = Double.parseDouble(dSplit[1]);

cardType = dSplit[2];
DecimalFormat df = new DecimalFormat("0.00");

if (cardType.equals("VISA card")) {

System.out.println("Total reward points earned in this transaction is "

+ df.format(v.computeRewardPoints(transactionType, amount)));

System.out.println("Do you want to continue?(Yes/No)");

flag = sc.nextLine();

} else if (cardType.equals("HPVISA card")) {

System.out.println("Total reward points earned in this transaction is "

+ df.format(h.computeRewardPoints(transactionType, amount)));

System.out.println("Do you want to continue?(Yes/No)");

flag = sc.nextLine();

} else {

System.out.println("Invalid data");

System.out.println("Do you want to continue?(Yes/No)");

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 class Event with the following protected attributes/variables.


Data Type Variable
String name
String type
double costPerDay
int noOfDays

Include a four argument constructor with parameters in the following order,


public Event(String name, String type, double costPerDay, int noOfDays)
Create class Exhibition which extends the Event class with the following private attributes/variables.
Data Type Variable
static int gst = 5
int noOfStalls

Include a five argument constructor with parameters in the following order,


public Exhibition(String name, String type, double costPerDay, int noOfDays, int noOfStalls)

Include the following methods.


Method Description
public double totalCost() This method is to calculate the total amount with 5% GST

Create class StageEvent which extends the Event class with the following private


attributes/variables.
Data Type Variable
static int gst = 15
int noOfSeats

Include a five argument constructor with parameters in the following order,


public StageEvent(String name, String type, double costPerDay, int noOfDays, int noOfSeats)

Include the following method.


Method Description
public double totalCost() This method is to calculate the total amount with 15% GST

Use super( ) to call and assign values in base class constructor.


Override toString() method to display the event details. Refer the sample output format.

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.

Input and Output Format:


Refer sample input and output for formatting specifications.
All text in bold corresponds to the input and the rest corresponds to output.

Sample Input and Output 1:


Enter event name
Sky Lantern Festival
Enter the cost per day
1500
Enter the number of days
3
Enter the type of event
1.Exhibition
2.Stage Event
2
Enter the number of seats
100
Event Details
Name:Sky Lantern Festival
Type:Stage Event
Number of seats:100
Total amount: 5175.00

Sample Input and Output 2:


Enter event name
Glastonbury
Enter the cost per day
5000
Enter the number of days
2
Enter the type of event
1.Exhibition
2.Stage Event
1
Enter the number of stalls
10
Event Details
Name:Glastonbury
Type:Exhibition
Number of stalls:10
Total amount: 10500.00

Sample Input and Output 3:


Enter event name
Glastonbury
Enter the cost per day
5000
Enter the number of days
2
Enter the type of event
1.Exhibition
2.Stage Event
3
Invalid input

import java.util.*;

import java.text.DecimalFormat;

public class Main {

public static void main(String[] args) {

String name, type;


double cpd;

int npd;

Scanner sc = new Scanner(System.in);

System.out.println("Enter event name");

name = sc.nextLine();

System.out.println("Enter the cost per day");

cpd = sc.nextDouble();

System.out.println("Enter the number of days");

npd = sc.nextInt();

sc.nextLine();

System.out.println("Enter the type of event\n1.Exhibition\n2.Stage Event");

type = sc.nextLine();

DecimalFormat df = new DecimalFormat("0.00");

switch (type) {

case "1":

System.out.println("Enter the number of stalls");

int stalls = sc.nextInt();

Exhibition e = new Exhibition(name, type, cpd, npd, stalls);

Double total = e.totalCost();

System.out.println(e.toString() + "\nTotal amount:" + df.format(total));

break;

case "2":

System.out.println("Enter the number of seats");

int seats = sc.nextInt();

StageEvent s = new StageEvent(name, type, cpd, npd, seats);

Double total1 = s.totalCost();

System.out.println(s.toString() + "\nTotal amount:" + df.format(total1));

break;

default:

System.out.println("Invalid input");

break;

}
}

class Event{

protected String name;

protected String type;

protected double costPerDay;

protected int noOfDays;

public Event(String name, String type, double costPerDay, int noOfDays) {

super();

this.name = name;

this.type = type;

this.costPerDay = costPerDay;

this.noOfDays = noOfDays;

class StageEvent extends Event {

static int gst = 15;

int noOfSeats;

public StageEvent(String name, String type, double costPerDay, int noOfDays, int noOfSeats) {

super(name, type, costPerDay, noOfDays);

this.noOfSeats = noOfSeats;

public double totalCost() {

double totalAmount = (costPerDay * noOfDays);

double gstAmount = (totalAmount * gst) / 100;

double total = (totalAmount + gstAmount);

return total;

}
@Override

public String toString() {

return "Event Details\nName:" + name + "\nType:Stage Event\nNumber of seats:" + noOfSeats;

class Exhibition extends Event {

static int gst = 5;

int noOfStalls;

public Exhibition(String name, String type, double costPerDay, int noOfDays, int noOfStalls) {

super(name, type, costPerDay, noOfDays);

this.noOfStalls = noOfStalls;

public double totalCost() {

double totalAmount = (costPerDay * noOfDays);

double gstAmount = (totalAmount * gst) / 100;

double total = (totalAmount + gstAmount);

return total;

@Override

public String toString() {

return "Event Details\nName:" + name + "\nType:Exhibition\nNumber of stalls:" + noOfStalls;

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 an abstract class called Event with following protected attributes.


Attributes Datatype
name String
detail String
type String
organiser String
 
Include 4 argument constructors in the Event class in the following order Event(String name, String
detail, String type, String organiser)

Include the following abstract method in the class Event.


Method  Description
abstract Double calculateAmount() an abstract method

Create a class named Exhibition which extends Event class with the following private attributes


Attributes Datatype
noOfStalls Integer
 rentPerStall Double
 
Include a six argument constructor with parameters in the following order,
public Exhibition(String name, String detail, String type, String organiser, Integer noOfStalls,Double
rentPerStall)
Use super( ) to call and assign values in base class constructor.

Include the following abstract method in the class Exhibition.


Method  Description
Double calculateAmount () This method returns the product of noOfStalls and rentPerStall

Create a class named StageEvent which extends Event class with the following private attributes.


Attribute Datatype
noOfShows Integer
costPerShow Double
Include a six argument constructor with parameters in the following order,
public StageEvent(String name, String detail, String type, String organiser, Integer
noOfShows,Double costPerShow)
Use super( ) to call and assign values in base class constructor.
Include the following abstract method in the class StageEvent.
Method   Description
Double calculateAmount() This method returns the product of noOfShows and costPerShow

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.

Sample Input and output 1:


 
Enter your choice
1.Exhibition
2.StageEvent
1
Enter the details in CSV format
Book expo,Special sale,Academics,Mahesh,100,1000
Exhibition Details
Event Name:Book expo
Detail:Special sale
Type:Academics
Organiser Name:Mahesh
Total Cost:100000.0

Sample Input and Output 2:


 
Enter your choice
1.Exhibition
2.StageEvent
2
Enter the details in CSV format
JJ magic show,Comedy magic,Entertainment,Jegadeesh,5,1000
Stage Event Details
Event Name:JJ magic show
Detail:Comedy magic
Type:Entertainment
Organiser Name:Jegadeesh
Total Cost:5000.0
 
 
Sample Input and Output 3:
 
Enter your choice
1.Exhibition
2.StageEvent
3
Invalid choice

public class Exhibition extends Event {


private Integer noOfStalls;

private Double rentPerStall;

public Exhibition(String name, String detail, String type, String organiser, Integer noOfStalls,

Double rentPerStall) {

super(name, detail, type, organiser);

this.noOfStalls = noOfStalls;

this.rentPerStall = rentPerStall;

Double calculateAmount() {

return noOfStalls * rentPerStall;

public class StageEvent extends Event {

private Integer noOfShows;

private Double costPerShow;

public StageEvent(String name, String detail, String type, String organiser, Integer noOfShows,

Double costPerShow) {

super(name, detail, type, organiser);

this.noOfShows = noOfShows;

this.costPerShow = costPerShow;

Double calculateAmount() {

return noOfShows * costPerShow;

public abstract class Event {

protected String name;

protected String detail;


protected String type;

protected String organiser;

public Event(String name, String detail, String type, String organiser) {

this.name = name;

this.detail = detail;

this.type = type;

this.organiser = organiser;

abstract Double calculateAmount();

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getDetail() {

return detail;

public void setDetail(String detail) {

this.detail = detail;

public String getType() {

return type;

}
public void setType(String type) {

this.type = type;

public String getOrganiser() {

return organiser;

public void setOrganiser(String organiser) {

this.organiser = organiser;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String s, name, detail, type, organiser;

Integer noOfStalls, noOfShows;

Double rentPerStall, costPerShow, totalCost;

System.out.println("Enter your choice");

System.out.println("1.Exhibition");

System.out.println("2.StageEvent");

int ch = sc.nextInt();

switch (ch) {

case 1:

System.out.println("Enter the details in CSV format");

sc.nextLine();

s = sc.nextLine();

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

name = split[0];

detail = split[1];
type = split[2];

organiser = split[3];

noOfStalls = Integer.parseInt(split[4]);

rentPerStall = Double.parseDouble(split[5]);

Exhibition e = new Exhibition(name, detail, type, organiser, noOfStalls, rentPerStall);

totalCost = e.calculateAmount();

System.out.println("Exhibition Details");

System.out.println("Event Name:" + e.getName());

System.out.println("Detail:" + e.getDetail());

System.out.println("Type:" + e.getType());

System.out.println("Organiser Name:" + e.getOrganiser());

System.out.println("Total Cost:" + totalCost);

break;

case 2:

System.out.println("Enter the details in CSV format");

sc.nextLine();

s = sc.nextLine();

String split1[] = s.split(",");

name = split1[0];

detail = split1[1];

type = split1[2];

organiser = split1[3];

noOfShows = Integer.parseInt(split1[4]);

costPerShow = Double.parseDouble(split1[5]);

StageEvent se = new StageEvent(name, detail, type, organiser, noOfShows, costPerShow);

totalCost = se.calculateAmount();

System.out.println("Stage Event Details");

System.out.println("Event Name:" + se.getName());

System.out.println("Detail:" + se.getDetail());

System.out.println("Type:" + se.getType());

System.out.println("Organiser Name:" + se.getOrganiser());

System.out.println("Total Cost:" + totalCost);


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.

Create a parent class Event with following protected attributes,


Attributes Datatype
name String
detail String
ownerName String
Include parameterized constructors to the Event class in the following order Event(String name,
String detail, String ownerName)
Include the below abstract method in the Event class.
Method Description
public abstract Double projectedRevenue() Return just 0.0

Then create child class Exhibition that extends Event with the following attribute,


Attributes Datatype
noOfStalls Integer
Include parameterized constructors to the Exhibition class in the following order Exhibition(String
name, String detail, String ownerName, Integer noOfStalls). Use super( ) to call and assign values in
base class constructor.
Add method projectedRevenue() in Exhibition class
Method Description
public Double projectedRevenue() Calculate revenue and return the double value. Each stall will produce R
 
And create another child class StageEvent that extends Event with the following attribute,
Attributes Datatype
noOfShows Integer
noOfSeatsPerShow Integer
Include parameterized constructors to the StageEvent class in the following order StageEvent(String
name, String detail, String ownerName, Integer noOfShows, Integer noOfSeatsPerShow). Use
super( ) to call and assign values in base class constructor.
Add method projectedRevenue() in StageEvent class
Method Description
public Double projectedRevenue() Calculate revenue and return the double value. Each seat produces 

Refer sample input/output for other further details and format of the output.

[All Texts in bold corresponds to the input and rest are output]
Sample Input/Output 1:

Enter the name of the event:


Science Fair
Enter the detail of the event:
Explore Technology
Enter the owner name of the event:
ABCD
Enter the type of the event:
1.Exhibition
2.StageEvent
1
Enter the number of stalls:
65
The projected revenue of the event is 650000.0

Sample Input/Output 2:

Enter the name of the event:


Magic Show
Enter the detail of the event:
See Magic without Logic
Enter the owner name of the event:
SDFG
Enter the type of the event:
1.Exhibition
2.StageEvent
2
Enter the number of shows:
10
Enter the number of seats per show:
100
The projected revenue of the event is 50000.0
 
 

public class StageEvent extends Event{

private Integer noOfShows;

private Integer noOfSeatsPerShow;

public StageEvent()

{}

public StageEvent(String name, String detail, String ownerName,Integer noOfShows,Integer noOfSeatsPerShow)

super(name,detail,ownerName);

this.name = name;

this.detail = detail;

this.ownerName = ownerName;

this.noOfShows = noOfShows;

this.noOfSeatsPerShow = noOfSeatsPerShow;

@Override

public double projectedRevenue()

double revenue = noOfShows * noOfSeatsPerShow * 50;

return revenue;

public abstract class Event {

protected String name;

protected String detail;

protected String ownerName;


public Event(){

public Event(String name, String detail, String ownerName)

this.name = name;

this.detail = detail;

this.ownerName = ownerName;

public double projectedRevenue(){

return 0.0;

import java.io.IOException;

import java.util.Scanner;

public class Main {

public static void main(String[] args) throws IOException {

Scanner sc = new Scanner(System.in);

double totalrevenue = 0;

System.out.println("Enter the name of the event:");

String name = sc.nextLine();


System.out.println("Enter the detail of the event:");

String detail = sc.nextLine();

System.out.println("Enter the owner name of the event:");

String ownerName = sc.nextLine();

System.out.println("Enter the type of the event:\n1.Exhibition\n2.StageEvent");

int choice = sc.nextInt();

switch(choice){

case 1 :

System.out.println("Enter the number of stalls:");

int noOfStalls = sc.nextInt();

Exhibition exObj = new Exhibition(name,detail,ownerName,noOfStalls);

totalrevenue = exObj.projectedRevenue();

System.out.println("The projected revenue of the event is " + totalrevenue);

break;

case 2 :

System.out.println("Enter the number of shows:");

int noOfShows = sc.nextInt();

System.out.println("Enter the number of seats per show:");

int noOfSeatsPerShow = sc.nextInt();

StageEvent seObj = new StageEvent(name,detail,ownerName,noOfShows,noOfSeatsPerShow);

totalrevenue = seObj.projectedRevenue();

System.out.println("The projected revenue of the event is " + totalrevenue);

break;
default : break;

public class Exhibition extends Event{

//Your code here

private Integer noOfStalls;

public Exhibition()

public Exhibition(String name, String detail, String ownerName,Integer noOfStalls)

super(name,detail,ownerName);

this.name = name;

this.detail = detail;

this.ownerName = ownerName;

this.noOfStalls = noOfStalls;

@Override

public double projectedRevenue()

double revenue = noOfStalls * 10000;

return revenue;
}

Duplicate mobile number exception


 

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.

Create a Class called ContactDetail with the following private attributes.

Attributes Datatype

mobile String

alternateMobile String

landLine String

email String

address String

Include getters and setters.


Include default and parameterized constructors.
Format for a parameterized constructor is ContactDetail(String mobile, String alternateMobile,String
landLine, String email, String address)

Override the toString() method to display the Contact details as specified.

Create a class called ContactDetailBO with following methods


Method  Description

This method throws DuplicateMobileNumb


static void validate(String mobile,String alternateMobile)
if the mobile and alternateMobile are the sa

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.

Input and Output format:


Refer to sample Input and Output for formatting specifications.

Note: All text in bold corresponds to the input and rest corresponds to the output.

Sample Input and Output 1:

Enter the contact details


9874563210,9874563210,0447896541,[email protected],22nd street kk nagar chennai
DuplicateMobileNumberException: Mobile number and alternate mobile number are same

Sample Input and Output 2:

Enter the contact details


9874563210,9876543211,0447896541,[email protected],22nd lane RR nagar kovai
Mobile:9874563210
Alternate mobile:9876543211
LandLine:0447896541
Email:[email protected]
Address:22nd lane RR nagar kovai

public class DuplicateMobileNumberException extends Exception{

public DuplicateMobileNumberException(String s)

super(s);

public String toString(){

return "DuplicateMobileNumberException: Mobile number and alternate mobile number are same ";

}
public class ContactDetailBO {

static void validate(String mobile, String alternateMobile) throws DuplicateMobileNumberException {

if (mobile.equals(alternateMobile)) {

throw new DuplicateMobileNumberException("DuplicateMobileNumberException :");

}-----------

public class ContactDetail {

//Your code here

private String mobile;

private String alternateMobile;

private String landLine;

private String email;

private String address;

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()

public String getMobile() {

return mobile;

public void setMobile(String mobile) {

this.mobile = mobile;

}
public String getAlternateMobile() {

return alternateMobile;

public void setAlternateMobile(String alternateMobile) {

this.alternateMobile = alternateMobile;

public String getLandLine() {

return landLine;

public void setLandLine(String landLine) {

this.landLine = landLine;

public String getEmail() {

return email;

public void setEmail(String email) {

this.email = email;

public String getAddress() {

return address;

public void setAddress(String address) {

this.address = address;

public String toString()

return "Mobile:"+this.mobile+"\nAlternate
mobile:"+this.alternateMobile+"\nLandLine:"+this.landLine+"\nEmail:"+this.email+"\nAddress:"+this.address;

import java.io.*;

public class Main {

public static void main(String[] args) throws Exception {


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the contact details");

String st = br.readLine();

String[] str = st.split(",");

ContactDetail userInfo = new ContactDetail(str[0], str[1], str[2], str[3], str[4]);

ContactDetailBO BO = new ContactDetailBO();

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 a class SeatNotAvailableException that extends Exception.

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.

Input and Output format:


Refer sample Input and Output for formatting specifications.t of the output.

[All Texts in bold corresponds to the input and rest are output]
Sample Input and Output 1:

Enter the number of rows and columns of the show:


3
Enter the number of seats to be booked:
2
Enter the seat number 1
8
Enter the seat number 2
0
The seats booked are:
100
000
001

Sample Input and Output 2:

Enter the number of rows and columns of the show:


3
Enter the number of seats to be booked:
2
Enter the seat number 1
9
java.lang.ArrayIndexOutOfBoundsException: 9
The seats booked are:
000
000
000

Sample Input and Output 3:

Enter the number of rows and columns of the show:


4
Enter the number of seats to be booked:
3
Enter the seat number 1
15
Enter the seat number 2
14
Enter the seat number 3
15
SeatNotAvailableException: Already Booked
The seats booked are:
0000
0000
0000
0011

public class SeatNotAvailableException extends Exception{

public SeatNotAvailableException(String s) {

super(s);

}
}
 ----------------------------------------------------------------------------------------------------------

import java.util.Scanner;

import java.io.*;

public class Main {

public static void main(String args[]) throws SeatNotAvailableException{

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of the show:");

int n = sc.nextInt();

int size = (n*n);

int s;

int a[] = new int[size];

int mat[][] = new int[n][n];

System.out.println("Enter the number of seats to be booked:");

int seats = sc.nextInt();

try {

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

System.out.println("Enter the seat number "+(i+1));

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 {

throw new SeatNotAvailableException("Already Booked");

}catch (Exception e) {

System.out.println(e);

finally {

System.out.println("The seats booked are:");

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.

Sample Input and Output 1:

Enter the stage event start date and end date


27-01-2017-12
Input dates should be in the format 'dd-MM-yyyy-HH:mm:ss'

Sample Input and Output 2:

Enter the stage event start date and end date


27-01-2017-12:0:0
28-01-2017-12:0:0
Start date:27-01-2017-12:00:00
End date:28-01-2017-12:00:00

import java.util.*;

import java.text.ParseException;

import java.text.SimpleDateFormat;

public class Main {

public static void main(String[] args) {

// your code here


String d,d1;

Scanner s=new Scanner(System.in);

try{

System.out.println("Enter the stage event start date and end date");

d=s.next();

SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy-HH:mm:ss");

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) {

System.out.println("Input dates should be in the format 'dd-MM-yyyy-HH:mm:ss'");

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.

Sample Input  and Output 1:

Enter the cost of the item for n days


100
Enter the value of n
 0
java.lang.ArithmeticException: / by zero

Sample Input and Output 2:

Enter the cost of the item for n days


100
Enter the value of n
20
Cost per day of the item is 5
 

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the cost of the item for n days");

int days = sc.nextInt();

System.out.println("Enter the value of n");

int num = sc.nextInt();

try{
int cost = days/num;

System.out.println("Cost per day of the item is "+cost);

}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.

Input and Output format:


The first line of input consists of an integer which corresponds to the number of seats to be booked.
The next n lines of input consist of the integer which corresponds to the seat number.
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 number of seats to be booked:


5
Enter the seat number 1
23
Enter the seat number 2
42
Enter the seat number 3
65
Enter the seat number 4
81
Enter the seat number 5
100
The seats booked are:
23
42
65
81
100

Sample Input and Output 2:

Enter the number of seats to be booked:


4
Enter the seat number 1
12
Enter the seat number 2
101
java.lang.ArrayIndexOutOfBoundsException: 100

import java.util.Scanner;

public class Main {

public static void main(String args[]) {

int[] seatArray = new int[100];

int n,count = 1;

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of seats to be booked:");

n = sc.nextInt();

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

System.out.println("Enter the seat number "+(i+1));

count = sc.nextInt();

seatArray[count-1] = count;

System.out.println("The seats booked are:");

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

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...

Fill up the blank to complete the code.

public class MyClass {


public static void main(String[] args) {
System.________.println("Object oriented programming");
}
}

Entered Answer: out


Correct Answer: out
2  Which translates the program line by line?

Which translates the program line by line?


PROBLEM
1)
compiler
2)
interpreter

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

4  How do you insert COMMENTS in Java code?

How do you insert COMMENTS in Java code?


1)
/* This is a comment
2)
#This is a comment
3)
//This is a comment

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...

Predict the output for the below code snippet?

public class Main {


public static void main(String args[]) {
System.out.println(i);
}
}
1)
i
PROBLEM
2)
error
3)
0
4)
1

7  Predict the type of error in the below code. public class Main { public static void main(string a...

Predict the type of error in the below code.

public class Main {


public static void main(string args[]) {
System.out.println("Hello");
}
}
1)
compilation errors
2)
logical errors
3)
run time errors
4)
None of the mentioned options

8  Java is short for JavaScript

Java is short for JavaScript


1)
TRUE
2)
FALSE

9  How to get the java code from the .class files?

How to get the java code from the .class files?


1)
using decompiler
2)
using compiler
3)
using interpreter
4)
using JVM

10  class is a ____________


PROBLEM
class is a ____________
1)
keyword
2)
entity
3)
object
4)
None of the mentioned options
Go to course

T1 - Topic 1... / Programming Fundamentals an...


CONGRATS!!!
Congrats !!! You have successfully completed the session :) ...
TOTAL SCORE: 93.33%

PROGRAMMING FUNDAMENTALS AND OOP USING JAVA / EXPLORE / HOTS


Answered Questions :14 / 15
Your Score : 93.33%

PROBLEM

1  What is bytecode in the context of Java?

What is bytecode in the context of Java?


1)
machine code
2)
java code
3)
binary code
4)
None of the mentioned options

2  Another name for compilation errors?

Another name for compilation errors?


1)
PROBLEM

run time error


2)
syntax error
3)
semantic error
4)
logical error

3  Predict the output for the below code. public class Main { public static void main(String[] args)...

Predict the output for the below code.

public class Main {


public static void main(String[] args){
// System.out.println("Java Programming");

}
}
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...

Predict the output for the below code snippet?

public class Main {


public static void main(String[] args){
/*Java
Multi
line
comment*/
System.out.println("Hello");

}
}
1)
Java

Multi
PROBLEM

line

comment

Hello
2)
Hello
3)
/*Java

Multi

line

comment*/

Hello
4)
None of the mentioned options

5  Which generates the intermediate object code?

Which generates the intermediate object code?


1)
JVM
2)
compiler
3)
JRE
4)
JDK

6  Which makes the Java a platform-independent language?

Which makes the Java a platform-independent language?


1)
bytecode implementation
2)
compilation
3)
execution
4)
None of the mentioned options
PROBLEM

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

8  Which translates the entire program?

Which translates the entire program?


1)
compiler
2)
interpreter

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

10  Java SE 12 was released on _____.

Java SE 12 was released on _____.


1)
2019
2)
2018
PROBLEM
3)
2017
4)
2020

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.

public class Main {


public static void Main(String[] args){

}
}
1)
Yes
2)
No

12  Choose the code to write a main class in Java.

Choose the code to write a main class in Java.


1)
public class Main {

public static Void main(String[] args){

}
2)
public class Main {

Public Static Void Main(String[] args){

}
3)
public class Main {
PROBLEM

public static void main(String[] args){

}
4)
public class Main {

public static void main(string[] args){

13  When Java program is compiled _________ will be generated

When Java program is compiled _________ will be generated


1)
bytecode
2)
classcode
3)
javacode
4)
binarycode

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

T1 - Topic 6... / Interfaces and Inner Class ...


CONGRATS!!!
Congrats !!! You have successfully completed the session :) ...
TOTAL SCORE: 100.0%

INTERFACES AND INNER CLASS / EXPLORE


Answered Questions :15 / 15
Your Score : 100.0%

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 { }

class B extends D implements A { }

public class Test extends Thread {


    public static void main(String[] args) {
        B b = new B();
        if (b instanceof A)
            System.out.println("b is an instance of A");
        if (b instanceof C)
            System.out.println("b is an instance of 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

2  The variables in an interface cannot be,

The variables in an interface cannot be,

1)
static
2)
final
3)
PROBLEM

protected
4)
constant

3  _______ access specifiers can be used for an interface?

_______ access specifiers can be used for an interface?

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(); ...

Which of the following is true considering the code,


 
public interface A {
    void method();
}
abstract public class B implements A{ }

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

5  Which of the following is true?

Which of the following is true?

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.

6  _______ keyword is used to define interfaces in Java.

_______ keyword is used to define interfaces in Java.

1)
interface
2)
Interface
3)
intf
4)
Intf

7  What is the output of this program?   public interface TestInf {     int i =10; } public class...

What is the output of this program?


 
public interface TestInf {
    int i =10;
}

public class Test {


    public static void main(String... args) {
        TestInf.i=12;
        System.out.println(TestInf.i);
    }
}

1)
10
2)
12
3)
compilation error
4)
PROBLEM

None of the listed options

8  Interfaces can have constructors.

Interfaces can have constructors.

1)
False
2)
True

9  The methods in an interface can not be,

The methods in an interface can not be,

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 ...

What is the output of this program?


 
interface A {
    void display();
}

interface B extends A{}

public class Test implements B {


    public void display() {
        System.out.print("Hi");
    }
    public static void main(String args[]) {
        Test t = new Test();
PROBLEM

        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...

What is the output of this program?


 
public interface A {
    protected String getName();
}

public class Test implements A {


    public String getName() {
        return "name";
    }
    
    public static void main (String[] args) {
        Test t = new Test();
        System.out.println(t.getName());
    }
}

1)
name
2)
compilation error due to protected method
3)
compilation error in method definition
4)
PROBLEM

None of the listed options

12  An interface can _________.

An interface can _________.

1)
extend many class
2)
extend many interface
3)
implement many interfaces
4)
implement many classes

13  Examples of marker interface are,

Examples of marker interface are,

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

15  Interfaces can have method implementation for few methods.


PROBLEM
Interfaces can have method implementation for few methods.

1)
True
2)
False

T1 - Topic 7... / Exception Handling / Explore


CONGRATS!!!
Congrats !!! You have successfully completed the session :) ...
TOTAL SCORE: 100.0%

EXCEPTION HANDLING / EXPLORE


Answered Questions :20 / 20
Your Score : 100.0%
PROBLEM

1  What will be the output for the following code snippet?   static int computeDivision(int a, int...

What will be the output for the following code snippet?


 
static int computeDivision(int a, int b) {
    int res =0;
    try {
        res = a/b;
    }
    catch(NumberFormatException ex) {
        System.out.println("NumberFormatException");
    }
    return res;
    }
public static void main(String args[]) {
    int a = 1,b = 0;
    try {
        int i = computeDivision(a,b);
        System.out.println(i);
    }
    catch(ArithmeticException e) {
        System.out.println(e.getMessage());
    }
}

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....

What will be the output for the following code snippet?


 
PROBLEM

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

3  Which of these keywords is used to monitor exceptions?

Which of these keywords is used to monitor exceptions?


1)
try
2)
finally
3)
throw
4)
catch

4  Which of the following will be used to print the Exception messages?

Which of the following will be used to print the Exception messages?


1)
printStackTrace()
2)
PROBLEM

getMessage()
3)
toString()
4)
All

5  To return description of an exception,Which of the following methods is used?

To return description of an exception,Which of the following methods is used?


1)
getException()
2)
getMessage()
3)
obtainDescription()
4)
obtainException()

6  The finally block will not be executed if

The finally block will not be executed if


1)
By calling System.exit(0)
2)
By causing a fatal error
3)
All of the listed options
4)
None of the listed options

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

8  Which of these statements is incorrect?

Which of these statements is incorrect?


1)
try block need not to be followed by catch block
2)
try block can be followed by finally block instead of catch block
3)
try can be followed by both catch and finally block
4)
try need not to be followed by anything

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");    ...

What will be the output for the following code snippet?


 
try {
    System.out.printf("1");
    int data = 5/0;
}
catch(ArithmeticException e) {
    Throwable o = new Throwable("Sample");
    try {
        throw o;
    }
    catch(Throwable e1) {
        System.out.printf("8");
    }
}
finally {
PROBLEM

    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?

Which of the following is a super class of all exception type classes?


1)
Catchable
2)
RuntimeExceptions
3)
String
4)
Throwable

12  parseInt() method can throw what type of Exception.

parseInt() method can throw what type of Exception.


1)
ArithmeticException
2)
ClassNotFoundException
3)
NullPointerException
4)
NumberFormatException

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...

What will be the output for the following code snippet?


 
try {
    int n = 100/0;
    System.out.print("1");
}
catch(Exception e) {
    System.out.print(e.toString());
}

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...

What will be the output for the following code snippet?

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...

What will be the output for the following code snippet?


 
static void validate(int age) {
    if(age<18)
        throw new ArithmeticException("Not Valid");
    else
        System.out.println("Welcome");
}
public static void main(String args[]) {
    try {
        validate(13);
    }
    catch(ArithmeticException e) {
        System.out.print(e.getMessage() + " ");
    }
    System.out.print("Further code...");
}

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...

What will be the output for the following code snippet?


 
try {
    int a[]=new int[2];
PROBLEM

    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...

What will happen when p() method is called?


 
void m() {
    throw new java.io.IOException("device error");//checked exception
}
void n() {
    m();
}
void p() {
    try {
        n();
        System.out.println("No exception occurred");
    }
PROBLEM

    catch(Exception e) {
        System.out.println("Exception handled");
    }
}

1)
Exception handled
2)
CompileTime Error
3)
No exception occurred
4)
None of the listed options

19  Unchecked Exceptions come under ____________

Unchecked Exceptions come under ____________


1)
Error Classes
2)
Runtime Exception Classes
3)
Error and Runtime Exception Classes
4)
None of the listed options

20  What will be the output for the following code snippet?   try {     int num=Integer.parseInt ("...

What will be the output for the following code snippet?


 
try {
    int num=Integer.parseInt ("XYZ") ;
    System.out.println(num);
}
catch(ArithmeticException e) {
    System.out.println("ArithmeticException");
}
catch(NumberFormatException e) {
    System.out.println("NumberFormatException");
PROBLEM

1)
Arithmetic Exception
2)
NumberFormatException
3)
XYZ
4)
num

T1 - Topic 9... / Primitive Wrappers and java...


CONGRATS!!!
Congrats !!! You have successfully completed the session :) ...
TOTAL SCORE: 100.0%

PRIMITIVE WRAPPERS AND JAVA.UTIL & JAVA.LANG CLASSES / EXPLORE


Answered Questions :20 / 20
Your Score : 100.0%

PROBLEM

1  Output for the below code snippet   Date d; SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yy...

Output for the below code snippet


 
Date d;
PROBLEM

SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");


d=sdf.parse("45-03-2018");
System.out.println(sdf.format(d));

1)
compile error
2)
04-03-2018
3)
14-04-2018
4)
14-03-2018

2  Output for the below code snippet   String s = "Java"+1+2+"Quiz"+""+(3+4); System.out.println(s);

Output for the below code snippet


 
String s = "Java"+1+2+"Quiz"+""+(3+4);
System.out.println(s);

1)
Java3Quiz7
2)
Java3Quiz34
3)
Java12Quiz34
4)
Java12Quiz7

3  Output for the below code snippet   String s1 = "one"; StringBuffer sb = new StringBuffer(s1); ...

Output for the below code snippet


 
String s1 = "one";
StringBuffer sb = new StringBuffer(s1);
StringBuffer s2 = sb.append("two");
System.out.println(s2);
 

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+" ");     ...

Output for the below code snippet


try{
    String s1 = null;
    System.out.print(s1+" ");
    System.out.print(s1.toString());
}catch(Exception e){
    System.out.println("NullPointerException");
}

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(...

Output for the below code snippet


 
String s = "Java String Quiz";
System.out.println(s.charAt(s.toUpperCase().length()));

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...

Output for the below code snippet


 
String s1 = " Hey, buddy! ";
s1=s1.trim();
System.out.println(s1.length());
 

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()...

Output for the below code snippet<br />


 
String s=" Hello World ";
System.out.print(s.length()+" ");
s.trim();
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")...

Output for the below code snippet


String str = null;
if(str.length() == 0){
System.out.print("1");
PROBLEM
}
else if(str == null){
System.out.print("2");
}
else{
System.out.print("3");
}
1)
Error
2)
1
3)
2
4)
3

12  Which of the following statements are incorrect?

Which of the following statements are incorrect?


1)
String is a class
2)
Strings in java are mutable
3)
Every string is an object of class String
4)
Java defines a peer class of String, called StringBuffer, which allows string to be altered

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);

What will the Output for the below code snippet?


 
PROBLEM

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...

Output for the below code snippet


 
Date d;
SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
sdf.setLenient(false);
d=sdf.parse("45-03-2018");
System.out.println(sdf.format(d));

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...

Output for the below code snippet


 
String s = "String Quiz";
System.out.println(s.charAt(s.toLowerCase().length()-1));

1)
Runtime Exception
2)
Prints "z"
3)
Prints "Z"
4)
Converts "Z" to int 90 and prints "90"

18  Which of the following is used to store the Date in database?

Which of the following is used to store the Date in database?


1)
java.sql.Date
2)
java.util.Date
3)
java.sql.DateTime
4)
java.util.DateTime

19  Output for the below code snippet. StringBuilder sb=new StringBuilder("Hello World"); sb.delete...

Output for the below code snippet.


StringBuilder sb=new StringBuilder("Hello World");
sb.delete(1,3);
System.out.println(sb);

1)
Ho World
2)
Hlo World
3)
Hello World
PROBLEM
4)
Hello Wd

20  Which of the following is true?

Which of the following is true?


1)Both StringBuffer and StringBuilder is not synchronized
2)Both StringBuffer and StringBuilder is synchronized
3)StringBuffer is Synchronized where as StringBuilder is not Synchronized
4)StringBuilder is Synchronized where as StringBuffer is not Synchronized

T1 - Topic 1... / Java Streams and Writers - ...


CONGRATS!!!
Congrats !!! You have successfully completed the session :) ...

TOTAL SCORE: 100.0%

STREAMS AND WRITERS / QUIZ


Answered Questions :20 / 20
Your Score :  100.0%

PROBLEM

1  Console c=System.console(); System.out.println("Enter password: "); char[] ch=c.readPassword(); ...

Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();

The password which is typed will be displayed to the user.


1)

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)

None of the listed options


3  try {     FileInputStream fin=new FileInputStream("output.txt");     int i=0;     while((i=fin.re...

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

4  Which of these class is used to read characters in a file?

Which of these class is used to read characters in a file?


1)

FileReader
2)

FileWriter
3)

FileInputStream
4)

InputStreamReader
5  StringReader takes an input ______ and changes it into ______ stream

StringReader takes an input ______ and changes it into ______ stream


1)

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()

Which of the following FileReader class has?

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 ______

The getBuffer() method in StringWriter class returns ______


1)

String
2)

byte
3)

char
4)

StringBuffer
PROBLEM

9  FileWriter class is used to write character-oriented data to a file

FileWriter class is used to write character-oriented data to a file


1)

True
2)

False
10  Reader and Writer is a

Reader and Writer is a


1)

class
2)

Interface
3)

Abstract class
4)

None of the listed options


11  To read input from the keyboard ______ class present in java.util package.

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 ...

InputStreamReader reader = new InputStreamReader(System.in);


In above object creation "in" is an object of ______ class
1)

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

The Writer's subClass must implements


1)

flush()
2)

write(char[], int, int)


3)

close()
4)

All of the listed options


15  Which exception is thrown by read() method?

Which exception is thrown by read() method?


1)

IOException
2)

InterruptedException
3)

SystemException
PROBLEM

4)

SystemInputException
16  ______ stream that connects two running programs

______ stream that connects two running programs


1)

Program stream
2)

Conduit
3)

Channel
4)

Pipe
17  Function of nextLine() method in Scanner class.

Function of nextLine() method in Scanner class.


1)

it returns the next token from the scanner.


2)

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)

All of the listed options


18  The print() and println() methods are in ______ class

The print() and println() methods are in ______ class


1)

System
2)

PrintStream
3)

StringWriter
4)

BufferedWriter
PROBLEM

19  What is a buffer?

What is a buffer?
1)

The cable that connects a data source to the bus.


2)

A section of memory used as a staging area for input or output data.


3)

Any stream that deals with character IO.


4)

A file that contains binary data.


20  What will be the output for the below code snippet?   String srg = "1##2#34###12"; byte ary[] =...

What will be the output for the below code snippet?


 

String srg = "1##2#34###12";


byte ary[] = srg.getBytes();
ByteArrayInputStream array = new ByteArrayInputStream(ary);
PushbackInputStream push = new PushbackInputStream(array);
int i;
while( (i = push.read())!= -1) {
    if(i == '#') {
        int j;
        if( (j = push.read()) == '#'){
        System.out.print("**");
        }
        else {
            push.unread(j);
            System.out.print((char)i);
        }
    }
    else {
        System.out.print((char)i);
    }
}
PROBLEM

1)

1**2#34*#12
2)

1**2*34**#12
3)

1**2#34***12
4)

1**2#34**#12

T3 - Topic 3... / Logging & Debugging / Explo...


CONGRATS!!!
Congrats !!! You have successfully completed the session :) ...

TOTAL SCORE: 100.0%

LOGGING & DEBUGGING / EXPLORE / HOTS


Answered Questions :10 / 10
Your Score :  100.0%

PROBLEM

1  Which of the following genres does Log4j produce?

Which of the following genres does Log4j produce?


1)

Gospel music
2)

Avant-rock
3)

Logging Tool
4)

Action game
2  What license is Log4j distributed under?

What license is Log4j distributed under?


PROBLEM

1)

Apache License 2.0


2)

Closed Source server, GPL clientwrong


3)

Shareware
4)

Originally Proprietary, BSD license since 2000


3  Mention what are the three principal components of Log4j?

Mention what are the three principal components of Log4j?


1)

Loggers
2)

Appenders
3)

Layouts
4)

All of the listed options


4  Mention what are the different types of Appenders?

Mention what are the different types of Appenders?


1)

ConsoleAppender logs to standard output


2)

FileAppender prints logs to some file


3)

Rolling file appender to a file with maximum size


4)

All of the listed options


5  The ___________ ignores any logging messages that have a level lower than the threshold level.

The ___________ ignores any logging messages that have a level lower than the threshold level.
1)

Appender
PROBLEM

2)

Logger
3)

Layout
4)

All of the listed options


6  Grails application logging can be configured using

Grails application logging can be configured using


1)

creating custom appenders


2)

logging levels
3)

console output
4)

All of the listed options


7  Who developed Log4j?

Who developed Log4j?


1)

Mozilla Foundation
2)

Apache Software Foundation


3)

Sony Creative Software


4)

Blender Foundation
8  Which of the following is correct about Appender object?

Which of the following is correct about Appender object?


1)

This is a lower-level layer of log4j architecture which provides Appender objects.


2)

The Appender object is responsible for publishing logging information to various preferred destinations such as a database, file, co
PROBLEM

3)

Both of the listed options


4)

None of the listed options


9  ________ is an appender that logs to standard output

________ is an appender that logs to standard output


1)

jdbc
2)

console
3)

file
4)

rollingFile
10  What is the purpose of immediateFlush configuration of FileAppender?

What is the purpose of immediateFlush configuration of FileAppender?


1)

output stream to the file being flushed with each append operation.
2)

to set the platform-specific encoding scheme.


3)

to set the threshold level for this appender.


4)

to set the name of the log file.


T3 - Topic 3... / Logging & Debugging / Explo...
CONGRATS!!!
Congrats !!! You have successfully completed the session :) ...

TOTAL SCORE: 100.0%

LOGGING & DEBUGGING / EXPLORE / MANDATORY


Answered Questions :15 / 15
Your Score :  100.0%

PROBLEM

1  Log4J also has the following logging level :

Log4J also has the following logging level :


1)

fatal
2)

error
3)

warning
4)

debug
2  Log4J configuration parameters are specified inside ________ file

Log4J configuration parameters are specified inside ________ file


1)

Conf.groovy
2)

Config.groovy
3)

Log.groovy
4)

None of the listed options


3  What is the purpose of M character used in the conversionPattern of PatternLayout object?
PROBLEM

What is the purpose of M character used in the conversionPattern of PatternLayout object?


1)

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?

Which of the following is correct about layout object in Appender?


1)

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?

Which of the following is correct about log4j?


1)

It is thread-safe.
2)

It is optimized for speed.


3)

It is based on a named logger hierarchy.


4)

All of the listed options


6  Which of the following method of logger print a log message in info mode?

Which of the following method of logger print a log message in info mode?
PROBLEM

1)

public void debug(Object message)


2)

public void error(Object message)


3)

public void fatal(Object message)


4)

public void info(Object message)


7  Which of the following level designates all levels including custom levels?

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?

What is the purpose of driver configuration of JDBCAppender?


1)

to set the driver class to the specified string.


PROBLEM

2)

to set the database password.


3)

to specify the SQL statement to be executed every time a logging event occurs.
4)

None of the listed options


10  Individual layout subclasses implement _________ method for layout specific formatting.

Individual layout subclasses implement _________ method for layout specific formatting.
1)

public abstract String format(LoggingEvent event)


2)

public abstract String getContentType()


3)

public abstract String format(LayoutEvent event)


4)

public abstract String format(AppenderEvent event)


11  What is the purpose of c character used in the conversionPattern of PatternLayout object?

What is the purpose of c character used in the conversionPattern of PatternLayout object?


1)

Used to output the category of the logging event.


2)

Used to output the fully qualified class name of the caller issuing the logging request.
3)

Used to output the date of the logging event.


4)

Used to output the file name where the logging request was issued.
12  A program must never be ________

A program must never be ________


1)

understandable
2)

accurate
PROBLEM

3)

long
4)

portable
13  _______ is a method that creates a mock object from a domain class.

_______ is a method that creates a mock object from a domain class.


1)

mockForConstraints
2)

mockForConstraintsTests
3)

mockConstraintsTests
4)

mockConstraints
14  Say TRUE or FALSE Logger uses the Layout objects and the conversion pattern associated with them ...

Say TRUE or FALSE


Logger uses the Layout objects and the conversion pattern associated with them to format the logging informatio
1)

TRUE
2)

FALSE
15  Which of the following is correct about filter in Appender?

Which of the following is correct about filter in Appender?


1)

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)

The filter is required to control the filtration of the log messages.


4)

Appender can have a filter associated with it independent of the logger level.

What symbol do flowcharts end with?


1)oval
2)Terminal
3)rectangle
4)diamond
Find the correct order
To test if a number is palindrome or not, do the following steps:
1. If both are the same then print palindrome number else print not a palindrome number.
2. Get the number from a user.
3. Compare it with the number entered by the user.
4. Reverse it.
1)1, 4, 3, 2
2)2, 4, 3, 1
3)2, 3, 4, 1
4)4, 2, 1, 3

Which of the following is correct pseudocode for find an average of n numbers


1)
1. Input the n numbers into the computer
2. Calculate the average by multiplying the numbers and add the answer by n
3. Display the average
2)
1. Input the n numbers into the computer
2. Calculate the average by adding the numbers and dividing the sum by 1
3. Display the average
3)
1. Input the n numbers into the computer
2. Calculate the average by multiplying the numbers and add the answer by 100
3. Display the average
4)
1. Input the n numbers into the computer
2. Calculate the average by adding the numbers and dividing the sum by n
3. Display the average
Find a way for a Knight to visit every square on a board exactly once.
which of the following is correct for above flowchart
1)Are all cells not filled?
2)Are 3 cells filled?
3)Are all cells filled?
4)Are 8 cells filled?

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

Which of the following is correct?


Algorithms can be represented with ____
1)
language
2)
system
3)
syntax
4)
pseudo codes
What is missing from the flowchart

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

Fill up the blank spaces in the below Pseudocode to compute Factorial of a


number :
Step 1: Declare N and F as integer variable.
Step 2: Initialize F=1.
Step 2: Enter the value of N.
Step 3: Check whether N>0, if not then F=1.
Step 4: If yes then, F=F*N
Step 5: Decrease the value of N by 1 .
Step 6: Repeat step ____ and _____ until N=0.
Step 7: Now print the value of F.
Type the steps in the below text box, separated by a space. (For eg: 2 3)

Correct Answer: 4 5
Fill up the missing content in decision box to print Hello World 10 times.

1)Is count < 10


2)Is count <= 10
3)Is count < 11
4)None of the listed options
At the end of the flow chart the number placed in which of the following boxes
will remain unchanged

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

Write an algorithm to generate the Fibonacci Sequence upto to the given


number.

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

Write an algorithm to display the number of digits in a given number.


NumberOfDigits(number):
SET count=0
WHILE (number > 0):
SET count=count+1 and SET number=number/10
ENDWHILE
PRINT count
END

Maximum element in an array

Write an algorithm to display the maximum element in an array.

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

Sum of elements in an array

Write an algorithm to find the sum of the numbers in an array.

Search Element

Write an algorithm to search for an element in an array.

Count of Even and Odd Elements

Write an algorithm to display the number of even and odd elements in an


array.
SWAPING TWO NUMBERS
SWAPPING OF TWO ROLL NUMBERS
Rita was about to award 2 students with 1st and 2nd prize. But unfortunately, he
interchanged both of them. Consider the first number as the roll number of the student
who won a the1st prize and the next roll number of the student who won 2nd prize. Can
you write a program to swap two numbers without using a third variable?
 Input format  :
  Input consists of two integers.
 Output format :
  Output consists of two integers which are swapped.
Sample Input and Output :
[ All text of bold corresponds to input ]
Enter values:
15
2
Values after swapping:
2
15
EVEN OR ODD

Even or Odd

Write a program to check whether the given number is 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
 

Write a program to reverse the digits of a number.

(Note : Please use initialize statement before input statement)


 

Input format :
Input consists of an integer value.

Output format :
Output consists of the reverse of the given number.

[ Refer Sample Input and Output for further details ]


 

Sample Input and Output 1 :


[ All text of bold corresponds to Input and the rest output]
Enter the number :
5642
Reverse of the number is 2465
 

Sample Input and Output 1 :


Enter the number :
144
Reverse of the number is 441
 

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

Write an algorithm to finf the Greatest Common Divisor of two


numbers.

How to execute a java project inside the Eclipse


1)
Run As -> Run Applet
2)
Run As -> Run on Server
3)
Run As -> Java Project
4)
Run As -> Java Application
What is the full form of JRE?
1)
Java Runtime Eclipse
2)
Java Run Environment
3)
Java Runtime Environment
4)
None of the mentioned options

1)
public class Main {

public static void main(String[] args){

Write your code//

}
2)
public class Main {

public static void main(String[] args){

Write your code// comments

}
3)
public class Main {
public static void main(String[] args) {

//Write your code

}
4)
public class Main {

public static void main(String[] args) {

Write your code

}
Select the appropriate code where 'Write your code' should be commented using multi line
comments
1)
public class Main {

public static void main(String[] args){

//Write

//your

//code

}
2)
public class Main {

public static void main(String[] args){


/* Write

your

code*/

}
3)
public class Main {

public static void main(String[] args){

*/Write

your

code/*

}
4)
public class Main {

public static void main(String[] args){

*/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

public void main(String args[])

System.out.println("Hello World");

}
2)
class HelloWorld

public static void main(String args[])

System.out.println("Hello World")

}
3)
class HelloWorld

public static void main(String args[])

System.out.println("Hello World");

}
4)
class HelloWorld

public static void main(String args[])

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

Can bytecode run directly on the machine?

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

Where does the execution starts in java program?


1)Main function
2)main function
3)Main class
4)imports
Java platform is associated with _________ and ______________
1)JVM and JDK
2)JVM and Java core libraries
3)JVM and JRE
4)JRE and Java core libraries
Which errors cannot be detected by a compiler nor by the JVM?
1)compilation errors
2)run time errors
3)logical errors
4)None of the mentioned options
State True or False
Comment Lines can be used to prevent some code lines from being executed.
1)TRUE
2)FALSE
Select the feature that is not applicable for Java
1)Strongly-typed programming language
2)Interpreted and compiled language
3)Platform dependent
4)Automatic memory management
What is the full form of JDK?
1)Java Diagram Kit
2)Java Demonstration Kit
3)Java Design Kit
4)Java Development Kit
Java is case insensitive
1)TRUE
How is a single line comment created in Java?
1)\\
2)*
3)//
4)/*
Which error occurs when the program is running?
1)compilation errors
2)run time errors
3)logical errors
4)None of the mentioned options
The standard java
compiler

Correct Answer: javac

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)Java Visual Machine


2)Java Virtual Machine
3)JaVa Machine
4)JAVA Member
Which includes JRE to execute the Java program?
1)JDK
2)JVM
3)Library Classes
4)None of the mentioned options
The ________ defines where the Java compiler and Java runtime look for .class
files to load
1)javac -jar jarName.jar
2)java -jar
3)java -jar jarName.jar
4)java jarName.jar
Where does the Java compiler will be available?
1)JVM
2)JRE
3)None of the mentioned options
4)JDK
What does java compiler do?

1)Converts Java code to byte code


2)Converts Java code to machine code
3)All of the mentioned options
4)None of the mentioned options
Advanced Password Strength
Using regex pattern, find the strength of the password based on the rules given below.      

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'.

Use appropriate getters and setters.

Create a class Main.java

Create another class file Customer.java with following data members.

Data Type Variable Name

String name
String password

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 number of customers


3
Enter name of customer1
Praveen
Enter the password
praveen
Enter name of customer2
Madhan
Enter the password
Madhan12@#
Enter name of customer3
Jimesh
Enter the password
Jimeshshar
Customer name: Praveen, password: praveen
Password strength is weak
Customer name: Madhan, password: Madhan12@#
Password strength is good
Customer name: Jimesh, password: Jimeshshar
Password strength is ok

public class Customer {


String name;
String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

public static void main(String[] args) {


// TODO Auto-generated method stub

Scanner sc=new Scanner(System.in);


List<Customer> cus=new ArrayList<Customer>();

System.out.println("Enter number of customers");


int count=sc.nextInt();
Customer c=new Customer();
for(int i=0;i<count;i++)
{

System.out.println("Enter name of customer"+(i+1));


String userName=sc.next();
System.out.println("Enter the password");
String password=sc.next();

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");'

Name the output file as 'call.csv'.

Sample Input and Output:


[All text in bold are input and the remaining are output]

 
Enter the mobile number

8972007627

Enter the duration (in Seconds)


5

Do you want to add another call history ?

yes

Enter the mobile number

8976543289

Enter the duration (in Seconds)

Do you want to add another call history ?

no

 
 
Output(call.csv):

8972007627,5

8976543289,6

 import java.io.*;
import java.util.Scanner;

public class Main {


public static void main(String [] args) {

String fileName = "call.csv";


Scanner sc= new Scanner(System.in);
try {

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

Data Type Variable Name

String name

String address
Integer age

String mobileNumber

Methods in class Customer

Method Name Method description

displayCustomer() To display the details of the customer.

Use Appropriate Getters & Setters for Customer class.


 

Create a class SeniorCitizenCustomer which extends the class Customer.


Methods in class SeniorCitizenCustomer

Method Name Method description Return Type

To calculate the payment


generateBillAmount(amount) amount Double
where the discount is 12% .

Create a class PrivilegeCustomer which extends the class Customer.


Methods in class PrivilegeCustomer

Method Name Method description Return Type

To calculate the payment


generateBillAmount(amount) amount Double
where the discount is 30% .

 
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:

Refer sample input and output for formatting specifications.

[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

Sample Input and Output 2:


1)Privilege Customer
2)SeniorCitizen Customer
Enter Customer Type
3
Invalid Customer Type

public class Customer {


private String name;
private String address;
private Integer age;
private String mobileNumber;

public Customer() {
// TODO Auto-generated constructor stub
}

public Customer(String name, String address, Integer age, String mobileNumber) {


super();
this.name = name;
this.address = address;
this.age = age;
this.mobileNumber = mobileNumber;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getAddress() {


return address;
}

public void setAddress(String address) {


this.address = address;
}

public Integer getAge() {


return age;
}

public void setAge(Integer age) {


this.age = age;
}

public String getMobileNumber() {


return mobileNumber;
}

public void setMobileNumber(String mobileNumber) {


this.mobileNumber = mobileNumber;
}

void displayCustomer() {
//fill your code here
}
}

import java.text.DecimalFormat;

public class PrivilegeCustomer extends Customer{

DecimalFormat format = new DecimalFormat("0.00");

private Double amount;

public final Double getAmount() {


return amount;
}

public final void setAmount(Double amount) {


this.amount = amount;
}

//To calculate the payment amount where the discount is 30%


double generateBillAmount(Double amount) {
amount = amount - (0.3 * amount);
return amount;
}

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;

public class SeniorCitizenCustomer extends Customer{

DecimalFormat format = new DecimalFormat("0.00");

private Double amount;

public final Double getAmount() {


return amount;
}

public final void setAmount(Double amount) {


this.amount = amount;
}

//To calculate the payment amount where the discount is 12%


double generateBillAmount(Double amount) {
return amount - (0.12 * amount);

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;

public class Main {

public static void main(String[] args) {


DecimalFormat format = new DecimalFormat("0.00");

Scanner sc = new Scanner(System.in);

Customer customer;

System.out.println("1)Privilege Customer\n2)SeniorCitizen Customer\nEnter Customer


Type");
int choice = sc.nextInt();

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();

System.out.println("Enter The Age");


Integer age = sc.nextInt();
sc.nextLine();
System.out.println("Enter The Address");
String address = sc.nextLine();

System.out.println("Enter The Mobile Number");


String mobileNumber = sc.nextLine();

System.out.println("Enter The Purchased Amount");


Double amount = sc.nextDouble();

switch (choice) {
case 1:

PrivilegeCustomer privilageCust = new PrivilegeCustomer();


privilageCust.setName(name);
privilageCust.setAddress(address);
privilageCust.setAge(age);
privilageCust.setMobileNumber(mobileNumber);
privilageCust.setAmount(amount);
privilageCust.displayCustomer();
break;

case 2:

SeniorCitizenCustomer seniorCitiCust = new SeniorCitizenCustomer();


seniorCitiCust.setName(name);
seniorCitiCust.setAddress(address);
seniorCitiCust.setAge(age);
seniorCitiCust.setMobileNumber(mobileNumber);
seniorCitiCust.setAmount(amount);
seniorCitiCust.displayCustomer();
break;

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.

Create a class Transaction with private member variables.


DataType Variable Name

String accountNumber

Double amount

Include apporapiate getter and setters for above class.


Include appropriate default and parameterized constructors for the above class.

Include with the following method in class Transaction

Return Type method name

Boolean validate(transactionAmount)

In validate method if the transaction amount is greater than current balance or if the


current balance is in minimal balance (500) then throw a manual exception then display
"Insufficient Balance". Otherwise return true. Use finally to display the available balance
after transaction completed.
 

Sample Input and Output :

Enter the transaction details


Enter the account number
123456
Enter the available amount
5000
Enter the transaction amount
500
Do you want to enter more ?(yes/no)
yes
Enter the transaction amount
1000
Do you want to enter more ?(yes/no)
yes
Enter the transaction amount
2000
Do you want to enter more ?(yes/no)
yes
Enter the transaction amount
800
Do you want to enter more ?(yes/no)
yes
Enter the transaction amount
850
Insufficient Balance
Your available balance 700.0
 

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.

Create a class Account with following attributes

Data type Variable name

String accountName

String accountType

Date dob

Include a default and parameterized constructor with all the variables.

Include the following methods in the class Account.

Method name Method description

void display() This method is used to display the details

boolean validateDOB(String This method is used to validate the given date of birth and return true
dob) based on the validation.

Sample Input and Output:


[All text in bold corresponds to input and the rest corresponds to output]
Enter the Customer details
Enter the name
Sastha
Enter account type
Savings
Enter date-of-birth
02/13/1993
Wrong Format(eg:01/01/2015)
Enter date-of-birth
35/02/1993
Wrong Format(eg:01/01/2015)
Enter date-of-birth
25/02/1993

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;

public class Account {


String accountName;
String accountType;
Date dob;
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Account() {
super();
// TODO Auto-generated constructor stub
}
public Account(String accountName, String accountType, Date dob) {
super();
this.accountName = accountName;
this.accountType = accountType;
this.dob = dob;
}
void display() throws ParseException{

System.out.println("\nAccount Details");
System.out.println("Name : " + getAccountName());
System.out.println("Type : " + getAccountType());

SimpleDateFormat outputbirthformat = new SimpleDateFormat("MMM-dd-yyyy");

String dob = outputbirthformat.format(getDob());


System.out.println("D.O.B : " + dob);

boolean validateDOB(String dob) {


boolean result = false;
String[] numbers = dob.split("/");
int day = Integer.parseInt(numbers[0]);
int month = Integer.parseInt(numbers[1]);

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 {

public static void main(String[] args) throws ParseException{

Scanner sc = new Scanner(System.in);


SimpleDateFormat inputbirthformat = new SimpleDateFormat("dd/MM/yyyy");

System.out.println("Enter the Customer details");


System.out.println("Enter the name");

String name = sc.next();

System.out.println("Enter account type");


String accType = sc.next();

Account ac = new Account();


boolean status = false;
String dob;

do{
System.out.println("Enter date-of-birth");
dob = sc.next();

status = ac.validateDOB(dob);

}while(status != true);

Date date1 = inputbirthformat.parse(dob);


Account pac = new Account(name,accType,date1);
pac.display();
// Date date2 = outputbirthformat.parse(dob);
// System.out.println("D.O.B : " + date2);

Interface Practical Problem 2


 
All the banks will have their own rules to be followed but there are few areas where
every bank has to follow the RBI rules. So when RBI changes any condition it must be
followed by all other banks.

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 the class HDFC which extends the class RBI .

Use Appropriate Getters Setters for above classes.

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.]

Sample Input and Output 1:

Select the Bank Name


1.ICICI
2.HDFC
1
Enter the Holder Name
Madhan Kumar
Enter the Account Number
218463
Enter the Previous Credit Score
652
Enter the Amount to be Paid
500
Amount Paid Successfully !!!
Hi,Madhan Kumar
You have gained 50.00 credit score for the payment of 500.0
Your Total Credit Score is 702.00

Sample Input and Output 2:

Select the Bank Name


1.ICICI
2.HDFC
2
Enter the Holder Name
Raina
Enter the Account Number
62354953
Enter the Previous Credit Score
6015
Enter the Amount to be Paid
15600
Amount Paid Successfully !!!
Hi,Raina
You have gained 1560.00 credit score for the payment of 15600.0
Your Total Credit Score is 7575.00

Sample Input and Output 3:

Select the Bank Name


1.ICICI
2.HDFC
6
Invalid Bank type
 

import java.text.DecimalFormat;public class HDFC extends RBI {


private String accountNumber;
private double creditScore;
private String holderName;
static double CREDIT;
public HDFC(String accountNumber, double creditScore, String holderName) {
super();
this.accountNumber = accountNumber;
this.creditScore = creditScore;
this.holderName = holderName;
}
public static double getCREDIT() {
return CREDIT;
}
public static void setCREDIT(double cREDIT) {
CREDIT = cREDIT;
}public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public double getCreditScore() {
return creditScore;
}
public void setCreditScore(double creditScore) {
this.creditScore = creditScore;
}
public String getHolderName() {
return holderName;
}
public void setHolderName(String holderName) {
this.holderName = holderName;
}
private static DecimalFormat df = new DecimalFormat("0.00");
private static DecimalFormat dg = new DecimalFormat("0.0");
public double calculateCreditScore(double amount) {
CREDIT=amount/10;
creditScore=creditScore+CREDIT;
return creditScore;
}
public void display() {
System.out.println("Amount Paid Successfully !!!");
System.out.println("Hi,"+getHolderName());
System.out.println("You have gained "+df.format(CREDIT)+" credit score for the payment of
"+dg.format(CREDIT*10));
System.out.println("Your Total Credit Score is "+df.format(getCreditScore()));
}
}

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;
}}}

public interface Bank {


abstract double calculateCreditScore();
}

public class RBI implements Bank{


private String accountNumber;
private double creditScore;
private String holderName;
static double CREDIT;

public double calculateCreditScore() {


return creditScore;
}
public void display() {
//fill your code here
}
}

import java.text.DecimalFormat;public class ICICI extends RBI {


private String accountNumber;
private double creditScore;
private String holderName;
static double CREDIT;
public ICICI(String accountNumber, double creditScore, String holderName) {
super();
this.accountNumber = accountNumber;
this.creditScore = creditScore;
this.holderName = holderName;
}
public static double getCREDIT() {
return CREDIT;
}
public static void setCREDIT(double cREDIT) {
CREDIT = cREDIT;
}public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public double getCreditScore() {
return creditScore;
}
public void setCreditScore(double creditScore) {
this.creditScore = creditScore;
}
public String getHolderName() {
return holderName;
}
public void setHolderName(String holderName) {
this.holderName = holderName;
}
private static DecimalFormat df = new DecimalFormat("0.00");
private static DecimalFormat dg = new DecimalFormat("0.0");
public double calculateCreditScore(double amount) {
CREDIT=amount/10;
creditScore=creditScore+CREDIT;
return creditScore;
}
public void display() {
System.out.println("Amount Paid Successfully !!!");
System.out.println("Hi,"+getHolderName());
System.out.println("You have gained "+df.format(CREDIT)+" credit score for the payment of
"+dg.format(CREDIT*10));
System.out.println("Your Total Credit Score is "+df.format(getCreditScore()));
}
}
- Packages/Packages / Assess
If we don't want to override the existing attribute values, then which non-access
modifier will be used for an attribute.
1)
const
2)
final
3)
finalize
Error output streams are provided by which of the class
1)
util
2)
lang
3)
net
If we use any package name for the project, then the package statement should be
present in the ________line of source code file.
1)
last
2)
any
3)
first
Select the non-access modifiers
1)
private
2)
final
3)
finalize
public class Student{
public int data = 50;
public void msg(){
System.out.println("Hello");
}
}

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

Write an algorithm to generate the Fibonacci Sequence upto to the given


number.

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;

public class Main {


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = Integer.parseInt(s.nextLine());
int ct=0,n=0,i=1,j=1;
while(n<a) {
j=1;
ct=0;
while(j<=i) {
if(i%j==0){
ct++;
}
j++;
}
if(ct==2) {
System.out.printf("%d ",i);
n++;
}
i++;
}
}
}
Total Expenses for the Event
 
The prime functionality of an Event Management System is budgeting. An Event
Management System should estimate the total expenses incurred by an event and the
percentage rate of each of the expenses involved in planning and executing an event.
Nikhil, the founder of "Pine Tree" wanted to include this functionality in his company’s
Amphi Event Management System and requested your help in writing a program for the
same.
 
The program should get the branding expenses, travel expenses, food expenses and
logistics expenses as input from the user and calculate the total expenses for an event
and the percentage rate of each of these expenses.
 
Input Format:
First input is a int value that corresponds to the branding expenses.
Second input is a int value that corresponds to the travel expenses.
Third input is a int value that corresponds to the food expenses.
Fourth input is a int value that corresponds to the logistics expenses.
 
Output Format:
First line of the output should display the int value that corresponds to the total
expenses for the Event.
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 and Output:


Enter branding expenses
20000
Enter travel expenses
40000
Enter food expenses
15000
Enter logistics expenses
25000
Total expenses : Rs.100000.00
Branding expenses percentage : 20.00%
Travel expenses percentage : 40.00%
Food expenses percentage : 15.00%
Logistics expenses percentage : 25.00%
 
Additional Sample TestCases
Sample Input and Output 1 :
Enter branding expenses
855
Enter travel expenses
877779
Enter food expenses
5544
Enter logistics expenses
2256
Total expenses : Rs.886434.00
Branding expenses percentage : 0.10%
Travel expenses percentage : 99.02%
Food expenses percentage : 0.63%
Logistics expenses percentage : 0.25%

import java.util.Scanner;

import java.text.DecimalFormat;

class Main {

public static void main(String[] args) {

DecimalFormat df = new DecimalFormat("0.00");

Scanner sc = new Scanner(System.in);

System.out.println("Enter branding expenses");

int branding = sc.nextInt();

System.out.println("Enter travel expenses");

int travel = sc.nextInt();

System.out.println("Enter food expenses");

int food = sc.nextInt();

System.out.println("Enter logistics expenses");

int logistics = sc.nextInt();


double totalexpense = branding+food+travel+logistics;

double brandingper=branding*100/totalexpense;

double travelingper=travel*100/totalexpense;

double foodper=food*100/totalexpense;

double logisticsper=logistics*100/totalexpense;

System.out.println("Total expenses : Rs."+df.format(totalexpense));

System.out.println("Branding expenses percentage : "+df.format(brandingper)+"%");

//System.out.print("% \n");

System.out.println("Travel expenses percentage : " +df.format(travelingper)+"%");

//cimalFormat df1 = new DecimalFormat("#.##");

System.out.println("Food expenses percentage : "+df.format(foodper)+"%");

System.out.println("Logistics expenses percentage : " +df.format(logisticsper)+"%");

}
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{

Scanner sc=new Scanner(System.in);

int age=sc.nextInt();

if((age<15)||(age>60)){

System.out.println("Not Allowed");

}else{

System.out.println("Allowed");}

Character Pattern 3
 

Write a program to generate a rectangular pattern of stars.


*
**
***
****
*****
 

Input and Output Format:


Input consists of a single integer that corresponds to n, the number of rows.
 

Sample Input 1:
5
 

Sample Output 1:
*
**
***
****
*****
 

import java.util.*;

import java.io.*;

class Main{

public static void main(String[] args) throws Exception{

Scanner sc=new Scanner(System.in);

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 a class named ItemType with the following private member variables /


attributes.
Data Type Variable
String name
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 method

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.

Example of getters and setters

private String name;

public String getName( ) {


        return name;
}

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 and Output 1:


Enter the item type name
Catering
Enter the cost per day
25000.00
Enter the deposit
10000.50
Item type details
Name : Catering
CostPerDay : 25000.00
Deposit : 10000.50
 

import java.text.DecimalFormat;

public class ItemType {

private String name;

private double costPerDay,deposit;


public String getName() {

return name;

public void setName(String name) {

this.name = name;

public double getCostPerDay() {

return costPerDay;

public void setCostPerDay(double costPerDay) {

this.costPerDay = costPerDay;

public double getDeposit() {

return deposit;

public void setDeposit(double deposit) {

this.deposit = deposit;

public void display(){

DecimalFormat df=new DecimalFormat("0.00");

System.out.println("Item type details");

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{

public static void main(String[] args) throws Exception {

ItemType i = new ItemType();

Scanner sc = new Scanner(System.in);

System.out.println("Enter the item type name");

i.setName(sc.nextLine());

System.out.println("Enter the cost per day");

i.setCostPerDay(sc.nextDouble());

System.out.println("Enter the deposit");

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

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)

Include the following method in User class.


Method Description

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.

Input and Output Format


Refer sample input and output for formatting specifications.
All text in bold corresponds to the input 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

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 a class named Rectangle with the following private member variables /


attributes.
Data Type Variable
int length
int width

Include appropriate getters and setters.


Include 2 argument constructor. The order in which the argument should be passed
is Rectangle(int length, int width)

In the Rectangle class include the following methods.


Method Description
int area( )  This method computes the area of the rectange and returns it.
 This method displays the length and width of the rectangle. Display
void display( )
dimensions.
Rectangle dimensionChange(int
 This method changes the rectangle dimension by increasing the le
d)

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).]

Input and Output Format:


Refer sample input and output for formatting specifications.
[All text in bold correspondstoinput and the rest corresponds to output.]

Sample Input and Output 1:


Enter the length of the rectangle
5
Enter the width of the rectangle
6
Rectangle Dimension
Length:5
Width:6
Area of the Rectangle:30
Enter the new dimension
2
Rectangle Dimension
Length:10
Width:12
Area of the Rectangle:120

Problem Requirements:

Keyword Min Count Max Count

instanceof 1 -

public class Rectangle {

private int length;

private int width;

public Rectangle(int length, int width) {

super();

this.length = length;

this.width = width;

public int getLength() {

return length;

public void setLength(int length) {

this.length = length;

}
public int getWidth() {

return width;

public void setWidth(int width) {

this.width = width;

public int area() {

return (getLength()*getWidth());

public void display(){

System.out.println("Rectangle Dimension");

System.out.println("Length:"+getLength());

System.out.println("Width:"+getWidth());

Rectangle dimensionChange(int d){

length=d*getLength();

setLength(length);

width=d*getWidth();

setWidth(width);

return new Rectangle(length, width);

}
}

import java.util.Scanner;

import java.io.IOException;

public class Main {

public static void main(String[] args) throws Exception, IOException {

int length,width,area,d;

Rectangle rec;

Scanner sc=new Scanner(System.in);

System.out.println("Enter the length of the rectangle");

length=sc.nextInt();

System.out.println("Enter the width of the rectangle");

width=sc.nextInt();

Rectangle r=new Rectangle(length, width);

r.display();

area=r.area();

System.out.println("Area of the Rectangle:"+area);

System.out.println("Enter the new dimension");

d=sc.nextInt();

rec=r.dimensionChange(d);

if(rec instanceof Rectangle){}

rec.display();

area=rec.area();

System.out.println("Area of the Rectangle:"+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.

Hence create a class named Fraction with the following method.


 
Method Name Description
This method should display the
void printValue(int,int)                                   
fraction in simplest form.
 
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

public class Fraction {

public static void printValue (int num,int den) {

if (num <= 0) {

System.out.println(0);

else if (num < den) {

int gcd = getGCD(num,den);

System.out.println(num/gcd+"/"+den/gcd);

} else if (num > den) {

int rem = num % den;

int quo = (int) (num / den);

if (rem != 0) {

int gcd = getGCD(rem, den);

System.out.println(quo + " " + rem/gcd + "/" + den/gcd);

else {

System.out.println(quo);

}
else {

System.out.println(1);

private static int getGCD(int num, int den) {

int gcd = 1;

for (int i=Math.min(num, den); i>=2; i--) {

if ((num %i == 0) && (den %i == 0)) {

gcd = i;

break;

return gcd;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

int num = s.nextInt();

int den = s.nextInt();

Fraction f = new Fraction();

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 Input and Output 1:


Enter n :
3
Enter numbers : 
100
23
15
Enter strings : 
hi
hello
welcome
Displaying numbers
100
23
15
Displaying strings
hi
hello
welcome
 

Command Line Argument - Count


Write a program to accept strings as command line argument and print the number of
arguments entered.
Sample Input (Command Line Argument) 1:
Command Arguments

Sample Output 1:
Arguments :
Command
Arguments
Number of arguments is 2

Sample Input (Command Line Argument) 1:


Commands

Sample Output 2:
Arguments :
Commands
Number of arguments is 1
public class Main{

public static void main(String[] args){

int count=0;

System.out.println("Arguments :");

for(int a=0;a<args.length;a++)

System.out.println(args[a]);

count++;

System.out.println("Number of arguments is "+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

Sample Input and Output 2:


Enter the username 1
Jack
Do you want to continue?(y/n)
y
Enter the username 2
Jason
Do you want to continue?(y/n)
n
The Names entered are:
Jack
Jason

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);

System.out.println("The Names entered are:");


for(String s:list){
System.out.println(s);
}
}
}

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.

Input and Output format:


Refer to sample Input and Output for formatting specifications.

Sample Input and Output:


[All text in bold corresponds to the input and rest corresponds to output]

Enter the username


Ram
Do you want to continue?(Y/N)
Y
Enter the username
Christoper
Do you want to continue?(Y/N)
Y
Enter the username
Ahamed
Do you want to continue?(Y/N)
Y
Enter the username
Ahamed
Do you want to continue?(Y/N)
N
The unique number of usernames is 3

java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {

public static void main(String[] args){


//Your code here
String username, askForContinue;
Scanner sc = new Scanner(System.in);
Set<String> userSet = new HashSet<>();
do {
System.out.println("Enter the username");
username = sc.nextLine();
userSet.add(username);
System.out.println("Do you want to continue?(Y/N)");
askForContinue = sc.nextLine();
} while (askForContinue.equals("Y"));
System.out.println("The unique number of usernames is " + userSet.size());
}

}
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.

Sample Input and Output 1:


[All Texts in bold corresponds to the input and rest are output]

Enter the number of events:


3
Enter event details in CSV(Customer Name,Ticket Price,No of Seats Booked)
Pramod,100,5
Anamika,200,10
Priscilla,100,3
Ticket Price    Tickets Booked
100                 8
200                 10

import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Main {

public static void main(String[] args){


//fill your code here
String[] events;
String input;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of events:");
int noOfEvent = sc.nextInt();
sc.nextLine();
TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();
System.out.println("Enter event details in CSV(Customer Name,Ticket Price,No of Seats Booked)");
for(int i=0;i<noOfEvent;i++) {
input = sc.nextLine();
events = input.split(",");
String name = events[0];
Integer price = Integer.parseInt(events[1]);
Integer seatBooked = Integer.parseInt(events[2]);
if(map.containsKey(price)) {
Integer seat = map.get(price);

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.

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 Address with the following private attributes


Attributes Datatype
username String
addressLine1 String
addressLine2 String
pinCode Integer
Include appropriate getters and setters
Create default constructor and a parameterized constructor with arguments in order
Address(String username, String addressLine1, String addressLine2, Integer pinCode).

The Address class implements the comparable interface. Compare pin code, If Pincode


is the same then compare with addressLine1.

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]

Enter the number of users:


3
Enter user address in CSV(Username,AddressLine 1,AddressLine 2,PinCode)
Josh,Marina street,Chennai,646461
Martin,Mullai nagar,Salem,640002
Justin,Ambedkar road,Chennai,646461
User Details:
Martin,Mullai nagar,Salem,640002
Justin,Ambedkar road,Chennai,646461
Josh,Marina street,Chennai,646461

import java.util.*;
import java.io.*;

public class Main {


public static void main(String[] args){
//fill code here
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number of users:");
//int num = Integer.parseInt(sc.nextLine());
int num = sc.nextInt();
sc.nextLine();
System.out.println("Enter user address in CSV(Username,AddressLine 1,AddressLine 2,PinCode)");
//Address userAddress = new Address();
ArrayList<Address> address = new ArrayList<Address>();
for (int i = 0; i < num; i++) {
String info [] = sc.nextLine().split(",");
address.add(new Address(info[0],info[1],info[2],Integer.parseInt(info[3])));
}
Collections.sort(address);
System.out.println("User Details:");
for (Address addr : address)
{
System.out.println(addr.getUsername()+"," + addr.getAddressLine1()+"," + addr.getAddressLine2()+"," + addr.getPinCode());
}
}
}

public class Address implements Comparable<Address>{


private String username;
private String addressLine1;
private String addressLine2;
private int pinCode;
Address(){
}
Address(String username, String addressLine1, String addressLine2, Integer pinCode) {
this.username = username;
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.pinCode = pinCode;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public int getPinCode() {
return pinCode;
}

public void setPinCode(int pinCode) {


this.pinCode = pinCode;
}

public int compareTo(Address address){

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.

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.

So let's create a class User with the following private attributes,


Attribute Data type
name String
mobileNumber String
username String
password String

Include appropriate getter/setter, default constructor and parameterized constructor.

Override toString() and print the details in a tabular format.

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.

Hint: Sort the user details based on the name of the user.

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.

Sample Input and Output 1:


[All Texts in bold corresponds to the input and rest are output]

Enter the number of users:


3
Enter the details of User 1
Jack,12345,Jack,Jack
Enter the details of User 2
Jane,13579,Jane,Jane
Enter the details of User 3
John,24680,John,John
The user details in reverse order:
Name           Mobile number  
John           24680          
Jane           13579          
Jack           12345
 

public class User implements Comparable<User> {


//write your code here
private String name;
private String mobileNumber;
private String username;
private String password;

public User(String name, String mobileNumber, String username, String password) {


this.name = name;
this.mobileNumber = mobileNumber;
this.username = username;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int compareTo(User user){

return (this.name.compareTo(user.name));

@Override
public String toString() {

return String.format("%-15s%-15s",getName(),getMobileNumber());

}
}

------------------------------
import java.io.*;
import java.util.*;

public class Main {


public static void main(String args[]) {
//write your code here
System.out.println("Enter the number of users:");
Scanner sc = new Scanner(System.in);

ArrayList<User> UserList = new ArrayList<User>();


try {
int num = sc.nextInt();
sc.nextLine();

for (int i = 0; i < num; i++)


{
System.out.println("Enter the details of User " + (i+1));
String user_info = sc.nextLine();
String user[] = user_info.split(",");
UserList.add(new User(user[0], user[1], user[2], user[3]));

}
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");

for (User user: UserList){


System.out.println(user.toString());
}
}
}
}

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.

Refer sample input output form input output format

Sample Input and Output:


Enter a integer :
15
Enter a string :
Hello World Generic class
Integer Value :15
String Value :Hello World Generic class

public class Item <T> {

private T t;

public void set(T t) {


this.t = t;
}

public T get() {
return t;
}

}
-------------------

import java.util.Scanner;
import java.io.*;

public class Main {


public static void main(String[] args) throws IOException {

Scanner sc = new Scanner(System.in);

Item<Integer> integerItem = new Item<Integer>();


Item<String> stringItem = new Item<String>();

System.out.println("Enter a integer :");

integerItem.set(sc.nextInt());
sc.nextLine();

System.out.println("Enter a string :");


stringItem.set(sc.nextLine());
System.out.println("Integer Value :" + integerItem.get());

System.out.println("String Value :" + stringItem.get());

}
}

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.

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 Stall with the following private attributes.


Attributes Datatype
name String
detail String
type String
ownerName String

Include getters and setters.


Create a default and Parameterized constructors.
Format for the parameterized constructor is Stall(String name, String detail, String type,
String ownerName)

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.

Sample Input and Output:


[All text in bold corresponds to the input and rest corresponds to the output]

Enter the number of stall details


5
Enter the stall 1 detail
test1,detail,type,johndoe
Enter the stall 2 detail
test2,detail1,type,janedoe
Enter the stall 3 detail
Food court,fruits and juice,food,Mahesh
Enter the stall 4 detail
Book,novels,sale,Rajesh
Enter the stall 5 detail
test,data,data,data
Name            Detail               Type            Owner name
Food court      fruits and juice     food            Mahesh
Book            novels               sale            Rajesh
 

sort() a List of Objects


 
 Write a program to take hall objects as input in the list and sort them in the order of
their costPerDay using sort() method of the comparable interface. Then display them in
tabular form.

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 Hall with the following private attributes,
Attribute Data type
name String
contactNumber String
costPerDay Double
ownerName String
 

Include appropriate getter/setter, default and parameterized constructor.

Override toString() and print the details in a tabular format. And implement comparable


interface in the class.

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.

Sample Input and Output 1:

Enter the number of halls:


3
Enter the details of hall 1
SDH hall,12345,12000,Jane
Enter the details of hall 2
SRT hall,13579,20000,John
Enter the details of hall 3
XUV hall,24680,15000,Jack
Sorted Order (from the least expensive to the most):
Name           Contact number Cost per day   Owner name     
SDH hall       12345          12000.0        Jane           
XUV hall       24680          15000.0        Jack           
SRT hall       13579          20000.0        John   

Sample Input and Output 2:

Enter the number of halls:


4
Enter the details of hall 1
ABC hall,12345,13000,John
Enter the details of hall 2
STR hall,13579,25000,Jane
Enter the details of hall 3
DFG hall,24680,10000,Jack
Enter the details of hall 4
JKL hall,67890,20000,Joe
Sorted Order (from the least expensive to the most):
Name           Contact number Cost per day   Owner name     
DFG hall       24680          10000.0        Jack           
ABC hall       12345          13000.0        John           
JKL hall       67890          20000.0        Joe            
STR hall       13579          25000.0        Jane           
 

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.

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 Seat with following private variables.


Attributes Datatype
section Character
number Integer
booked Boolean
Include getters and setters.
Create a default and Parameterized constructors.
The format for the parameterized constructor is Seat(Character section, Integer
number,Boolean booked).

The Seat class has the following methods


Method name Description
This method gets the number of rows and seats per
static List<List<Seat>> generateSeats(int rows,int seat)
It returns a List of seat List.
This method accepts the List of List of Seats and St
static void book(List<List<Seat>> seat,String seats)
It changes the booked variable to true for seats to b

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:

Enter the number of rows


5
Enter the number of seats per row
5
Enter the seats to book in CSV format
A1,B2,C4,D3
Seats
-- A2 A3 A4 A5 
B1 -- B3 B4 B5 
C1 C2 C3 -- C5 
D1 D2 -- D4 D5 
E1 E2 E3 E4 E5 
 
Email Search
 
In your application let’s dive deep into Set and explore its inbuilt functions. In this
problem experiment with containsAll() method. Write a program to search all the email
addresses which are given as CSV format.

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".

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 Email address
[email protected]
Do you want to Continue?(yes/no)
yes
Enter Email address
[email protected]
Do you want to Continue?(yes/no)
yes
Enter Email address
[email protected]
Do you want to Continue?(yes/no)
yes
Enter Email address
[email protected]
Do you want to Continue?(yes/no)
no
Enter the email addresses to be searched separated by comma
[email protected],[email protected]
Email addresses are present

Sample Input and Output 2:


Enter Email address
[email protected]
Do you want to Continue?(yes/no)
yes
Enter Email address
[email protected]
Do you want to Continue?(yes/no)
no
Enter the email addresses to be searched separated by comma
[email protected],[email protected]
Email addresses are not present
 

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:

Enter the count of booked tickets:


On Day 1
20,25,30,35
On Day 2
20,20,20,20
On Day 3
15,25,35,20
On Day 4
50,60,40,75
On Day 5
85,88,93,78
Enter the day to know its remaining ticket count:
5
Remaining tickets:[15, 12, 7, 22]
Do you want to continue?(y/n)
y
Enter the day to know its remaining ticket count:
2
Remaining tickets:[80, 80, 80, 80]
Do you want to continue?(y/n)
y
Enter the day to know its remaining ticket count:
4
Remaining tickets:[50, 40, 60, 25]
Do you want to continue?(y/n)
n
 

Min() and Max()


 
In our fair, we have decided to announce one lucky winner in many who attends the
events. We want the lucky winner as the one who spends the most in our events. So
write a program to find the minimum and maximum spenders from the list of visitors
who attended our events along with the money they spent in the events. Use min and
max functions.

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 TicketBooking with following private attributes which implements the
Comparable interface
Attributes Datatype
customerName String
price Integer
Include appropriate getters and setters
Create default constructor and a parameterized constructor with arguments in
order TicketBooking(String customerName, Integer price) and overrides the compare
method.

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.

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
username String
password String
Include appropriate getters and setters
Create default constructor and a parameterized constructor with arguments in
order User(String username, String password).

Include following methods


Method Description
This method takes the source list(user list) and
List<User> backUp(List<User>dest , List<User> source) destination list(blank list) for back up.
It returns a list with user details backed up.

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.

Create a class called Address with the following private attributes.


 

Attributes Datatype
addressLine1 String
addressLine2 String
city String
state String
pincode Integer

Include appropriate getters and setters.


Include default and parameterized constructor for the class.
Format for the Parameterized Constructor Address(String addressLine1, String
addressLine2, String city,
String state, Integerpincode)

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:

First line corresponds to number of address inputs 'n'


next n lines consists of 'n' address details in CSV format
n+1th line consists of state input
n+2nd line consists of city input

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:   

Enter the number of address


4
Enter the address 1 detail
5/15 7th lane,RK nagar,Madurai,Tamil nadu,625001
Enter the address 2 detail
1/45 8th street,KK nagar,Chennai,Tamil nadu,600021
Enter the address 3 detail
3rd street,KRK nagar,Visak,Andhrapradesh,745601
Enter the address 4 detail
22nd lane,RR nagar,Chennai,Tamil nadu,600028
Enter the state to be searched
Tamil nadu
Enter the city to be searched
Madurai
Line 1          Line 2          City            State           Pincode
5/15 7th lane   RKnagar        Madurai         Tamil nadu      625001
 

\
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.

Input Output Format:


Input consists of a single integer corresponding to the number of elements in the arrays.
Refer Sample Input Output for output format.

Sample Input and Output:


Enter a number :
6
Enter the elements of the integer array
123456
Enter the elements of the double array
1.1 2.2 3.3 4.4 5.5 6.6
Enter the elements of the character array
ancdef
Integer array contains:
123456
Double array contains:
1.1 2.2 3.3 4.4 5.5 6.6
Character array contains:
ancdef
Basic Elements of Java / Practice / Mandatory
Customized Welcome Message
 
Nikhil, the founder of “Pine Tree” company wished 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 display customized welcome messages by
taking Customers’ name as input. Help Nikhil on the task.
 
Input Format:
First line of the input is a string that corresponds to a Customer’s name. Assume that
the maximum length of the string is 50.

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.]

Sample Input and Output:


Enter your name
Beena
Hello Beena ! Welcome to Amphi Event Management System

import java.util.Scanner;
class Main {
public static void main(String[] args) {

Scanner sc=new Scanner(System.in);


System.out.println("Enter your name");
String name=sc.nextLine();
int n=name.length();
if(n<=50)
{
System.out.println("Hello "+name+" ! Welcome to Amphi Event Management System");
}
}
}
Total Expenses for the Event
 
The prime functionality of an Event Management System is budgeting. An Event
Management System should estimate the total expenses incurred by an event and the
percentage rate of each of the expenses involved in planning and executing an event.
Nikhil, the founder of "Pine Tree" wanted to include this functionality in his company’s
Amphi Event Management System and requested your help in writing a program for the
same.
 
The program should get the branding expenses, travel expenses, food expenses and
logistics expenses as input from the user and calculate the total expenses for an event
and the percentage rate of each of these expenses.
 
Input Format:
First input is a int value that corresponds to the branding expenses.
Second input is a int value that corresponds to the travel expenses.
Third input is a int value that corresponds to the food expenses.
Fourth input is a int value that corresponds to the logistics expenses.
 
Output Format:
First line of the output should display the int value that corresponds to the total
expenses for the Event.
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 and Output:


Enter branding expenses
20000
Enter travel expenses
40000
Enter food expenses
15000
Enter logistics expenses
25000
Total expenses : Rs.100000.00
Branding expenses percentage : 20.00%
Travel expenses percentage : 40.00%
Food expenses percentage : 15.00%
Logistics expenses percentage : 25.00%
 

Additional Sample TestCases


Sample Input and Output 1 :
Enter branding expenses
855
Enter travel expenses
877779
Enter food expenses
5544
Enter logistics expenses
2256
Total expenses : Rs.886434.00
Branding expenses percentage : 0.10%
Travel expenses percentage : 99.02%
Food expenses percentage : 0.63%
Logistics expenses percentage : 0.25%

import java.util.Scanner;
import java.text.DecimalFormat;
class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("0.00");

Scanner sc = new Scanner(System.in);


System.out.println("Enter branding expenses");
int branding = sc.nextInt();
System.out.println("Enter travel expenses");
int travel = sc.nextInt();
System.out.println("Enter food expenses");
int food = sc.nextInt();
System.out.println("Enter logistics expenses");
int logistics = sc.nextInt();
double totalexpense = branding+food+travel+logistics;
double brandingper=branding*100/totalexpense;
double travelingper=travel*100/totalexpense;
double foodper=food*100/totalexpense;
double logisticsper=logistics*100/totalexpense;
System.out.println("Total expenses : Rs."+df.format(totalexpense));
System.out.println("Branding expenses percentage : "+df.format(brandingper)+"%");
//System.out.print("% \n");
System.out.println("Travel expenses percentage : " +df.format(travelingper)+"%");
//cimalFormat df1 = new DecimalFormat("#.##");
System.out.println("Food expenses percentage : "+df.format(foodper)+"%");
System.out.println("Logistics expenses percentage : " +df.format(logisticsper)+"%");
}
}

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{


Scanner sc=new Scanner(System.in);
int age=sc.nextInt();
if((age<15)||(age>60)){
System.out.println("Not Allowed");
}else{
System.out.println("Allowed");}
}
}

PROBLEM
Character Pattern 3
 

Write a program to generate a rectangular pattern of stars.


*
**
***
****
*****
 

Input and Output Format:


Input consists of a single integer that corresponds to n, the number of rows.
 

Sample Input 1:
5
 

Sample Output 1:
*
**
***
****
*****
 

import java.util.*;

import java.io.*;

class Main{

public static void main(String[] args) throws Exception{

Scanner sc=new Scanner(System.in);


int n=sc.nextInt();

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) {

int sub1, sub2, sub3, sub4, sub5;

Scanner scan = new Scanner(System.in);

System.out.println("Enter the subject1 mark");


sub1 = scan.nextInt();

System.out.println("Enter the subject2 mark");


sub2 = scan.nextInt();

System.out.println("Enter the subject3 mark");


sub3 = scan.nextInt();

System.out.println("Enter the subject4 mark");


sub4 = scan.nextInt();
System.out.println("Enter the subject5 mark");
sub5 = scan.nextInt();

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;

public class Main {


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = Integer.parseInt(s.nextLine());
int ct=0,n=0,i=1,j=1;
while(n<a) {
j=1;
ct=0;
while(j<=i) {
if(i%j==0){
ct++;
}
j++;
}
if(ct==2) {
System.out.printf("%d ",i);
n++;
}
i++;
}
}
}

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{

public static void main(String[] args){

System.out.println("Welcome to Amphi Event Management System");

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;

public class Main{


public static void main(String[] args){

Scanner sc = new Scanner(System.in);

int A = sc.nextInt();
int B = sc.nextInt();
int N = sc.nextInt();
int sum = 0;

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

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 a class named ItemType with the following private member variables /


attributes.
Data Type Variable
String name
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 method

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.

Example of getters and setters

private String name;

public String getName( ) {


        return name;
}

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 and Output 1:


Enter the item type name
Catering
Enter the cost per day
25000.00
Enter the deposit
10000.50
Item type details
Name : Catering
CostPerDay : 25000.00
Deposit : 10000.50
 

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)

Include the following method in User class.


Method Description

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.

Input and Output Format


Refer sample input and output for formatting specifications.
All text in bold corresponds to the input 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

User.java

public class User {

//Fill your code

String name;

String username;

String password;

long phoneNo;

public User(){}

public User(String name, String username, String password, long phoneNo){

this.name = name;

this.username = username;

this.password = password;

this.phoneNo = phoneNo;

public String getName() {

return name;

}
public void setName(String name) {

this.name = name;

//System.out.println(this.name);

public String getUserName() {

return username;

public void setUserName(String username) {

this.username = username;

public String getPassword() {

return password;

public void setPassword(String password) {

this.password = password;

public long getPhoneNo() {

return phoneNo;

public void setPhoneNo(long phoneNo) {

this.phoneNo = phoneNo;

public boolean comparePhoneNumber(User user) {

//Fill your code

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{

public static void main(String[] args) throws IOException{

//Fill your code

//DecimalFormat df = new DecimalFormat("0.00");


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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());

//System.out.println("phone: " +phoneNo1);

User User = new User(name, username, password, phoneNo);

User user = new User(name1, username1, password1, phoneNo1);

boolean result = User.comparePhoneNumber(user);

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 a class named Rectangle with the following private member variables /


attributes.
Data Type Variable
int length
int width

Include appropriate getters and setters.


Include 2 argument constructor. The order in which the argument should be passed
is Rectangle(int length, int width)

In the Rectangle class include the following methods.


Method Description
int area( )  This method computes the area of the rectange and returns it.
 This method displays the length and width of the rectangle. Display
void display( )
dimensions.
Rectangle dimensionChange(int
 This method changes the rectangle dimension by increasing the le
d)

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).]

Input and Output Format:


Refer sample input and output for formatting specifications.
[All text in bold correspondstoinput and the rest corresponds to output.]

Sample Input and Output 1:


Enter the length of the rectangle
5
Enter the width of the rectangle
6
Rectangle Dimension
Length:5
Width:6
Area of the Rectangle:30
Enter the new dimension
2
Rectangle Dimension
Length:10
Width:12
Area of the Rectangle:120

Problem Requirements:
Java

Keyword Min Count

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.
 

Sample Input and Output


Enter the first string : 
Amphisoft
Enter the second string : 
TECHNOLOGIES
Substring : hisoft
Character at 3rd position is : H
Is str1 and str2 equal : false
Concatenated string : AmphisoftTECHNOLOGIES
 
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 Input and Output 1:


Enter n :
3
Enter numbers : 
100
23
15
Enter strings : 
hi
hello
welcome
Displaying numbers
100
23
15
Displaying strings
hi
hello
welcome
 

Problem Requirements:
Java

Keyword Min Count

for 1

PROBLEM

Command Line Argument - Count


Write a program to accept strings as command line argument and print the number of
arguments entered.

Sample Input (Command Line Argument) 1:


Command Arguments

Sample Output 1:
Arguments :
Command
Arguments
Number of arguments is 2

Sample Input (Command Line Argument) 1:


Commands

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)

Include the following method in the Customer class


Method Name Description
void displayDetails() To display the details ofthe customer in given format.

Create a Main class to include the main() method.


In the main method
 Obtain the details of the customer.
 Create an object for Customer class using parameterized
constructor(customerName, customerEmail, customerType, customerAddress)
 Call the method displayDetails() in Main class
Note :
1.Strictly adhere to the object oriented specifications given as a part of the
problem statement.
2.All text in bold corresponds to input and the rest corresponds to output
Sample Input and Output:
Enter the Customer Details
Enter the name
Yogi
Enter the email
[email protected]
Enter the type
Domestic
Enter the location
India
Name: Yogi
E-mail: [email protected]
Type: Domestic
Location: India

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

Keyword Min Count

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 Input and Output


Enter the first string : 
Amphisoft
Enter the second string : 
TECHNOLOGIES
Upper Case : AMPHISOFT
Lower Case : technologies
Command Line Argument - Print String
Write a program to accept a string as command line argument and print the same.

Sample Input (Command Line Argument) 1:


Programming

Sample Output 1:
Programming - Command Line Arguments

Sample Input (Command Line Argument) 2:


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.
 

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 named Address with the following public attributes

Data Type Attribute

String street

String city

int pincode

String country

Create a class named Address and include the following methods 


Method  Description

This method is used to display all the


void displayAddress()
details.

Create a Main class to include the main method and test the above class.

In the main method

 Obtain the details of the Address.


 Create an object for Address class and assign the values to the attribute
 Call the method displayAddress() in the Main class

Sample Input and Output:


[All text in bold corresponds to input and the rest corresponds to the output]

Enter Customer Address


Enter the street
13,Rockfort Street
Enter the city
Chennai
Enter the pincode
654035
Enter the country
India
Street: 13,Rockfort Street
City: Chennai
Pincode: 654035
Country: India

public class Address{

private String Street;


private String City;
private int Pincode;
private String Country;

Address(String street, String city, int pincode, String country){

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;
}

public void setPincode(int pincode) {


this.pincode = pincode;
}
public int getPincode() {
return pincode;
}

public void setCountry(String country) {


this.country = country;
}
public String getCountry() {
return country;
}*/
}

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;

InputStreamReader stream = new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

//Scanner sc = new Scanner(System.in);


System.out.println("Enter Customer Address");

System.out.println("Enter the street");


street=br.readLine();
//street = sc.nextLine();
System.out.println("Enter the city");
city=br.readLine();
//city = sc.nextLine();

System.out.println("Enter the pincode");


pincode = Integer.parseInt(br.readLine());
//pincode = sc.nextInt();

System.out.println("Enter the country");


country=br.readLine();
//country = sc.nextLine();

Address obj= new Address(street, city, pincode, country);


obj.displayAddress();

}
}

Wrapper Class – Integer I


 
This program is to illustrate Integer Wrapper class.
 
Write a program that accepts a “Integer” class type value as input and invokes some of
the methods defined in the Integer Wrapper class.
 
Refer sample input and output. All functions should be performed using the methods
defined in the Integer class.
 
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 and Output :
Enter an integer
540
The binary equivalent of 540 is 1000011100
The hexadecimal equivalent of 540 is 21c
The octal equivalent of 540 is 1034
Byte value of 540 is 28
Short value of 540 is 540
Long value of 540 is 540
Float value of 540 is 540.0
Double value of 540 is 540.0

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);
}
}

Duplicate mobile number exception


 

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.

Create a Class called ContactDetail with the following private attributes.

Attributes Datatype

mobile String

alternateMobile String

landLine String
email String

address String

Include getters and setters.


Include default and parameterized constructors.
Format for a parameterized constructor is ContactDetail(String mobile, String
alternateMobile,String landLine, String email, String address)

Override the toString() method to display the Contact details as specified.

Create a class called ContactDetailBO with following methods

Method  Description

This method throws DuplicateMobile


static void validate(String mobile,String alternateMobile)
if the mobile and alternateMobile are

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.

Input and Output format:


Refer to sample Input and Output for formatting specifications.

Note: All text in bold corresponds to the input and rest corresponds to the output.

Sample Input and Output 1:

Enter the contact details


9874563210,9874563210,0447896541,[email protected],22nd street kk nagar chennai
DuplicateMobileNumberException: Mobile number and alternate mobile number are
same

Sample Input and Output 2:


Enter the contact details
9874563210,9876543211,0447896541,[email protected],22nd lane RR nagar kovai
Mobile:9874563210
Alternate mobile:9876543211
LandLine:0447896541
Email:[email protected]
Address:22nd lane RR nagar kovai

public class DuplicateMobileNumberException extends Exception{

public DuplicateMobileNumberException(String s)

super(s);

public String toString(){

return "DuplicateMobileNumberException: Mobile number and alternate mobile number are same ";

public class ContactDetailBO {

static void validate(String mobile, String alternateMobile) throws DuplicateMobileNumberException {

if (mobile.equals(alternateMobile)) {

throw new DuplicateMobileNumberException("DuplicateMobileNumberException :");

}-----------

public class ContactDetail {

//Your code here

private String mobile;

private String alternateMobile;

private String landLine;

private String email;


private String address;

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()

public String getMobile() {

return mobile;

public void setMobile(String mobile) {

this.mobile = mobile;

public String getAlternateMobile() {

return alternateMobile;

public void setAlternateMobile(String alternateMobile) {

this.alternateMobile = alternateMobile;

public String getLandLine() {

return landLine;

public void setLandLine(String landLine) {


this.landLine = landLine;

public String getEmail() {

return email;

public void setEmail(String email) {

this.email = email;

public String getAddress() {

return address;

public void setAddress(String address) {

this.address = address;

public String toString()

return "Mobile:"+this.mobile+"\nAlternate
mobile:"+this.alternateMobile+"\nLandLine:"+this.landLine+"\nEmail:"+this.email+"\nAddress:"+this.ad
dress;

import java.io.*;

public class Main {

public static void main(String[] args) throws Exception {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the contact details");

String st = br.readLine();

String[] str = st.split(",");

ContactDetail userInfo = new ContactDetail(str[0], str[1], str[2], str[3], str[4]);


ContactDetailBO BO = new ContactDetailBO();

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 a class SeatNotAvailableException that extends Exception.

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.

Input and Output format:


Refer sample Input and Output for formatting specifications.t of the output.

[All Texts in bold corresponds to the input and rest are output]
Sample Input and Output 1:

Enter the number of rows and columns of the show:


3
Enter the number of seats to be booked:
2
Enter the seat number 1
8
Enter the seat number 2
0
The seats booked are:
100
000
001

Sample Input and Output 2:

Enter the number of rows and columns of the show:


3
Enter the number of seats to be booked:
2
Enter the seat number 1
9
java.lang.ArrayIndexOutOfBoundsException: 9
The seats booked are:
000
000
000

Sample Input and Output 3:

Enter the number of rows and columns of the show:


4
Enter the number of seats to be booked:
3
Enter the seat number 1
15
Enter the seat number 2
14
Enter the seat number 3
15
SeatNotAvailableException: Already Booked
The seats booked are:
0000
0000
0000
0011

public class SeatNotAvailableException extends Exception{

public SeatNotAvailableException(String s) {
super(s);

}
 ----------------------------------------------------------------------------------------------------------

import java.util.Scanner;

import java.io.*;

public class Main {

public static void main(String args[]) throws SeatNotAvailableException{

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of the show:");

int n = sc.nextInt();

int size = (n*n);

int s;

int a[] = new int[size];

int mat[][] = new int[n][n];

System.out.println("Enter the number of seats to be booked:");

int seats = sc.nextInt();

try {

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

System.out.println("Enter the seat number "+(i+1));

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 {

throw new SeatNotAvailableException("Already Booked");

}catch (Exception e) {

System.out.println(e);

finally {

System.out.println("The seats booked are:");

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.

Sample Input and Output 1:

Enter the stage event start date and end date


27-01-2017-12
Input dates should be in the format 'dd-MM-yyyy-HH:mm:ss'

Sample Input and Output 2:

Enter the stage event start date and end date


27-01-2017-12:0:0
28-01-2017-12:0:0
Start date:27-01-2017-12:00:00
End date:28-01-2017-12:00:00

import java.util.*;
import java.text.ParseException;

import java.text.SimpleDateFormat;

public class Main {

public static void main(String[] args) {

// your code here

String d,d1;

Scanner s=new Scanner(System.in);

try{

System.out.println("Enter the stage event start date and end date");

d=s.next();

SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy-HH:mm:ss");

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) {

System.out.println("Input dates should be in the format 'dd-MM-yyyy-HH:mm:ss'");

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.

Sample Input  and Output 1:


Enter the cost of the item for n days
100
Enter the value of n
 0
java.lang.ArithmeticException: / by zero

Sample Input and Output 2:

Enter the cost of the item for n days


100
Enter the value of n
20
Cost per day of the item is 5
 

import java.util.*;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the cost of the item for n days");

int days = sc.nextInt();

System.out.println("Enter the value of n");

int num = sc.nextInt();

try{

int cost = days/num;

System.out.println("Cost per day of the item is "+cost);

}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.

Input and Output format:


The first line of input consists of an integer which corresponds to the number of seats to
be booked.
The next n lines of input consist of the integer which corresponds to the seat number.
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 number of seats to be booked:


5
Enter the seat number 1
23
Enter the seat number 2
42
Enter the seat number 3
65
Enter the seat number 4
81
Enter the seat number 5
100
The seats booked are:
23
42
65
81
100

Sample Input and Output 2:

Enter the number of seats to be booked:


4
Enter the seat number 1
12
Enter the seat number 2
101
java.lang.ArrayIndexOutOfBoundsException: 100

import java.util.Scanner;

public class Main {

public static void main(String args[]) {

int[] seatArray = new int[100];

int n,count = 1;

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of seats to be booked:");


n = sc.nextInt();

try{

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

System.out.println("Enter the seat number "+(i+1));

count = sc.nextInt();

seatArray[count-1] = count;

System.out.println("The seats booked are:");

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

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 a class named Person with the following private data members.                           


Data Type     Data Member   
String name
String dateOfBirth
String gender
String mobileNumber
String bloodGroup

Include appropriate getters and setters.

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.

The class Donor should have the following method


Method Member Function 
This method displays the donation details.
public void displayDonationDetails( )
Display the statement ‘Donation Details :’ inside this method

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.

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 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
 

class Donor extends Person{

private String bloodBankName;

private String donorType;

private String donationDate;

public Donor() {

public String getBloodBankName() {

return bloodBankName;

}
public void setBloodBankName(String bloodBankName) {

this.bloodBankName = bloodBankName;

public String getDonorType() {

return donorType;

public void setDonorType(String donorType) {

this.donorType = donorType;

public String getDonationDate() {

return donationDate;

public void setDonationDate(String donationDate) {

this.donationDate = donationDate;

public void displayDonationDetails( ) {


System.out.println("Donation Details :");

System.out.println("Name : "+getName());

System.out.println("Date Of Birth : "+getDateOfBirth());

System.out.println("Gender : "+getGender());

System.out.println("Mobile Number : "+getMobileNumber());

System.out.println("Blood Group : "+getBloodGroup());

System.out.println("Blood Bank Name : "+getBloodBankName());

System.out.println("Donor Type : "+getDonorType());

System.out.println("Donation Date : "+getDonationDate());

//Fill your code here

class Person{

private String name;

private String dateOfBirth;

private String gender;

private String mobileNumber;

private String bloodGroup;

Person(){

public String getName() {

return name;

}
public void setName(String name) {

this.name = name;

public String getDateOfBirth() {

return dateOfBirth;

public void setDateOfBirth(String dateOfBirth) {

this.dateOfBirth = dateOfBirth;

public String getGender() {

return gender;

public void setGender(String gender) {

this.gender = gender;

}
public String getMobileNumber() {

return mobileNumber;

public void setMobileNumber(String mobileNumber) {

this.mobileNumber = mobileNumber;

public String getBloodGroup() {

return bloodGroup;

public void setBloodGroup(String bloodGroup) {

this.bloodGroup = bloodGroup;

import java.util.Scanner;
public class Main {

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

Donor d = new Donor();

System.out.println("Enter the name :");

d.setName(sc.nextLine());

System.out.println("Enter Date of Birth :");

d.setDateOfBirth(sc.nextLine());

System.out.println("Enter Gender :");

d.setGender(sc.nextLine());

System.out.println("Enter Mobile Number :");

d.setMobileNumber(sc.nextLine());

System.out.println("Enter Blood Group :");

d.setBloodGroup(sc.nextLine());

System.out.println("Enter Blood Bank Name :");

d.setBloodBankName(sc.nextLine());

System.out.println("Enter Donor Type :");

d.setDonorType(sc.nextLine());
System.out.println("Enter Donation Date :");

d.setDonationDate(sc.nextLine());

d.displayDonationDetails();

//Fill your code here

}
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.

Create a class VISACard with the following method.


Method Description
public double computeRewardPoints(String type, double amount) This method returns the 1% of the

Create a class HPVISACard which extends VISACard class and overrides the following


method.
Method Description
public double computeRewardPoints(String type, double amount) In this method, calculate the reward po

Hint:
Use super keyword to calculate reward points from base class.

Create Main class with main method, get the transaction details as a


comma separated values.
(Transaction type, amount, card type)

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).

Input and Output Format


Refer sample input and output for formatting specifications.
All text in bold corresponds to the input and the rest corresponds to output.

Sample Input and Output :


Enter the transaction detail
Shopping,5000,VISA card
Total reward points earned in this transaction is 50.00
Do you want to continue?(Yes/No)
Yes
Enter the transaction detail
Fuel,5000,HIVISA card
Invalid data
Do you want to continue?(Yes/No)
Yes
Enter the transaction detail
Fuel,5000,HPVISA card
Total reward points earned in this transaction is 60.00
Do you want to continue?(Yes/No)
No
 

public class VISACard {

public double computeRewardPoints(String type, double amount) {

return amount * 0.01;

class HPVISACard extends VISACard{

public double computeRewardPoints(String type, double amount){

double total=super.computeRewardPoints(type, amount);

if(type.equalsIgnoreCase("Fuel")) {

total=total+10;

return total;

}else{

return total;

import java.io.*;

import java.util.*;

import java.text.DecimalFormat;

public class Main {


public static void main(String[] args) {

String tDetails = null;

String transactionType = null;

double amount = 0;

String cardType = null;

String flag = null;

VISACard v = new VISACard();

HPVISACard h = new HPVISACard();

Scanner sc = new Scanner(System.in);

do {

System.out.println("Enter the transaction detail");

tDetails = sc.nextLine();

String dSplit[] = tDetails.split(",");

transactionType = dSplit[0];

amount = Double.parseDouble(dSplit[1]);

cardType = dSplit[2];

DecimalFormat df = new DecimalFormat("0.00");

if (cardType.equals("VISA card")) {

System.out.println("Total reward points earned in this transaction is "

+ df.format(v.computeRewardPoints(transactionType,
amount)));

System.out.println("Do you want to continue?(Yes/No)");

flag = sc.nextLine();

} else if (cardType.equals("HPVISA card")) {

System.out.println("Total reward points earned in this transaction is "

+ df.format(h.computeRewardPoints(transactionType,
amount)));

System.out.println("Do you want to continue?(Yes/No)");

flag = sc.nextLine();
} else {

System.out.println("Invalid data");

System.out.println("Do you want to continue?(Yes/No)");

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 class Event with the following protected attributes/variables.


Data Type Variable
String name
String type
double costPerDay
int noOfDays

Include a four argument constructor with parameters in the following order,


public Event(String name, String type, double costPerDay, int noOfDays)

Create class Exhibition which extends the Event class with the following private


attributes/variables.
Data Type Variable
static int gst = 5
int noOfStalls

Include a five argument constructor with parameters in the following order,


public Exhibition(String name, String type, double costPerDay, int noOfDays, int
noOfStalls)

Include the following methods.


Method Description
public double totalCost() This method is to calculate the total amount with 5% GST

Create class StageEvent which extends the Event class with the following private


attributes/variables.
Data Type Variable
static int gst = 15
int noOfSeats

Include a five argument constructor with parameters in the following order,


public StageEvent(String name, String type, double costPerDay, int noOfDays, int
noOfSeats)

Include the following method.


Method Description
public double totalCost() This method is to calculate the total amount with 15% GST

Use super( ) to call and assign values in base class constructor.


Override toString() method to display the event details. Refer the sample output format.

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.

Input and Output Format:


Refer sample input and output for formatting specifications.
All text in bold corresponds to the input and the rest corresponds to output.

Sample Input and Output 1:


Enter event name
Sky Lantern Festival
Enter the cost per day
1500
Enter the number of days
3
Enter the type of event
1.Exhibition
2.Stage Event
2
Enter the number of seats
100
Event Details
Name:Sky Lantern Festival
Type:Stage Event
Number of seats:100
Total amount: 5175.00

Sample Input and Output 2:


Enter event name
Glastonbury
Enter the cost per day
5000
Enter the number of days
2
Enter the type of event
1.Exhibition
2.Stage Event
1
Enter the number of stalls
10
Event Details
Name:Glastonbury
Type:Exhibition
Number of stalls:10
Total amount: 10500.00

Sample Input and Output 3:


Enter event name
Glastonbury
Enter the cost per day
5000
Enter the number of days
2
Enter the type of event
1.Exhibition
2.Stage Event
3
Invalid input

import java.util.*;

import java.text.DecimalFormat;
public class Main {

public static void main(String[] args) {

String name, type;

double cpd;

int npd;

Scanner sc = new Scanner(System.in);

System.out.println("Enter event name");

name = sc.nextLine();

System.out.println("Enter the cost per day");

cpd = sc.nextDouble();

System.out.println("Enter the number of days");

npd = sc.nextInt();

sc.nextLine();

System.out.println("Enter the type of event\n1.Exhibition\n2.Stage Event");

type = sc.nextLine();

DecimalFormat df = new DecimalFormat("0.00");

switch (type) {

case "1":

System.out.println("Enter the number of stalls");

int stalls = sc.nextInt();

Exhibition e = new Exhibition(name, type, cpd, npd, stalls);

Double total = e.totalCost();

System.out.println(e.toString() + "\nTotal amount:" + df.format(total));

break;

case "2":

System.out.println("Enter the number of seats");

int seats = sc.nextInt();

StageEvent s = new StageEvent(name, type, cpd, npd, seats);

Double total1 = s.totalCost();


System.out.println(s.toString() + "\nTotal amount:" + df.format(total1));

break;

default:

System.out.println("Invalid input");

break;

class Event{

protected String name;

protected String type;

protected double costPerDay;

protected int noOfDays;

public Event(String name, String type, double costPerDay, int noOfDays) {

super();

this.name = name;

this.type = type;

this.costPerDay = costPerDay;

this.noOfDays = noOfDays;

class StageEvent extends Event {

static int gst = 15;

int noOfSeats;

public StageEvent(String name, String type, double costPerDay, int noOfDays, int noOfSeats) {

super(name, type, costPerDay, noOfDays);

this.noOfSeats = noOfSeats;
}

public double totalCost() {

double totalAmount = (costPerDay * noOfDays);

double gstAmount = (totalAmount * gst) / 100;

double total = (totalAmount + gstAmount);

return total;

@Override

public String toString() {

return "Event Details\nName:" + name + "\nType:Stage Event\nNumber of seats:" +


noOfSeats;

class Exhibition extends Event {

static int gst = 5;

int noOfStalls;

public Exhibition(String name, String type, double costPerDay, int noOfDays, int noOfStalls) {

super(name, type, costPerDay, noOfDays);

this.noOfStalls = noOfStalls;

public double totalCost() {

double totalAmount = (costPerDay * noOfDays);

double gstAmount = (totalAmount * gst) / 100;

double total = (totalAmount + gstAmount);

return total;
}

@Override

public String toString() {

return "Event Details\nName:" + name + "\nType:Exhibition\nNumber of stalls:" +


noOfStalls;

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 an abstract class called Event with following protected attributes.


Attributes Datatype
name String
detail String
type String
organiser String
 
Include 4 argument constructors in the Event class in the following order Event(String
name, String detail, String type, String organiser)

Include the following abstract method in the class Event.


Method  Description
abstract Double calculateAmount() an abstract method

Create a class named Exhibition which extends Event class with the following private


attributes
Attributes Datatype
noOfStalls Integer
 rentPerStall Double
 
Include a six argument constructor with parameters in the following order,
public Exhibition(String name, String detail, String type, String organiser, Integer
noOfStalls,Double rentPerStall)
Use super( ) to call and assign values in base class constructor.

Include the following abstract method in the class Exhibition.


Method  Description
Double calculateAmount () This method returns the product of noOfStalls and rentPerStall

Create a class named StageEvent which extends Event class with the following private


attributes.
Attribute Datatype
noOfShows Integer
costPerShow Double
Include a six argument constructor with parameters in the following order,
public StageEvent(String name, String detail, String type, String organiser, Integer
noOfShows,Double costPerShow)
Use super( ) to call and assign values in base class constructor.
Include the following abstract method in the class StageEvent.
Method   Description
Double calculateAmount() This method returns the product of noOfShows and costPerShow

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.

Sample Input and output 1:


 
Enter your choice
1.Exhibition
2.StageEvent
1
Enter the details in CSV format
Book expo,Special sale,Academics,Mahesh,100,1000
Exhibition Details
Event Name:Book expo
Detail:Special sale
Type:Academics
Organiser Name:Mahesh
Total Cost:100000.0

Sample Input and Output 2:


 
Enter your choice
1.Exhibition
2.StageEvent
2
Enter the details in CSV format
JJ magic show,Comedy magic,Entertainment,Jegadeesh,5,1000
Stage Event Details
Event Name:JJ magic show
Detail:Comedy magic
Type:Entertainment
Organiser Name:Jegadeesh
Total Cost:5000.0
 
 
Sample Input and Output 3:
 
Enter your choice
1.Exhibition
2.StageEvent
3
Invalid choice

public class Exhibition extends Event {

private Integer noOfStalls;

private Double rentPerStall;

public Exhibition(String name, String detail, String type, String organiser, Integer noOfStalls,

Double rentPerStall) {

super(name, detail, type, organiser);

this.noOfStalls = noOfStalls;
this.rentPerStall = rentPerStall;

Double calculateAmount() {

return noOfStalls * rentPerStall;

public class StageEvent extends Event {

private Integer noOfShows;

private Double costPerShow;

public StageEvent(String name, String detail, String type, String organiser, Integer noOfShows,

Double costPerShow) {

super(name, detail, type, organiser);

this.noOfShows = noOfShows;

this.costPerShow = costPerShow;

Double calculateAmount() {

return noOfShows * costPerShow;

public abstract class Event {

protected String name;

protected String detail;

protected String type;

protected String organiser;

public Event(String name, String detail, String type, String organiser) {


this.name = name;

this.detail = detail;

this.type = type;

this.organiser = organiser;

abstract Double calculateAmount();

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getDetail() {

return detail;

public void setDetail(String detail) {

this.detail = detail;

public String getType() {

return type;

public void setType(String type) {


this.type = type;

public String getOrganiser() {

return organiser;

public void setOrganiser(String organiser) {

this.organiser = organiser;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String s, name, detail, type, organiser;

Integer noOfStalls, noOfShows;

Double rentPerStall, costPerShow, totalCost;

System.out.println("Enter your choice");

System.out.println("1.Exhibition");

System.out.println("2.StageEvent");

int ch = sc.nextInt();

switch (ch) {

case 1:

System.out.println("Enter the details in CSV format");

sc.nextLine();

s = sc.nextLine();

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


name = split[0];

detail = split[1];

type = split[2];

organiser = split[3];

noOfStalls = Integer.parseInt(split[4]);

rentPerStall = Double.parseDouble(split[5]);

Exhibition e = new Exhibition(name, detail, type, organiser, noOfStalls,


rentPerStall);

totalCost = e.calculateAmount();

System.out.println("Exhibition Details");

System.out.println("Event Name:" + e.getName());

System.out.println("Detail:" + e.getDetail());

System.out.println("Type:" + e.getType());

System.out.println("Organiser Name:" + e.getOrganiser());

System.out.println("Total Cost:" + totalCost);

break;

case 2:

System.out.println("Enter the details in CSV format");

sc.nextLine();

s = sc.nextLine();

String split1[] = s.split(",");

name = split1[0];

detail = split1[1];

type = split1[2];

organiser = split1[3];

noOfShows = Integer.parseInt(split1[4]);

costPerShow = Double.parseDouble(split1[5]);

StageEvent se = new StageEvent(name, detail, type, organiser, noOfShows,


costPerShow);
totalCost = se.calculateAmount();

System.out.println("Stage Event Details");

System.out.println("Event Name:" + se.getName());

System.out.println("Detail:" + se.getDetail());

System.out.println("Type:" + se.getType());

System.out.println("Organiser Name:" + se.getOrganiser());

System.out.println("Total Cost:" + totalCost);

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.

Create a parent class Event with following protected attributes,


Attributes Datatype
name String
detail String
ownerName String
Include parameterized constructors to the Event class in the following order Event(String
name, String detail, String ownerName)
Include the below abstract method in the Event class.
Method Description
public abstract Double projectedRevenue() Return just 0.0

Then create child class Exhibition that extends Event with the following attribute,


Attributes Datatype
noOfStalls Integer
Include parameterized constructors to the Exhibition class in the following
order Exhibition(String name, String detail, String ownerName, Integer noOfStalls). Use
super( ) to call and assign values in base class constructor.
Add method projectedRevenue() in Exhibition class
Method Description
public Double projectedRevenue() Calculate revenue and return the double value. Each stall will pro
 

And create another child class StageEvent that extends Event with the


following attribute,
Attributes Datatype
noOfShows Integer
noOfSeatsPerShow Integer
Include parameterized constructors to the StageEvent class in the following
order StageEvent(String name, String detail, String ownerName, Integer noOfShows,
Integer noOfSeatsPerShow). Use super( ) to call and assign values in base class
constructor.
Add method projectedRevenue() in StageEvent class
Method Description
public Double projectedRevenue() Calculate revenue and return the double value. Each seat pro

Refer sample input/output for other further details and format of the output.

[All Texts in bold corresponds to the input and rest are output]
Sample Input/Output 1:

Enter the name of the event:


Science Fair
Enter the detail of the event:
Explore Technology
Enter the owner name of the event:
ABCD
Enter the type of the event:
1.Exhibition
2.StageEvent
1
Enter the number of stalls:
65
The projected revenue of the event is 650000.0

Sample Input/Output 2:

Enter the name of the event:


Magic Show
Enter the detail of the event:
See Magic without Logic
Enter the owner name of the event:
SDFG
Enter the type of the event:
1.Exhibition
2.StageEvent
2
Enter the number of shows:
10
Enter the number of seats per show:
100
The projected revenue of the event is 50000.0
 

public class StageEvent extends Event{

private Integer noOfShows;

private Integer noOfSeatsPerShow;

public StageEvent()

{}

public StageEvent(String name, String detail, String ownerName,Integer noOfShows,Integer


noOfSeatsPerShow)

super(name,detail,ownerName);

this.name = name;
this.detail = detail;

this.ownerName = ownerName;

this.noOfShows = noOfShows;

this.noOfSeatsPerShow = noOfSeatsPerShow;

@Override

public double projectedRevenue()

double revenue = noOfShows * noOfSeatsPerShow * 50;

return revenue;

public abstract class Event {

protected String name;

protected String detail;

protected String ownerName;

public Event(){

public Event(String name, String detail, String ownerName)

this.name = name;

this.detail = detail;

this.ownerName = ownerName;
}

public double projectedRevenue(){

return 0.0;

import java.io.IOException;

import java.util.Scanner;

public class Main {

public static void main(String[] args) throws IOException {

Scanner sc = new Scanner(System.in);

double totalrevenue = 0;

System.out.println("Enter the name of the event:");

String name = sc.nextLine();

System.out.println("Enter the detail of the event:");

String detail = sc.nextLine();

System.out.println("Enter the owner name of the event:");

String ownerName = sc.nextLine();


System.out.println("Enter the type of the event:\n1.Exhibition\n2.StageEvent");

int choice = sc.nextInt();

switch(choice){

case 1 :

System.out.println("Enter the number of stalls:");

int noOfStalls = sc.nextInt();

Exhibition exObj = new Exhibition(name,detail,ownerName,noOfStalls);

totalrevenue = exObj.projectedRevenue();

System.out.println("The projected revenue of the event is " + totalrevenue);

break;

case 2 :

System.out.println("Enter the number of shows:");

int noOfShows = sc.nextInt();

System.out.println("Enter the number of seats per show:");

int noOfSeatsPerShow = sc.nextInt();

StageEvent seObj = new


StageEvent(name,detail,ownerName,noOfShows,noOfSeatsPerShow);

totalrevenue = seObj.projectedRevenue();

System.out.println("The projected revenue of the event is " + totalrevenue);

break;

default : break;

}
}

public class Exhibition extends Event{

//Your code here

private Integer noOfStalls;

public Exhibition()

public Exhibition(String name, String detail, String ownerName,Integer noOfStalls)

super(name,detail,ownerName);

this.name = name;

this.detail = detail;

this.ownerName = ownerName;

this.noOfStalls = noOfStalls;

@Override

public double projectedRevenue()

{ double revenue = noOfStalls * 10000;

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
 

Create an interface named MaintenanceCharge with the following method


Method Description
float calculateMaintancecharge(float no of This method is used to calculate the
years) maintenance charge

Create a class named CurrentAccount which implements MaintenanceCharge interface


Create a class named SavingsAccount which implements MaintenanceCharge interface
Create an another class named Main with main( ) method to test the above classes.
In Savings Account the maintenance amount will be 2*m*n+50.
In Current Account, the maintenance amount will be m*n+200.
where m is the maintenance charge per year and n is the number of years.
Maintenance charge Rs.50  for saving account and 100 for the Current account.
 

Note: Refere sample input and output for the specifications.


All text in bold corresponds to the input and remaining text corresponds to output.
Sample input and output 1:
1.Current Account
2.Savings Account
1
Name
SB
Account Number
12345
Account Balance
5000
Enter the Start Date(yyyy-mm-dd)
2013-04-22
Enter the Years
2
Maintenance Charge For Current Account 400.00
Sample input and output 2:
1.Current Account
2.Savings Account
2
Name
SB
Account Number
54321
Account Balance
3000
Enter the Start Date(yyyy-mm-dd)
2014-04-12
Enter the Years
5
Maintenance Charge For Savings Account 550.00

public class CurrentAccount implements MaintainanceCharge {

@Override

public float calculateMaintanceCharge(int noOfYear) {

return (100 * noOfYear) + 200;

class Account {

String name;

String accountNumber;
double balance;

String startDate;

public Account(String name, String accountNumber, double balance, String startDate) {

super();

this.name = name;

this.accountNumber = accountNumber;

this.balance = balance;

this.startDate = startDate;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getAccountNumber() {

return accountNumber;

public void setAccountNumber(String accountNumber) {

this.accountNumber = accountNumber;

public double getBalance() {

return balance;
}

public void setBalance(double balance) {

this.balance = balance;

public String getStartDate() {

return startDate;

public void setStartDate(String startDate) {

this.startDate = startDate;

public interface MaintainanceCharge{

float calculateMaintanceCharge(int noOfYear);

class SavingsAccount implements MaintainanceCharge {

@Override

public float calculateMaintanceCharge(int noOfYear) {

return (2 * 50 * noOfYear) + 50;

}
import java.text.DecimalFormat;

import java.util.*;

public class Main {

public static void main(String args[]) {

Scanner s = new Scanner(System.in);

String name, sdate, account;

double accountBalance;

int years;

System.out.println("1.Current Account");

System.out.println("2.Savings Account");

int n = s.nextInt();

DecimalFormat df = new DecimalFormat("0.00");

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();

System.out.println("Enter the Start Date(yyyy-mm-dd)");

sdate = s.nextLine();

System.out.println("Enter the Years");

years = s.nextInt();

Account a = new Account(name, account, accountBalance, sdate);

CurrentAccount c = new CurrentAccount();

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();

System.out.println("Enter the Start Date(yyyy-mm-dd)");

sdate = s.nextLine();

System.out.println("Enter the Years");

years = s.nextInt();

Account a1 = new Account(name, account, accountBalance, sdate);

SavingsAccount sa = new SavingsAccount();

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.

Create an interface Stall  with the following method


Method Description
void display() abstract method.

Create a class GoldStall which implements Stall interface with the following private


attributes
Attribute Datatype
stallName String
cost Integer
ownerName String
tvSet Integer
Create default constructor and a parameterized constructor with arguments in
order GoldStall(String stallName, Integer cost, String ownerName, Integer tvSet).
Include appropriate getters and setters.

Include the following method in the class GoldStall


Method Description
void display() To display the stall name, cost of the stall, owner name and the number of tv sets.

Create a class PremiumStall which implements Stall interface with following private


attributes
Attribute Datatype
stallName String
cost Integer
ownerName String
projector Integer
Create default constructor and a parameterized constructor with arguments in
order PremiumStall(String stallName, Integer cost, String ownerName, Integer
projector).
Include appropriate getters and setters.

Include the following method in the class PremiumStall.


Method Description
void display() To display the stall name, cost of the stall, owner name and the number of projectors

Create a class ExecutiveStall which implements Stall interface with following private


attributes
Attribute Datatype
stallName String
cost Integer
ownerName String
screen Integer
Create default constructor and a parameterized constructor with arguments in
order ExecutiveStall(String stallName, Integer cost, String ownerName, Integer screen).
Include appropriate getters and setters.

Include the following method in the class ExecutiveStall.


Method Description
void display() To display the stall name, cost of the stall, owner name and the number of screens.

Create a driver class named Main to test the above class.

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

Sample Input and Output 1:

Choose Stall Type


1)Gold Stall
2)Premium Stall
3)Executive Stall
1
Enter Stall details in comma separated(Stall Name,Stall Cost,Owner Name,Number of TV
sets)
The Mechanic,120000,Johnson,10
Stall Name:The Mechanic
Cost:120000.Rs
Owner Name:Johnson
Number of TV sets:10

Sample Input and Output 2:

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

Sample Input Output 3:

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

Sample Input Output 4:

ChooseStall Type
1)Gold Stall
2)Premium Stall
3)Executive Stall
4
Invalid Stall Type

public class PremiumStall implements Stall {

private String stallName;


private Integer cost;
private String ownerName;
private Integer projector;

public PremiumStall(String stallName, Integer cost, String ownerName, Integer


projector) {
this.stallName = stallName;
this.cost = cost;
this.ownerName = ownerName;
this.projector = projector;
}

public PremiumStall() {

public void display() {


System.out.println("Stall Name:" + stallName + "\nCost:" + cost +
".Rs\nOwner Name:" + ownerName
+ "\nNumber of Projectors:" + projector);
}

public String getStallName() {


return stallName;
}

public void setStallName(String stallName) {


this.stallName = stallName;
}

public Integer getCost() {


return cost;
}
public void setCost(Integer cost) {
this.cost = cost;
}

public String getOwnerName() {


return ownerName;
}

public void setOwnerName(String ownerName) {


this.ownerName = ownerName;
}

public Integer getProjector() {


return projector;
}

public void setProjector(Integer projector) {


this.projector = projector;
}
}
public class ExecutiveStall implements Stall {

private String stallName;


private Integer cost;
private String ownerName;
private Integer screen;

public ExecutiveStall(String stallName, Integer cost, String ownerName, Integer


screen) {
this.stallName = stallName;
this.cost = cost;
this.ownerName = ownerName;
this.screen = screen;
}

public ExecutiveStall() {

public void display() {


System.out.println("Stall Name:" + stallName + "\nCost:" + cost +
".Rs\nOwner Name:" + ownerName
+ "\nNumber of Screens:" + screen);
}

public String getStallName() {


return stallName;
}

public void setStallName(String stallName) {


this.stallName = stallName;
}

public Integer getCost() {


return cost;
}

public void setCost(Integer cost) {


this.cost = cost;
}

public String getOwnerName() {


return ownerName;
}

public void setOwnerName(String ownerName) {


this.ownerName = ownerName;
}

public Integer getScreen() {


return screen;
}

public void setScreen(Integer screen) {


this.screen = screen;
}
}
public interface Stall {
void display();

}
import java.util.Scanner;

public class Main {


public static void main(String[] args) throws Exception {

// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


String[] arr = new String[3];
String stallDetails = "";

System.out.println("Choose Stall Type\n1)Gold Stall\n2)Premium


Stall\n3)Executive Stall");

Scanner scan = new Scanner(System.in);


int n = scan.nextInt();

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(",");

int cost = Integer.parseInt(arr[1]);


int num = Integer.parseInt(arr[3]);

GoldStall gStall = new GoldStall(arr[0], cost, arr[2], num);


gStall.display();

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]);

PremiumStall pStall = new PremiumStall(arr[0], cost, arr[2], num);


pStall.display();
break;
case 3:
scan.nextLine();
System.out.println(
"Enter Stall details in comma separated(Stall
Name,Stall Cost,Owner Name,Number of Screens)");

stallDetails = scan.nextLine();

arr = stallDetails.split(",");
cost = Integer.parseInt(arr[1]);
num = Integer.parseInt(arr[3]);

ExecutiveStall eStall = new ExecutiveStall(arr[0], cost, arr[2], num);


eStall.display();
break;
default:
System.out.println("Invalid Stall Type");

}
}
public class GoldStall implements Stall {

private String stallName;


private Integer cost;
private String ownerName;
private Integer tvSet;

public GoldStall(String stallName, Integer cost, String ownerName, Integer tvSet) {


this.stallName = stallName;
this.cost = cost;
this.ownerName = ownerName;
this.tvSet = tvSet;
}

public GoldStall() {

public void display() {


System.out.println("Stall Name:" + stallName + "\nCost:" + cost +
".Rs\nOwner Name:" + ownerName
+ "\nNumber of TV sets:" + tvSet);
}
public String getStallName() {
return stallName;
}

public void setStallName(String stallName) {


this.stallName = stallName;
}

public Integer getCost() {


return cost;
}

public void setCost(Integer cost) {


this.cost = cost;
}

public String getOwnerName() {


return ownerName;
}

public void setOwnerName(String ownerName) {


this.ownerName = ownerName;
}

public Integer getTvSet() {


return tvSet;
}

public void setTvSet(Integer tvSet) {


this.tvSet = tvSet;
}

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

Create a class BankFactory with two methods


Method Description
This method is used to return the object for ICICI
public Icici getIcici( )
class
public Hdfc This method is used to return the object for HDFC
getHdfc( ) class
Create the Main class with main( ) method to test the above class.

Input and Output format:


The first integer corresponds to select the bank, the next integer corresponds to the
type of the notification.
If there is no valid input then display 'Invalid input'.
 

[Note: All text in bold corresponds to the input and remaining text corresponds to
output]

Sample Input and Output 1:

Welcome to Notification Setup


Please select your bank:
1)ICICI
2)HDFC
1
Enter the type of Notification you want to enter
1)SMS
2)Mail
3)Courier
1
ICICI - Notification By SMS

Sample Input and Output 2:


Welcome to Notification Setup
Please select your bank:
1)ICICI
2)HDFC
2
Enter the type of Notification you want to enter
1)SMS
2)Mail
3)Courier
3
HDFC - Notification By Courier

Sample Input and Output 3:

Welcome to Notification Setup


Please select your bank:
1)ICICI
2)HDFC
3
Invalid Input

public class ICICI implements Notification {

@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 void notificationBySms();

public void notificationByEmail();

public void notificationByCourier();

}
public class BankFactory {

public ICICI getIcici() {


ICICI icici = new ICICI();
return icici;
}

public HDFC getHdfc() {


HDFC hdfc = new HDFC();
return hdfc;
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Main {

public static void main(String[] args) throws IOException {


Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Notification Setup");
System.out.println("Please select your bank:\n1)ICICI\n2)HDFC");
int bank = sc.nextInt();
switch (bank) {
case 1:
System.out.println("Enter the type of Notification you want to
enter\n1)SMS\n2)Mail\n3)Courier");
int msg = sc.nextInt();
BankFactory b = new BankFactory();
ICICI c = b.getIcici();
switch (msg) {
case 1:
c.notificationBySms();
break;
case 2:
c.notificationByEmail();
break;
case 3:
c.notificationByCourier();
break;
default:
System.out.println("Invalid Input");
break;
}
break;
case 2:
System.out.println("Enter the type of Notification you want to
enter\n1)SMS\n2)Mail\n3)Courier");
int msg1 = sc.nextInt();
BankFactory b1 = new BankFactory();
HDFC h = b1.getHdfc();
switch (msg1) {
case 1:
h.notificationBySms();
break;
case 2:
h.notificationByEmail();
break;
case 3:
h.notificationByCourier();
break;
default:
System.out.println("Invalid Input");
break;
}
break;
default:
System.out.println("Invalid Input");
break;
}
}
}

Static Inner Class


Write a program to calculate the area of the rectangle and triangle using the static inner
class concept in java.

Create an outer class Shape with the following public static attributes


Attribute Datatyp
s e
value1 Double
value2 Double
 

Create a static inner class Rectangle which have the outer class Shape.


Include the following method in the Rectangle class
Method Name Description
Here Calculate and return the area of the rectangle by accessing
public Double
the attributes value1(length) & value2(breadth) of Shape class.
computeRectangleArea()
Area of the rectangle = (length * breadth)

Create a static inner class Triangle which have the outer class Shape.


Include the following method in the Triangle class
Method Name Description
public Double Here Calculate and return the area of the triangle by accessing the
computeTriangleArea() attributes value1(base) & value2(height) of Shape class.
Area of the triangle = (1/2) * (base * height)

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.

Create a driver class Main to test the above classes.

[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.

[All text in bold corresponds to input and rest corresponds to output]


Sample Input/Output 1:
Enter the shape
1.Rectangle
2.Triangle
1
Enter the length and breadth:
10
25
Area of rectangle is 250.00

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

public class Shape {


public static Double value1;
public static Double value2;

public static class Rectangle {


public Double computeRectangleArea() {
return (value1 * value2);
}
}

public static class Triangle {


public Double computeTriangleArea() {
return ((0.5) * (value1 * value2));
}
}
}
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {


public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the shape\r\n1.Rectangle\r\n2.Triangle");
int ch = sc.nextInt();
DecimalFormat df = new DecimalFormat("0.00");
switch (ch) {
case 1:
System.out.println("Enter the length and breadth:");
Shape.value1 = sc.nextDouble();
Shape.value2 = sc.nextDouble();
Shape.Rectangle r = new Shape.Rectangle();
Double rectangle = r.computeRectangleArea();
System.out.println("Area of rectangle is " + df.format(rectangle));
break;
case 2:
System.out.println("Enter the base and height:");
Shape.value1 = sc.nextDouble();
Shape.value2 = sc.nextDouble();
Shape.Triangle t = new Shape.Triangle();
Double triangle = t.computeTriangleArea();
System.out.println("Area of triangle is " + df.format(triangle));
break;
default:
System.out.println("Invalid choice");
break;
}
}
}

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)

The Article class includes the following methods


Method Description
void This method counts the number of articles in a given line
run() and stores the value in the count variable.

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.

Input and Output format:


Refer to sample Input and Output for formatting specifications.
[All text in bold corresponds to the input and rest corresponds to the output]
Sample Input and Output:
Enter the number of lines
3
Enter line 1
An article is a word used to modify a noun, which is a person, place, object, or
idea.
Enter line 2
Technically, an article is an adjective, which is any word that modifies a noun.
Enter line 3
There are two different types of articles.
There are 7 articles in the given input

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Article extends Thread {

String line;

int count;

public Article() {

super();

}
public Article(String line) {

super();

this.line = line;

public String getLine() {

return line;

public void setLine(String line) {

this.line = line;

public int getCount() {

return count;

public void setCount(int count) {

this.count = count;

@Override

public void run() {

Matcher m = Pattern.compile("(?i)\\b((a)|(an)|(the))\\b").matcher(this.getLine());

while (m.find()) {

this.count++;

}
}

import java.util.Scanner;

public class Main {

public static void main(String[] args) throws InterruptedException{

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of lines");

int n = sc.nextInt();

int count = 0;

sc.nextLine();

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

Article a = new Article();

System.out.println("Enter line "+(i+1));

a.setLine(sc.nextLine());

a.start();

a.join();

count +=a.getCount();

System.out.println("There are "+count+" articles in the given input");

}
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.

Include following methods.


Override run() method which displays event name along with their status (i.e) Profit or
Loss. 
If  (seats booked / hall capacity) * 100 >= 60 then it is a profit else loss  .

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:

The first line of input corresponds to the number of events 'n'.


The next 'n' line of input corresponds to the event details in CSV format of (Event
Name,Hall Name,Cost,Hall Capacity,Seats Booked).
Refer to sample input for formatting specifications.

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".

Sample Input and Output 1:


[All text in bold corresponds to input and rest corresponds to output]

Enter the number of events


4
Enter event details in CSV
Party,Le Meridian,12000,400,250
Wedding,MS mahal,500000,1000,400
Alumni meet,Ramans,10000,600,300
Plaza party,Rizzodous,30000,1200,1000
Party yields profit
Wedding yields loss
Alumni meet yields loss
Plaza party yields profit

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class Event {


private String name;
private HallBooking hallBooking;

public Event() {
}

public Event(String name, HallBooking hallBooking) {


this.name = name;
this.hallBooking = hallBooking;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public HallBooking getHallBooking() {


return hallBooking;
}

public void setHallBooking(HallBooking hallBooking) {


this.hallBooking = hallBooking;
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class ComputeStatus implements Runnable {
List<Event> eventList;

public List<Event> getEventList() {


return eventList;
}

public void setEventList(List<Event> eventList) {


this.eventList = eventList;
}

@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(String hallName, Double cost, Integer hallCapacity, Integer


seatsBooked) {
this.hallName = hallName;
this.cost = cost;
this.hallCapacity = hallCapacity;
this.seatsBooked = seatsBooked;
}
public HallBooking() {
}

public String getHallName() {


return hallName;
}

public void setHallName(String hallName) {


this.hallName = hallName;
}

public Double getCose() {


return cost;
}

public void setCose(Double cose) {


this.cost = cose;
}

public Integer getHallCapacity() {


return hallCapacity;
}

public void setHallCapacity(Integer hallCapacity) {


this.hallCapacity = hallCapacity;
}

public Integer getSeatsBooked() {


return seatsBooked;
}

public void setSeatsBooked(Integer seatsBooked) {


this.seatsBooked = seatsBooked;
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of events");
int noOfEvents = Integer.parseInt(scanner.nextLine());
if (noOfEvents > 0 && noOfEvents % 2 == 0) {
System.out.println("Enter event details in CSV");
String eventDetail = "";
List<Event> eventList = new ArrayList<Event>();
ComputeStatus computeStatus = new ComputeStatus();
// computeStatus.setEventList(eventList);
ThreadGroup threadGroup = new ThreadGroup("TG1");
Thread t1 = new Thread(threadGroup, computeStatus, "T1");
Thread t2 = new Thread(threadGroup, computeStatus, "T2");
for (int i = 0; i < noOfEvents; i++) {
eventDetail = scanner.nextLine();
String[] details = eventDetail.split(",");
HallBooking hallBooking = new HallBooking(details[1],
Double.parseDouble(details[2]),
Integer.parseInt(details[3]),
Integer.parseInt(details[4]));
Event event = new Event(details[0], hallBooking);
eventList.add(event);
computeStatus.setEventList(eventList);
if (i + 1 == noOfEvents / 2) {
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
eventList.clear();
}
if (i + 1 == noOfEvents) {
t2.start();
}
}
} else {
System.out.println("Invalid Input");
}
}
}
Multi-Threading
To illustrate the creation of multiple threads in a program performing concurrent
operations, let us consider the processing of the following mathematical equation:
p = sin (x) + cos (y) + tan (z)
As these trigonometric functions are independent operations without any dependencies
between them, they can be executed concurrently. After that their results can be
combined to produce the final result.

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.

Input & Output Format:


Refer sample Input and Output for formatting specifications.

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));

Sample Input and Output :


Enter the Degree for Sin :
45
Enter the Degree for Cos :
30
Enter the Degree for Tan :
30
Sum of sin, cos, tan = 2.15
 
public class CosClass extends Thread {
double value;
double cos;

public CosClass(double cos) {


// TODO Auto-generated constructor stub
this.cos = cos;
}

@Override
public void run() {

double b = Math.toRadians(cos);
value = Math.cos(b);

}
public double getValue() {

return value;
}

public class SineClass extends Thread {


double value;
double sins;

public SineClass(double sins) {


this.sins = sins;
}

@Override
public void run() {
double b = Math.toRadians(sins);
value = Math.sin(b);

public double getValue() {

return value;
}

public class TanClass extends Thread {


double value;
double tan;

public TanClass(double tan) {


// TODO Auto-generated constructor stub
this.tan = tan;
}

@Override
public void run() {

double b = Math.toRadians(tan);

value = Math.tan(b);
}

public double getValue() {

return value;
}

import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {


// TODO Auto-generated method stub
DecimalFormat df = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Degree for Sin : ");
double sins = sc.nextDouble();
System.out.println("Enter the Degree for Cos : ");
double coss = sc.nextDouble();
System.out.println("Enter the Degree for Tan : ");
double tans = sc.nextDouble();

SineClass s = new SineClass(sins);


CosClass c = new CosClass(coss);
TanClass t = new TanClass(tans);

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();
}

System.out.println("Sum of sin, cos, tan = " + df.format(s.getValue() + t.getValue() + c.getValue()));

}
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

 Input and Output Format:

There is no input to this program.


Refer sample output for formatting specifications.

 Sample Output:
Maximum exponent :127
Maximum value :3.4028235E38
Number of bits :32

public class Main {


public static void main(String[] args) {
System.out.println("Maximum exponent :"+Float.MAX_EXPONENT+" ");
System.out.println("Maximum value :"+Float.MAX_VALUE+" ");
System.out.println("Number of bits :"+Float.SIZE );
}
}

Converting a String to Double


Many a times we receive the input in String and convert it into other data types
(Double / Integer). Lets practice this simple exercise. Get the input amount as string and
parse it using 'valueOf/parseDouble' method.
 
Create a main class "Main.java". 
 
Create another class file "BillHeader.java" with the following private members
Data Type Variable name
Date issueDate
Date dueDate
Double originalAmount
Double amountOutstanding
Include appropriate getters and setters.
 
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 the issue date as dd/MM/yyyy
12/07/2015
Enter the due date as dd/MM/yyyy
21/08/2015
Enter the original amount
2000
Enter amount paid so far
1000
Issue date: 12/07/2015
Due Date: 21/08/2015
Original amount Rs.2000.0
Amount outstanding Rs.1000.0

import java.util.Date;
import java.util.Scanner;
import java.io.IOException;
import java.text.*;

public class Main {


public static void main(String[] args) throws IOException, ParseException {

Scanner sc = new Scanner(System.in);

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

System.out.println("Enter the issue date as dd/MM/yyyy");

Date issueDate = formatter.parse(sc.nextLine());

System.out.println("Enter the due date as dd/MM/yyyy");


Date dueDate = formatter.parse(sc.nextLine());

System.out.println("Enter the original amount");


Double originalAmount = Double.parseDouble(sc.nextLine());

System.out.println("Enter amount paid so far");


Double paidAmount = Double.parseDouble(sc.nextLine());

Double amountOutstanding = originalAmount - paidAmount;

BillHeader billHeader = new BillHeader();

billHeader.setIssueDate(issueDate);
billHeader.setDueDate(dueDate);
billHeader.setOriginalAmount(originalAmount);
billHeader.setAmountOutstanding(amountOutstanding);

//System.out.println("Issue date: " + formatter.format(billHeader.getIssueDate()) + "\nDue Date: " +


formatter.format(billHeader.getDueDate()) + "\nOriginal amount Rs." + billHeader.getOriginalAmount()
+ "\nAmount outstanding Rs." + billHeader.getAmountOutstanding());
System.out.println(billHeader);
}
}
import java.util.Date;
import java.text.*;
public class BillHeader {
private Date issueDate;
private Date dueDate;
private Double originalAmount;
private Double amountOutstanding;

public BillHeader() {
}

public BillHeader(Date issueDate, Date dueDate, Double originalAmount, Double


amountOutstanding) {
super();
this.issueDate = issueDate;
this.dueDate = dueDate;
this.originalAmount = originalAmount;
this.amountOutstanding = amountOutstanding;
}

public Date getIssueDate() {


return issueDate;
}

public void setIssueDate(Date issueDate) {


this.issueDate = issueDate;
}

public Date getDueDate() {


return dueDate;
}

public void setDueDate(Date dueDate) {


this.dueDate = dueDate;
}

public Double getOriginalAmount() {


return originalAmount;
}

public void setOriginalAmount(Double originalAmount) {


this.originalAmount = originalAmount;
}

public Double getAmountOutstanding() {


return amountOutstanding;
}

public void setAmountOutstanding(Double amountOutstanding) {


this.amountOutstanding = amountOutstanding;
}

@Override
public String toString() {

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");


//return "Issue date: " + issueDate + "\nDue Date: " + dueDate + "\nOriginal amount Rs."
+ originalAmount + "\nAmount outstanding Rs." + amountOutstanding;
return "Issue date: " + formatter.format(getIssueDate()) + "\nDue Date: " +
formatter.format(getDueDate()) + "\nOriginal amount Rs." + getOriginalAmount() + "\nAmount
outstanding Rs." + getAmountOutstanding();
}
}
String Reversal
Write a program to reverse a given string.
 
Input and Output Format:
Input consists of a string.
 
Refer sample input and output for formatting specifications.
All text in bold corresponds to input and the rest corresponds to output.
 
Sample Input and Output:
Enter a string to reverse
Punitha
Reverse of entered string is : ahtinuP

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);

System.out.println("Enter a string to reverse");


String str = sc.nextLine();
StringBuffer sbr = new StringBuffer(str);

// To reverse the string


System.out.println("Reverse of entered string is : " + sbr.reverse());

}
}

String API : startsWith() : Illustration


Write a program to illustrate the use of the method startsWith() defined in the string API.
 
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 and Output 1:
Enter the string
Ampphisoft
Enter the start string
Amphi
"Ampphisoft" does not start with "Amphi"
 
Sample Input and Output 2:
Enter the string
Amphisoft
Enter the start string
Amphi
"Amphisoft" starts with "Amphi"
 

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+'"');
}
}
}

String API : split() : Illustration


This program is to illustrate the use of the method split() defined in the string API.
Write a program to split a string based on spaces (There may be multiple spaces too) and
returns the tokens in the form of an array.
 
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 and Output :
Enter the string
Amphisoft Technologies is             a                  private     organization
The words in the string are
Amphisoft
Technologies
is
a
private
organization
 

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());
}
}
}

Customer Address Using String Builder


We know that Strings are immutable and are placed in a common pool called String Pool.
It is always suggested that if the value of a string variable changes quite often, then the
string pool would keep creating new strings and is considered as a bad practice. In these
cases, the alternate way is to use StringBuilder & StringBuffer.

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

// fill your code here

public class Address {


private String line1;
private String line2;
private String city;
private String country;
private int zipCode;

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;
}

public String getLine1() {


return line1;
}

public void setLine1(String line1) {


this.line1 = line1;
}

public String getLine2() {


return line2;
}

public void setLine2(String line2) {


this.line2 = line2;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

public String getCountry() {


return country;
}

public void setCountry(String country) {


this.country = country;
}

public int getZipCode() {


return zipCode;
}

public void setZipCode(int zipCode) {


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

Scanner sc = new Scanner(System.in);


System.out.println("Enter Address Details :\nEnter Line 1 :");
String line1 = sc.nextLine();
System.out.println("Enter Line 2 :");
String line2 = sc.nextLine();
System.out.println("Enter City :");
String city = sc.nextLine();
System.out.println("Enter Country :");
String country = sc.nextLine();
System.out.println("Enter Zip Code :");
int zipCode = sc.nextInt();

Address address = new Address(line1, line2, city, country, zipCode);


System.out.println(address.toString());
}
}

String API : endsWith() : Illustration


Write a program to illustrate the use of the method endsWith() defined in the string API.
 
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 and Output 1:
Enter the string
Ampphisoft
Enter the end string
softi
"Ampphisoft" does not end with "softi"
 
Sample Input and Output 2:
Enter the string
Amphisoft
Enter the end string
soft
"Amphisoft" ends with "soft"

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();

if( str.endsWith( strEnd ) ) {


System.out.println( "\"" + str + "\"" + " ends with \"" + strEnd + "\"" );
} else {
System.out.println( "\"" + str + "\"" + " does not end with \"" + strEnd + "\"" );
}

}
}

Wrapper Class – Integer II


This program is to illustrate the parseInt() method defined in the Integer Wrapper class.
 
Write a program that accepts 3 String values as input and invokes some of the methods
defined in the Integer Wrapper class.
 
Refer sample input and output. All functions should be performed using the methods
defined in the Integer class.
 
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 and Output :
Enter the binary number
111
Enter the octal number
11
Enter the hexadecimal number
1F
The integer value of the binary number 111 is 7
The integer value of the octal number 11 is 9
The integer value of the hexadecimal number 1F is 31
 

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("Enter the octal number");


String octalNo = scnr.next();

System.out.println("Enter the hexadecimal number");


String hexaDecimalNo = scnr.next();

int binNo = Integer.parseInt(binaryNo,2);


int octNo = Integer.parseInt(octalNo,8);
int hexNo = Integer.parseInt(hexaDecimalNo,16);
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);

}
}

String API : replace() : Illustration


Write a program to illustrate the use of the method replace() defined in the string API.
Two companies enter into a Marketing Agreement and they prepare an Agreement
Draft. After that one of the companies changes its name. The name changes need to be
made in the Agreement Draft as well. Write a program to perform the name changes in
the agreement draft.
 
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 and Output :
Enter the content of the document
Amphi is a private organisation. Amphi is a product based company. EBox is a Amphi
product
Enter the old name of the company
Amphi
Enter the new name of the company
Amphisoft
The content of the modified document is
Amphisoft is a private organisation. Amphisoft is a product based company. EBox is a
Amphisoft product

Equals & == in String


One important property of String literals are that - All String literals are placed in a
common pool called String pool. If I create two string literals with the same content, both
will point to the same object. Moreover, If i reassign the variable to another value, a new
space is created and the existing space is left with the same value. Once a value is
assigned or allocated it is never modified until its destroyed. This is why strings are called
immutable.
"==" operator compares address, but since string literals point to the same location (if
values are same) it returns true.
"equals" operator compares the content of the two strings.

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 ].
 

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 First Customer Details :
Enter Customer Name :
Roger
Enter Customer Email :
[email protected]
Enter Second Customer Details :
Enter Customer Name :
Lee
Enter Customer Email :
[email protected]
The Email ids of Roger and Lee are not equal
Comparing without considering the cases :
The Email ids of Roger and Lee are Equal
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
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'.

1. Create a custom Exception class "OverLimitException" which extends


Exception.
2. Add a constructor which takes a Throwable Object, calls the super class
construtor using super() and prints the output as described in Problem
statement.
Create a class Account with following data members.
Data Type Variable Name
String accountNumber
String accountName
Double dueAmount

Create a class Account with following methods.


Return
Metod Name Function
Type       
    Create a 3 argument constructor.
check the both conditions
validate(String dueDate, Double
Boolean (unpaid amount > $2000 || date
unpaidAmount, Double amount)
crossed more than 45 days).
void display() display the account details
 
Sample Input and Output:
Enter the transaction details
Enter the account number
123456
Enter the account holder name
Madhan
Enter the last due date
01/01/2016
Enter the unpaid amount
500
Enter the transaction amount
5000
Transaction successsfully completed.
Account Number : 123456
Account Name : Madhan
Unpaid Amount : 5500.0
 

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();
}

}
}

You might also like