Sanet - ST Java Coding Programs Nodrm
Sanet - ST Java Coding Programs Nodrm
“You don’t learn to walk by following rules. You learn by doing, and by falling over.”
- Richard Branson
Learning programming is like mastering any other skill: it requires practice, repetition,
and experimentation. We don’t learn by simply following rules and reading theories;
deeper understanding of the concepts and how to apply them to real-world problems.
when we are practicing, we can identify and fix your mistakes more easily. This
helps us to write more e ff i c i e n t and reliable code. It also improves your problem-
problems.
book has over 300 color-coded solved programs for each Java concept, helping
you to learn the concepts in different ways and improve your problem-solving skills
I would like to acknowledge the e ff o r t s of everyone who helped me bring this idea
to life. I dedicate this book to everyone who is taking steps to improve their lives
Happy Reading
Regards,
Chirag Khimani
Java Coding Programs
ISBN: 978-93-6013-662-8
No part of this book may be reproduced in any form or by any electronic or mechanical means,
including information storage & retrieval systems, without written permission from the author.
JAVA BASICS
PROGRAMS
JAVA BASIC PROGRAMS
O u tp u t
Hello World
Write a program to print “Hello” in the 1st line and “World” in the 2nd line
O u tp u t
Hello
World
// Sentence (String)
// Characters (char)
char charVariable = ‘ a ’;
O u tp u t
127
128
500
1032423
1.5
5464564.5
true
int a = 10;
O u tp u t
10.0
10
result = a / c * b + b * a / c - a * c;
O u tp u t
int a = 5;
int b = ++a;
O u tp u t
int a = 5;
int b = a++;
O u tp u t
O u tp u t
true
import java.util.Scanner;
O u tp u t
JAVA OPERATORS
JAVA OPERATORS
import java.util.Scanner;
Output
10
20
Sum=30
import java.util.Scanner;
Output
10
20
30
Average=20
import java.util.Scanner;
Output
Enter a number
10
Write a program to calculate simple interest based on principle, rate of interest and
number of years
import java.util.Scanner;
// Variable Declaration
int noOfYears;
principleAmount = input.nextDouble();
rateOfInterest = input.nextDouble();
noOfYears = input.nextInt();
Output
1000
6.5
20
Write a program to take age from user in years and display his age in a month, days
and minutes
import java.util.Scanner;
// Variable Declaration
int age;
age = input.nextInt();
System. out .println(“ You are “ + age * 365 + “ days old ”);
System. out .println(“ You are “ + age * 365 * 60 + “ minutes old ”);
Output
23
Write a program to take total bill amount and discount percentage from user and print
import java.util.Scanner;
// Variable Declaration
totalBillAmount = input.nextDouble();
discountPercentage = input.nextDouble();
10
Output
1200
10
import java.util.Scanner;
// Variable Declaration
num1 = input.nextInt();
num2 = input.nextInt();
temp = num1;
num1 = num2;
num2 = temp;
Output
10
20
20
10
11
Write a program to swap values of two variables without using third variable using
import java.util.Scanner;
// Variable Declaration
num1 = input.nextInt();
num2 = input.nextInt();
Output
10
20
20
10
Write a program to swap values of two variables without using third variable using
import java.util.Scanner;
12
// Variable Declaration
num1 = input.nextInt();
num2 = input.nextInt();
Write a program to take the temperature in fahrenheit and print it into the celsius
import java.util.Scanner;
// Variable Declaration
double temp;
temp = input.nextDouble();
System. out .println(“ Temperature in Celsius : “ + (temp - 32) * 5 / 9); um1, num2;
13
Output
98.6
Write a program to get marks of three subject from user and print result in percentage
import java.util.Scanner;
// Variable Declaration
double percentage;
mark1 = input.nextInt();
mark2 = input.nextInt();
mark3 = input.nextInt();
Output
60
70
90
Percentage : 73.33333333333333
14
Write a program to convert mega bytes into the kilo bytes (1 MB = 1024 KB)
import java.util.Scanner;
// Variable Declaration
int megabytes;
megabytes = input.nextInt();
Output
50
Write a program to get number of days from user and convert into the seconds
import java.util.Scanner;
// Variable Declaration
int numOfDays;
numOfDays = input.nextInt();
15
Output
Write a program to find area of the circle ( Area of Circle = PI * Radius * Radius )
import java.util.Scanner;
// Variable Declaration
double r adius;
radius = input.nextDouble();
Output
Write a program to get weight in kilogram and convert it into lbs (1 kg = 2.2 lbs)
import java.util.Scanner;
// Variable Declaration
double weightInKg ;
16
weightInKg = input.nextDouble();
Output
Write a program to convert distance from kilometer to miles (1 mile = 1.60934 km)
import java.util.Scanner;
// Variable Declaration
double distanceInKm;
distanceInKm = input.nextInt();
Output
100
Write a program to take number from user and display its last digit
import java.util.Scanner;
17
// Variable Declaration
int num;
num = input.nextInt();
Output
Enter a number
1432
Write a program to take number of balls from user and convert it into the overs and
import java.util.Scanner;
// Variable Declaration
double numOfBalls ;
numOfBalls = input.nextInt();
System. out .println(“ Total it is “ + totalOver + “ over and “ + remainingBall + “ balls ”);
18
Output
17
Write a program to calculate salary of the employee based on number of hours they
Rate as follow
___________________________________________
import java.util.Scanner;
// Variable Declaration
int numOfHours;
int overTimeHours;
numOfHours = input.nextInt();
overTimeHours= input.nextInt();
Output
Write a program to print the discount obtain by the customer based on the total bill
19
import java.util.Scanner;
// Variable Declaration
double originalAmount;
double discountPercentage;
originalAmount = input.nextInt();
discountPercentage = input.nextInt();
Output
Write a program to print total shipping cost to the customer including tax based on
import java.util.Scanner;
// Variable Declaration
double shippingCost;
double finalShippingCost;
shippingCost = input.nextInt();
20
Output
200
Write a program to get weight and height from user and calculate BMI units
import java.util.Scanner;
// Variable Declaration
double weight ;
double height;
double bmiUnit;
weight = input.nextInt();
height = input.nextInt();
Output
72
172
21
Write a program to find volume of the Cuboid based on length, width and height
import java.util.Scanner;
// Variable Declaration
length = input.nextInt();
width = input.nextInt();
height = input.nextInt();
Output
12
12
12
Write a program to find gross salary of the employee from the basic salary
22
import java.util.Scanner;
// Variable Declaration
salary = input.nextInt();
lta = 3000;
sa = salary * 10 / 100;
pf = salary * 12 / 100;
Output
3500
23
CONDITIONAL
STATEMENTS
CONDITIONAL STATEMENTS
Write a program to take number from user and print if it is divisible by 5 or not
import java.util.Scanner;
// Variable Declaration
int num;
num = input.nextInt();
if (num % 5 == 0) {
} else {
Output
10
10 is divisible by 5
import java.util.Scanner;
if (num % 2 == 0) {
25
} else {
Output
55
Odd
Write a program to print greatest number out of two numbers (Assume, numbers are
not equal)
import java.util.Scanner;
} else {
Output
34
12
34 is greatest
26
import java.util.Scanner;
if (num > 0) {
} else {
Output
10
Number is positive
Input Output
____________________________
1 31 day
2 28/29 days
3 31 days
Example
4 30 days
12 31 days
import java.util.Scanner;
27
if (month == 1) {
} else if (month == 2) {
} else if (month == 3) {
} else if (month == 4) {
} else if (month == 5) {
} else if (month == 6) {
} else if (month == 7) {
} else if (month == 8) {
} else if (month == 9) {
} else {
Output
31 days
Write a program to print number of days in a given month using Switch Statement
Input Output
____________________________
1 31 days
2 28/29 days
3 31 days
Example
4 30 days
12 31 days
28
import java.util.Scanner;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 10:
case 8:
case 12:
break ;
case 2:
break ;
case 4:
case 6:
case 9:
case 11:
break ;
default :
System. out .print(“ Please enter valid input from 1 to 12 only ”);
Output
31 days
29
Write a program to print name of the day from the given number
Input Output
____________________________
0 Sunday
1 Monday
2 Tuesday
Example
3 Wednesday
6 Saturday
import java.util.Scanner;
if (dayOfWeek == 0) {
} else if (dayOfWeek == 1) {
} else if (dayOfWeek == 2) {
} else if (dayOfWeek == 3) {
} else if (dayOfWeek == 4) {
} else if (dayOfWeek == 5) {
} else if (dayOfWeek == 6) {
} else {
Output
12
30
Marks Grade
____________________________
90 to 100 A+
80 to 89 A
70 to 79 B+
60 to 69 B
Example
50 to 59 C+
40 to 49 C
0 to 39 Fail
import java.util.Scanner;
} else {
Output
55
C+
31
Write a program to calculate final bill of customer after giving appropriate discount
Amount Discount
_______________________________________
import java.util.Scanner;
System. out .println(“ You’ve given 15% Discount. your final bill is “ + billAmount * 0.85);
System. out .println(“ You’ve given 10% Discount. your final bill is “ + billAmount * 0.90);
System. out .println(“ You’ve given 5% Discount. your final bill is “ + billAmount * 0.95);
System. out .println(“ You’ve given 0% Discount. your final bill is “ + billAmount);
} else {
System. out .println(“ Please contact our admin office your bill is incorrect ”);
Output
9500
32
Input Output
__________________________________________
import java.util.Scanner;
} else {
Output
33
53
12
53 is greatest
Vowel characters - a, e, i, o, u
Input Output
__________________________________________
a a is vowel
b b is not vowel
Example
33
import java.util.Scanner;
char c = ‘ r ’;
if (c == ‘ a ’ || c == ‘ e ’ || c == ‘ i ’ || c == ‘ o ’ || c == ‘ u ’) {
} else {
Output
Not Vowel
Please brainstorm and write above program to include capital letters as well
Input Output
__________________________________________
10,20, Add 30
import java.util.Scanner;
34
switch ( choice ) {
case “Add”:
break ;
case “Sub”:
break ;
case “Mul”:
break ;
case “Div”:
break ;
default :
System. out .print(“ This calculator only supports Add, Div, Mul & Sub ”);
Output
13
15
Add
28
Write a program to take username and password from user and print appropriate
dbUsername dbPassword
________________________________________________________
3312 1234
Data
Input Output
_________________________________________________________________________________________
35
if (username == dbUsername) {
if (password == dbPassword) {
} else {
} else {
if (password == dbPassword) {
} else {
Output
1234
3333
Incorrect password
Rating Message
__________________________________________
5 Very Good
4 Good
3 Average
Example
2 Poor
1 Very Poor
36
import java.util.Scanner;
switch (rating) {
case 5:
break ;
case 4:
break ;
case 3:
break ;
case 2:
break ;
case 1:
break ;
default :
Output
Average
Input Output
__________________________________________
2 Notes of 20
Example
3 Notes of 5
37
import java.util.Scanner;
if (result > 0) {
amount = amount % 500; // We will remove the amount that is multiple of 500
// Divide amount with 100 on remainder amount so we will get number of notes of 100
if (result > 0) {
amount = amount % 100; // We will remove the amount that is multiple of 100
if (result > 0) {
if (result > 0) {
result = amount / 5;
if (result > 0) {
amount = amount % 5;
result = amount / 2;
if (result > 0) {
amount = amount % 2;
if (amount > 0) {
38
Output
365
Write a program to reads power consumed in units and print amount to be paid by
customer
________________________________________________________________________________
If unit is 401 or more Fixed Fee of USD 220 + USD 0.85 per unit
Input Output
__________________________________________
672 791.2
Example
import java.util.Scanner;
double totalPrice = 0;
} else {
Output
672
39
Write a program to print FIFA world cup team captain based on team name entered by
user
Team Captain
______________________________________________
Input Output
__________________________________________
switch (teamName) {
case “Qatar”:
break ;
case “Netherlands”:
break ;
case “Argentina”:
break ;
case “Portugal”:
break ;
case “Brazil”:
break ;
case “Serbia”:
break ;
case “Switzerland”:
break ;
40
case “Cameroon”:
break ;
default :
Output
Portugal
Cristiano Ronaldo
Write a program to print a welcome message to the passenger and notify them to do
security checks if they are not coming from connecting flight, and at the end print “enjoy
your flight”
Output Input
__________________________________________________________________________________
System. out .println(“ Are you coming from connecting flight(Yes / No)? ”);
if (!userInput.equalsIgnoreCase(“Yes”)) {
41
Output
no
Write a program to print a welcome message to the traveler and notify them of a 10%
discount if they are returning customers, at the end print the message “Enjoy your stay
here”
Output Input
_________________________________________________________________________________________
if (userInput.equalsIgnoreCase(“Yes”)) {
System. out .println(“ Congratulation!! You have got 10% discount on your stay ”);
Output
Yes
42
Write a program to get three subject marks from the user and print the total percentage
secured by the student. If the percentage is more than or equal to 70 print the message
Output
80
75
65
Write a program to print total shipping cost to the customer including tax based on cost
entered by user, tax rate is decided based on cost as shown in the table below
_________________________________
0 - 999 5%
43
} else {
System. out .println(“ Your total shipping cost including tax is “ + shippingCost);
Output
4300
Write a program to print obesity level of the user based on bmi value calculated from
____________________________________________________
25 - 29.9 overweight
Data
30 - 34.9 obese
// Variable Declaration
44
weight = input.nextDouble();
height = input.nextDouble();
} else {
Output
72
170
Normal
Write a program to find smallest number out of two numbers (Assume both numbers
// Variable Declaration
num1 = input.nextInt();
45
num2 = input.nextInt();
} else {
Output
45
56
45 is smallest
Write a program to get age from user and check if user is Teenager or not
import java.util.Scanner;
} else {
Output
17
46
Write a program to find smallest number out of three numbers (Assume numbers are
not equal)
import java.util.Scanner;
// Variable Declaration
num1 = input.nextInt();
num2 = input.nextInt();
num3 = input.nextInt();
} else {
Output
32
54
13
13 is smallest
47
Write a program to take age and amount from user and print rate of interest of fixed
_______________________________________________________
import java.util.Scanner;
// Variable Declaration
age = input.nextInt();
amount = input.nextInt();
} else {
} else {
} else {
Output
54
35000
7.0%
48
Write a program to take age and weight from the user and check if they are eligible for
___________________________________________________________________________________
import java.util.Scanner;
// Variable Declaration
age = input.nextInt();
weight = input.nextInt();
System. out .println(“ You are too young to donate blood ”);
} else {
} else {
} else {
Output
43
65
49
Write a program to take salary and existing loan amount from user and decide their
_______________________________________________________________________________
import java.util.Scanner;
// Variable Declaration
salary = input.nextInt();
existingLoan = input.nextInt();
else {
} else {
} else {
50
Output
35000
15000
25000
Write a program to calculate income tax of the employee from the total salary
_________________________________________________________________________________
Up to 3000 0%
import java.util.Scanner;
// Variable Declaration
int salary;
double incomeTax;
salary = input.nextInt();
incomeTax = 0;
incomeTax = (salary - 12000) * 0.2 + 3000 * 0.15 + 3000 * 0.1 + 3000 * 0.05;
} else {
incomeTax = (salary - 15000) * 0.3 + 3000 * 0.2 + 3000 * 0.15 + 3000 * 0.1 + 3000 * 0.05;
51
Output
18000
52
FOR LOOP
FOR LOOP
O u tp u t
10
if (i % 2 == 0) {
1
}
APPROACH
54
}
APPROACH
O u tp u t
10
O u tp u t
10
55
int num = 5;
O u tp u t
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50
if (i % 3 == 0) {
}
APPROACH
}
APPROACH
56
O u tp u t
12
15
18
// Because we are printing two lines in one iteration so we’ll execute loop 5 time only
O u tp u t
10
// Initialize sum variable to 0. This variable will hold the sum of the numbers.
int sum = 0;
57
sum = sum + i;
O u tp u t
55
int sum = 0;
if (i % 2 == 0) {
sum = sum + i;
O u tp u t
30
int sum = 0;
if (i % 3 == 0 || i % 5 == 0) {
sum = sum + i;
O u tp u t
593
58
int sum = 0;
if (i % 3 == 0) {
sum = sum - i;
} else {
sum = sum + i;
O u tp u t
19
double sum = 0;
O u tp u t
7.980122655122655
Can you guess the answer, why we need to take i double instead of int?
int sum = 0;
59
sum = sum + i;
O u tp u t
55
Java program to find sum of 1^2 + 2^2 + 3^2 + 4^2 + 5^2 +...+ 10^2
int sum = 0;
O u tp u t
385
import java.util.Scanner;
// We will store multiplication in mul variable, and we will start with initial value 1
int mul = 1;
mul = mul * i;
60
O u tp u t
120
Input Output
____________________________
6 1,2,3,6
14 1,2,7,14
Example
import java.util.Scanner;
if (num % i == 0) {
O u tp u t
12
Factors: 1 2 3 4 6 12
61
Perfect number is a positive integer that is equal to the sum of its positive
Input Output
____________________________
import java.util.Scanner;
int sum = 0;
if (num % i == 0) {
sum = sum + i;
if (sum == num) {
} else {
O u tp u t
28
62
import java.util.Scanner;
int count = 0;
if (num % i == 0) {
count++;
// If number of divisor is exactly 2 then it is prime number as it is divisible only by 1 and itself
if (count == 2) {
} else {
O u tp u t
13
Prime
if (i % 2 == 1) {
63
O u tp u t
int num = 1;
O u tp u t
11
20
28
35
41
46
50
53
55
56
int num = 1;
64
O u tp u t
16
32
64
65
WHILE LOOP
WHILE LOOP
int i = 1;
Output
10
int i = 1;
if (i%2==0){
i++;
67
Output
10
int i = 1;
i = i * 2;
Output
16
32
64
Write a program to print each digit of the number into separate line in reverse order
Input Output
____________________________
5232 2
3
Example
Concept Reminder
When we do num % 10 then it will give us the last digit from the number
When we do num / 10 then it will give us the number without the last digit
68
import java.util.Scanner;
int lastDigit;
while (num != 0) {
Output
35434
Input Output
____________________________
5232 4
34343 5
Example
import java.util.Scanner;
69
while (num != 0) {
// Increment the count and each time remove the last digit from the number
count++;
Output
45448
Write a program to print sum of each digits from the given number
Input Output
____________________________
5232 12
34343 17
Example
import java.util.Scanner;
while (num != 0) {
70
Output
6456789
45
Input Output
____________________________
73453 7
843179 9
Example
import java.util.Scanner;
while (num != 0) {
// Compare each digit with our assumed digit, if any digit is greater than our assumed
max = lastDigit;
71
Output
346454
Input Output
____________________________
73453 35337
843179 971348
Example
import java.util.Scanner;
int rev = 0;
while (num != 0) {
Output
12345
54321
72
Input Output
____________________________
12321 Palindrome
import java.util.Scanner;
int rev = 0;
while (num != 0) {
if (rev == originalNum) {
} else {
Output
643534
Not Palindrom
Input Output
____________________________
20 0 1 1 2 3 5 8 13
30 0 1 1 2 3 5 8 13 21
Example
import java.util.Scanner;
73
int num1 = 0;
int num2 = 1;
num1 = num2;
num2 = sum;
Output
12
0 1 1 2 3 5 8
Armstrong number is a number that is equal to the sum of cubes of its digits
Input Output
_________________________________________
1 + 125 + 27
Example
=153
import java.util.Scanner;
74
if (originalNum == sum) {
} else {
Output
153
Armstrong
import java.util.Scanner;
int decimal = 0, i = 0;
i++;
75
Output
1101
13
import java.util.Scanner;
num = num / 2;
Output
17
10001
Java program to find sum of digit of a given number until the final sum is in single digit
Input Output
_________________________________________
864 8 + 6 + 4 = 18
1 + 8
Example
= 9
import java.util.Scanner;
76
int sum = 0;
num = sum;
sum = 0;
Output
34567
Given number is Magic number, if the sum of its digits are calculated till a
single digit is 1
Input Output
_________________________________________
325 3 + 2 + 5 = 10
1 + 0
Example
= 1
import java.util.Scanner;
77
int sum = 0;
num = sum;
sum = 0;
if (num == 1) {
} else {
Output
325
It is Magic Number
A number is called a spy number if the sum and product of its digits are equal
Input Output
_________________________________________
132 Product : 1 * 3 * 2 = 6
Sum : 1 + 3 + 2 = 6
Example
import java.util.Scanner;
78
if (product == sum) {
} else {
Output
217
79
DO WHILE LOOP
DO WHILE LOOP
Write a program to print addition of two numbers until user enters ‘No’
Input Output
_______________________________________________________________
10 20 30
Press 2 for No
Yes
Example
20 40 60
Press 2 for No
No
import java.util.Scanner;
int userChoice;
do {
userChoice = input.nextInt();
Output
10 20
30
81
Press 2 for No
50 100
150
Press 2 for No
Write a program to check given number is prime or not until user enters ‘No’
Input Output
_______________________________________________________________
20 Not prime
Press 2 for No
Yes
Example
13 prime
Press 2 for No
No
import java.util.Scanner;
int userChoice;
do {
if (num % i == 0) {
82
count++;
// If number of divisor is exactly 2 then it is prime number as it is divisible only by 1 and itself
if (count == 2) {
} else {
userChoice = input.nextInt();
Output
20
Not Prime
Press 2 for No
11
Prime
Press 2 for No
Write a program to Develop ATM machine algorithm using do while loop that supports
three operation
1. Withdraw
2. Deposit
3. Check Balance
83
import java.util.Scanner;
do {
switch (choice) {
case 1:
amount = input.nextInt();
break ;
case 2:
amount = input.nextInt();
break ;
case 3:
break ;
default :
repeatOperation = input.nextInt();
84
Output
10000
1. Withdraw
2. Deposit
3. Check Balance
500
Press 2 for No
1. Withdraw
2. Deposit
3. Check Balance
Press 2 for No
85
NESTED LOOP
NESTED LOOP
12345
12345
12345
12345
12345
int numOfRows = 5;
11111
22222
33333
44444
55555
int numOfRows = 5;
87
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
31 32 33 34 35
counter++;
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
88
// If counter value reaches 3 then activate the flag so that we will decrement
counter++;
} else {
isDecrementActivated = true;
counter--;
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
int numOfRows = 5;
89
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
int numOfRows = 5;
1 2 3 4 5
1 2 3 4 5
2 4 6 8 10
2 4 6 8 10
3 6 9 12 15
3 6 9 12 15
4 8 12 16 20
4 8 12 16 20
5 10 15 20 25
5 10 15 20 25
90
multiplier++;
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
int numOfRows = 5;
A A A A A
A A A A A
B B B B B
B B B B B
C C C C C
C C C C C
D D D D D
D D D D D
E E E E E
E E E E E
91
int numOfRows = 5;
char ch = ‘ A ’;
Write a program to print following pattern in the output from given String
Example Ouptut
J J J J
J J J J
A A A A
A A A A
V V V V
V V V V
A A A A
A A A A
import java.util.Scanner;
92
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
int numOfRows = 5;
if (i == j) {
} else {
0 0 0 0 0
0 1 1 1 0
0 1 1 1 0
0 1 1 1 0
0 0 0 0 0
int numOfRows = 5;
93
if (i == 1 || i == numOfRows || j == 1 || j == numOfRows) {
} else {
1 1 1 1 1
0 1 1 1 1
0 0 1 1 1
0 0 0 1 1
0 0 0 0 1
int numOfRows = 5;
if (j >= i) {
} else {
94
1 1 1 1 1
0 0 0 0 0
1 1 1 1 1
0 0 0 0 0
1 1 1 1 1
int numOfRows = 5;
if (i % 2 == 0) {
} else {
1 0 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 0 1
int numOfRows = 5;
if (j % 2 == 0) {
95
} else {
* * * * *
* * * * *
* *
* *
* *
* *
* *
* *v
* * * * *
* * * * *
int numOfRows = 5;
if (i == 1 || i == numOfRows || j == 1 || j == numOfRows) {
} else {
96
* * * * *
* * * * *
* *
* *
* * * * *
* * * * *
* *
* *
* * * * *
* * * * *
int numOfRows = 5;
if (i == 1 || i == 5 || j == 1 || j == 5 || i == (numOfRows / 2) + 1) {
} else {
12
123
1234
12345
int numOfRows = 5;
97
22
333
4444
55555
int numOfRows = 5;
**
***
****
*****
int numOfRows = 5;
98
54
543
5432
54321
int numOfRows = 5;
45
345
2345
12345
99
int numOfRows = 5;
44
333
2222
11111
int numOfRows = 5;
100
21
321
4321
54321
int numOfRows = 5;
2 3
4 5 6
7 8 9 10
11 12 13 14 15
counter++;
101
1 0
1 0 0
1 0 0 0
1 0 0 0 0
int numOfRows = 5;
if (j == 1) {
} else {
JA
JAV
JAVA
import java.util.Scanner;
102
1 1
12 12
123 123
1234 1234
12345 12345
int numOfRows = 5;
22
22
333
333
4444
4444
55555
55555
103
int numOfRows = 5;
* *
** **
*** ***
**** ****
**********
int numOfRows = 5;
104
C
C
CH
CH
CHI
CHI
CHIR
CHIR
CHIRA
CHIRA
CHIRAG
CHIRAG
import java.util.Scanner;
5
5
54
54
543
543
5432
5432
54321
54321
105
int numOfRows = 5;
5 5
45 45
345 345
23452345
12345
12345
int numOfRows = 5;
106
0
0
11
11
000
000
1111
1111
00000
00000
int numOfRows = 5;
if (i % 2 == 0) {
} else {
1 1
10 10
100 100
1000 1000
10000
10000
107
int numOfRows = 5;
if (j == 1) {
} else {
1
1
222
222
33333
33333
4444444
4444444
555555555
555555555
int numOfRows = 5;
108
*
*
***
***
*****
*****
*******
*******
*********
*********
int numOfRows = 5;
111
111
00000
00000
1111111
1111111
000000000
000000000
109
int numOfRows = 5;
if (i % 2 == 0) {
} else {
1
1
121
121
12321
12321
1234321
1234321
123454321
123454321
int numOfRows = 5;
110
0
0
101
101
11011
11011
1110111
1110111
111101111
111101111
int numOfRows = 5;
if (j == i) {
} else {
111
5
5
545
545
54345
54345
5432345
5432345
543212345
543212345
int numOfRows = 5;
5
5
454
454
34543
34543
2345432
2345432
123454321
123454321
int numOfRows = 5;
112
C C
CHC CHC
CHIHCCHIHC
CHIRIHC
CHIRIHC
CHIRARIHC
CHIRARIHC
CHIRAGARIHC
CHIRAGARIHC
113
1
1
101
101
10001
10001
1000001
1000001
100000001
100000001
int numOfRows = 5;
if (i == 1 || j == 1 || j == 2 * i - 1) {
} else {
114
12345
1234
123
12
int numOfRows = 5;
55555
4444
333
22
int numOfRows = 5;
115
*****
****
***
**
int numOfRows = 5;
54321
5432
543
54
int numOfRows = 5;
116
12345
2345
345
45
int numOfRows = 5;
11111
2222
333
44
int numOfRows = 5;
117
54321
4321
321
21
int numOfRows = 5;
CHIRAG
CHIRA
CHIR
CHI
CH
import java.util.Scanner;
118
12345
12345
1234
1234
123
123
12
12
1
1
int numOfRows = 5;
55555
55555
4444
4444
333
333
22
22
1
1
119
int numOfRows = 5;
*****
*****
****
****
***
***
**
**
*
*
int numOfRows = 5;
120
54321
54321
5432
5432
543
543
54
54
5
5
int numOfRows = 5;
12345
12345
2345
2345
345
345
45
45
5
5
int numOfRows = 5;
121
11111
11111
2222
2222
333
333
44
44
5
5
int numOfRows = 5;
122
54321
54321
4321
4321
321
321
21
21
1
1
int numOfRows = 5;
CHIRAG
CHIRAG
CHIRA
CHIRA
CHIR
CHIR
CHI
CHI
CH
CH
C
C
123
CHIRAG
CHIRAG
HIRAG
HIRAG
IRAG
IRAG
RAG
RAG
AG
AG
G
G
124
555555555
555555555
4444444
4444444
33333
33333
222
222
1
1
int numOfRows = 5;
123454321
123454321
12343211234321
12321 12321
121 121
1 1
int numOfRows = 5;
125
000000000
000000000
1111111
1111111
00000
00000
111
111
0
0
int numOfRows = 5;
if (i % 2 == 0) {
} else {
126
*********
*********
*******
*******
*****
*****
***
***
int numOfRows = 5;
543212345
543212345
5432345
5432345
5434554345
545 545
5 5
int numOfRows = 5;
127
123454321
123454321
2345432
2345432
34543
34543
454
454
5
5
int numOfRows = 5;
128
CHIRAGARIHC
CHIRARIHC
CHIRIHC
CHIHC
CHC
100000001
100000001
1000001
1000001
10001
10001
101 101
1 1
129
int numOfRows = 5;
if (j == 1 || j == 2 * i - 1) {
} else {
1 1
222
33333
33333
4444444
4444444
555555555
555555555
4444444
4444444
33333
33333
222
222
1 1
int numOfRows = 5;
130
*
*
***
***
*****
*****
*******
*******
*********
*********
*******
*******
*****
*****
***
***
*
*
int numOfRows = 5;
131
0
0
111
111
00000
00000
1111111
1111111
000000000
000000000
1111111
1111111
00000
00000
111
111
0
0
int numOfRows = 5;
132
if (i % 2 == 0) {
} else {
if (i % 2 == 0) {
} else {
1
1
121
121
12321
12321
1234321
1234321
123454321
123454321
1234321
1234321
12321
12321
121
121
1
1
133
int numOfRows = 5;
134
0
0
101
101
11011
11011
1110111
1110111
111101111
111101111
1110111
1110111
11011
11011
101
101
0
0
int numOfRows = 5;
if (i == j) {
} else {
if (i == j) {
135
} else {
55
545
545
54345
54345
5432345
5432345
543212345
543212345
5432345
5432345
5434554345
545 545
5 5
int numOfRows = 5;
136
454
34543
2345432
123454321
2345432
34543
454
int numOfRows = 5;
137
C
C
CHC
CHC
CHIHC
CHIHC
CHIRIHC
CHIRIHC
CHIRARIHC
CHIRARIHC
CHIRAGARIHC
CHIRAGARIHC
CHIRARIHC
CHIRARIHC
CHIRIHC
CHIRIHC
CHIHC
CHIHC
CHC
CHC
C
C
import java.util.Scanner;
138
139
1
1
101
101
10001
10001
1000001
1000001
100000001
100000001
1000001
1000001
10001
10001
101
101
1
1
int numOfRows = 5;
if (i == 1 || j == 1 || j == 2 * i - 1) {
} else {
if (j == 1 || j == 2 * i - 1) {
140
} else {
141
STRING PROGRAM
STRING PROGRAM
Input Output
_____________________________________________________________________
import java.util.Scanner;
str = str.toLowerCase();
int vowelCount = 0;
|| str.charAt(i) == ‘ u ’) {
vowelCount++;
Output
Enter a String
10
Write a program to count number of vowels, digit, spaces from the string
Input Output
________________________________________________________________________________
Num of digit - 0
Example
Num of spaces - 6
import java.util.Scanner;
143
switch (str.charAt(i)) {
case ‘ a ’:
case ‘ e ’:
case ‘ i ’:
case ‘ o ’:
case ‘ u ’:
numberOfVowels++;
break ;
case ‘ 0 ’:
case ‘ 1 ’:
case ‘ 2 ’:
case ‘ 3 ’:
case ‘ 4 ’:
case ‘ 5 ’:
case ‘ 6 ’:
case ‘ 7 ’:
case ‘ 8 ’:
case ‘ 9 ’:
digit++;
break ;
case ‘ ‘:
spaces++;
break ;
Output
Enter a String
10
Input Output
____________________________________________________________________
144
import java.util.Scanner;
Output
Enter a String
Write a program to count number of words of String without using library function
Input Output
___________________________________________________________________
import java.util.Scanner;
int frequecyCounter = 0;
if (!str.isEmpty()) {
if (str.charAt(i) == ‘ ‘) {
frequecyCounter++;
} else {
145
Output
Enter a String
Input Output
________________________________________________________________________________
Character : s 3
import java.util.Scanner;
char c = input.next().charAt(0);
int frequecyCounter = 0;
if (str.charAt(i) == ‘c) {
frequecyCounter++;
Output
Enter a String
Enter a character
146
Input Output
___________________________________________
import java.util.Scanner;
}
APPROACH
Output
Elon Musk
Write a program to take full name from the user and print initials from the name
Input Output
______________________________________________
import java.util.Scanner;
147
if (name.charAt(i) == ‘ ‘) {
Output
Elon Musk
Initials - E.M.
Input Output
_____________________________________________________
import java.util.Scanner;
int count = 0;
if (str.charAt(i) == ‘ ‘) {
count++;
148
Output
Spaces - 4
Two strings are said to be anagrams, if they contain the same characters but
in a different order
Input Output
__________________________________________________
import java.util.Scanner;
Arrays.sort(array1);
Arrays.sort(array2);
if Arrays.equals(array1, array2)) {
} else {
Output
Earth
149
Heart
Anagram
Input Output
_____________________________________
level palindrome
Example
import java.util.Scanner;
if str.equals(rev)) {
} else {
Output
moodoom
Palindrome
Input Output
______________________________________________________
150
import java.util.Scanner;
int frequency = 0;
frequency++;
array[j] = ‘ ‘;
if (frequency > 0) {
Output
Input Output
______________________________________________________________________________
import java.util.Scanner;
151
int frequency = 0;
frequency++;
array[j] = null;
if (frequency > 0) {
Output
Java
and
Input Output
________________________________________________________________________________
import java.util.Scanner;
152
// If we find any word that is greater than our current max word then we will assign new
maxLength = words[i].length();
maxString = words[i];
Output
Learning java programming is not easy but once you learn java it is easy and interesting
programming
Input Output
______________________________________________________________________________
import java.util.Scanner;
153
// If we find any word that is greater than our current max word then we will assign new
minLength = words[i].length();
minString = words[i];
Output
Learning java programming is not easy but once you learn java it is easy and interesting
is
Write a program to find length of the String without using the length() function
Input Output
_____________________________________
programming 11
Example
import java.util.Scanner;
int count = 0;
APPROACH
count++;
import java.util.Scanner;
2
154
int count = 0;
try {
while (true) {
str.charAt(count);
count++;
} catch (StringIndexOutOfBoundsException e) {
Output
programming
11
import java.util.Scanner;
Output
155
java 4
revision 8
notes 5
and 3
java 4
programming 11
puzzules 8
Write a program to replace all spaces in the String with the back slash
Input Output
______________________________________________________________________________
import java.util.Scanner;
Output
Learning java programming is not easy but once you learn java it is easy and interesting
Learning\java\programming\is\not\easy\but\once\you\learn\java\it\is\easy\and\interesting
Write a program to encode the given String using Caeser Cipher Algorithm
Input Output
_____________________________________________________________________________
abcdefghijklmnopqrstuvwxyz
Shift : 23 wxyzabcdefghijklmnopqrstuv
Example
easyjava
Shift : 5 jfxdofaf
156
import java.util.Scanner;
Output
easyjava
jfxdofaf
Input Output
______________________________________________________________________________
easy but once you learn java it is ysae tub ecno uoy nrael avaj ti si
import java.util.Scanner;
157
} rev = rev + “ “;
Output
Learning java programming is not easy but once you learn java it is easy and interesting
gninrael avaj gnimmargorp si ton ysae tub ecno uoy nrael avaj ti si ysae dna gnitseretni
Input Output
_____________________________________________
programming puzzules r
Example
import java.util.Scanner;
//If first index of character is equals to last index of character then that character is unique
if (str.indexOf(c) == str.lastIndexOf(c)) {
isFound = true;
break ;
158
// If value of isFound is still false then it means that we do not have unique character of String
//is empty
if (!isFound) {
Output
javajava
-1
Input Output
______________________________________________________________________________
import java.util.Scanner;
int count = 1;
if (words[i].equalsIgnoreCase(words[j])) {
count++;
// make another word blank otherwise it will get count more than one time
words[j] = “”;
159
Output
Write a program to check given string is palindrome or not ignoring the space and case
Input Output
___________________________________________________
import java.util.Scanner;
if (str.equals(rev)) {
} else {
Output
Yo banana boy
Palindrome
160
Input Output
________________________________________
aabbbccddd a2b3c2d4
Example
import java.util.Scanner;
int count = 1;
char c = str.charAt(0);
if (c == str.charAt(i)) {
count++;
} else {
count = 1;
c = str.charAt(i);
Output
aaabcccddddd
a3
b1
c3
d5
Input Output
______________________________________________________________________________________
Learning java is now feels easy ease feels now is java Learning
Example
161
import java.util.Scanner;
Output
162
USING ARRAY
USING ARRAY
Input Output
_____________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
if (targetNumber == numbers[i]) {
System .out.println(i);
isFound = true ;
if ( ! isFound) {
System .out.println( -1 );
Output
56 24 75 43 65
24
Input Output
_____________________________________________________________________
164
import java.util.Scanner;
numbers[i] = input.nextInt();
max = num;
System .out.println(max);
Output
56 24 75 43 65
75
Input Output
_____________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
int sum = 0 ;
165
System .out.println(sum);
Output
56 23 74 45 65
263
Input Output
_____________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
int sumEvn = 0 ;
int sumOdd = 0 ;
if (numbers[i] % 2 == 0 ) {
} else {
System .out.println(sumOdd);
System .out.println(sumEvn);
166
Output
56 24 75 43 65
183
80
Input Output
_____________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
if (num >= 0 ) {
positiveCount ++ ;
} else {
negativeCount ++ ;
System .out.println(positiveCount);
System .out.println(negativeCount);
Output
56 -24 -75 43 65
167
Input Output
____________________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
if (targetNum == num) {
isNumberFound = true ;
if (isNumberFound) {
} else {
Output
56 -24 -75 43 65
65
65 is in the array
168
Input Output
_____________________________________________________________________
import java.util.Scanner;
int count = 0 ;
numbers[i] = input.nextInt();
count = 0 ;
count ++ ;
if (count > 0) {
System .out.println(numbers[i]);
Output
54 54 54 56 56
54
56
169
Write a program to print the elements of an array present in the odd position
Input Output
_____________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
int count = 0 ;
if (i % 2 == 1 ) {
System .out.println(numbers[i]);
Output
45 23 76 23 56
23
23
Input Output
__________________________________________________________________________________________
import java.util.Scanner;
170
numbers[i] = input.nextInt();
// Check each number with current number and if we find any number less than current number,
numbers[i] = numbers[j];
numbers[j] = temp;
System .out.println(num);
Output
45 23 76 23 56
Sorted Array
23
23
45
56
76
Input Output
_____________________________________________________________________
import java.util.Scanner;
171
numbers[i] = input.nextInt();
int count = 1 ;
count = 1 ;
count ++ ;
numbers[i] = Integer.MAX_VALUE;
System .out.println(numbers[i]);
Output
54 54 54 56 56
54
56
Write a program to segregate odd and even numbers from the array
Segregate odd numbers on left and even are on right side of the array
Input Output
_________________________________________________________________________________________
import java.util.Scanner;
172
numbers[i] = input.nextInt();
left ++ ;
right -- ;
numbers[left] = numbers[right];
numbers[right] = temp;
System .out.print(num + “ “ );
Output
52 54 13 77 80
Result Array
77 13 54 52 80
Write a program to find two elements in the array whose sum is equal to a given
number
Input Output
_____________________________________________________________________
173
import java.util.Scanner;
numbers[i] = input.nextInt();
System .out.println(numbers[i]);
System .out.println(numbers[j]);
Output
3 4 7 2 7
Input Output
______________________________________________________________________________________
import java.util.Scanner;
174
numbers[i] = input.nextInt();
if (numbers[i] == targetNum) {
isElementFound = true ;
targetPosition = i;
break ;
if (isElementFound) {
if (i != targetPosition) {
anotherArray[j] = numbers[i];
j ++ ;
} else {
Output
52 54 13 77 80
13
Result Array
52 54 77 80
175
Input Output
_____________________________________________________________________________________________
import java.util.Scanner;
numbers[i] = sc.nextInt();
if (i == targetPosition) {
anotherArray[j] = targetNum;
j ++ ;
anotherArray[j] = numbers[i];
j ++ ;
176
Output
52 54 13 77 80
12
Result Array
52 54 12 13 77 80
Write a program to convert each element of an array in reverse order for integer
array
Input Output
_________________________________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
int rev = 0 ;
num = num / 10 ;
numbers[i] = rev;
177
Output
52 54 13 77 32
Result Array
25 45 31 77 23
Write a program to convert each element of an array in reverse order for String array
Input Output
_____________________________________________________________________________________________
Enter five String : Java Python Ruby Test Automation Result Array : avaJ nohtyP
Example
import java.util.Scanner;
listOfString[i] = input.next();
listOfString[i] = rev;
Output
Result Array
178
Input Output
_____________________________________________________________________________________________
32
import java.util.Scanner;
array1[i] = input.nextInt();
array2[i] = input.nextInt();
if (array1[i] == array2[j]) {
System .out.println(array1[i]);
break ;
Output
Test Case 1
52 54 13 77 32
53 52 17 32 15
52
32
179
Test Case 2
15 15 15 15 15
15 15 15 14 14
15
15
15
15
15
Please brainstorm how to print unique common elements between two arrays?
Input Output
__________________________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
int count = 1 ;
count ++ ;
180
int noOfUniqueElement = 0 ;
noOfUniqueElement ++ ;
anotherArray[j] = numbers[i];
j ++ ;
System .out.println(num);
Output
56 56 76 56 43
Result Array
76
56
43
Input Output
_________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
181
secondMax = max;
max = num;
secondMax = num;
System .out.println(secondMax);
Output
5 4 3 2 1
Input Output
_________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
secondMin = min;
min = num;
182
secondMin = num;
System .out.println(secondMin);
Output
1 2 3 4 5
Input Output
_________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
min = num;
System .out.println(min);
Output
56 56 76 56 43
43
183
Input Output
_________________________________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
int index = 0 ;
if (num != 0 ) {
numbers[index] = num;
index ++ ;
numbers[index] = 0 ;
index ++ ;
Output
31 0 34 0 0
Result Array
31 34 0 0 0
184
Write a program to count number of odd and even number in the array
Input Output
____________________________________________________________________________________
No of odd element is 3
import java.util.Scanner;
numbers[i] = input.nextInt();
if (num % 2 == 0 ) {
even ++ ;
} else {
odd ++ ;
Output
34 45 23 56 23
No of even element is 2
No of odd element is 3
Write a program to find the sum of array elements except largest and smallest
Input Output
__________________________________________________________________
185
import java.util.Scanner;
numbers[i] = input.nextInt();
int sum = 0 ;
smallest = num;
largest = num;
sum += numb;
System .out.println(sum);
Output
34 45 23 56 23
102
Write a Java program to find the length of the longest consecutive elements
Input Output
______________________________________________________________________________________
186
import java.util.Scanner;
numbers[i] = input.nextInt();
if (numbers[i] + 1 == numbers[i + 1 ]) {
} else {
temp = 1 ;
count = temp;
System .out.println(count);
Output
3 4 7 8 9 10 43 45 46 47 9
Write a Java program to find the two elements from a given array of whose sum is
Input Output
__________________________________________________________________
187
import java.util.Scanner;
numbers[i] = input.nextInt();
// First find sum of two elements and check if it is less than our min value,
// then update the min variable just like how we find the smallest number from array
int num1 = 0 ;
int num2 = 0 ;
// If current sum is less than minSum then update the value of minSum
num1 = numbers[i];
num2 = numbers[j];
minSum = currentSum;
Output
12 3 0 -1 1
-1 1
Write a Java program to find maximum product of two integers in a given array of
integers
Input Output
__________________________________________________________________
188
import java.util.Scanner;
numbers[i] = input.nextInt();
int maxProduct = 0 ;
maxProduct = currentProduct;
System .out.println(maxProduct);
Output
12 3 0 -1 1
36
int columnSum = 0 ;
189
System .out.println(columnSum);
Output
Frequency=3
Write a program to find sum of each row from two dimention array
int sum = 0 ;
sum = 0 ;
System .out.println(sum);
Output
22
13
18
190
max = data[i][j];
System .out.println(max);
Output
931
191
USER DEFINED
METHODS
USER DEFINED METHODS
Input Output
_____________________________________________________________________
import java.util.Scanner;
if (num == reverse) {
} else {
while (num != 0 ) {
lastDigit = num % 10 ;
num = num / 10 ;
return reverse;
Output
Enter a number
1441
Palindrom
if (isPalindromeNumber(i)) {
193
while (num != 0 ) {
lastDigit = num % 10 ;
num = num / 10 ;
if (reverse == originalNum) {
return true ;
} else {
return false ;
Output
11 22 33 44 55 66 77 88 99 101 111 121 131 141 151 161 171 181 191
if (isPrime(i)) {
int divisor = 0 ;
if (num % i == 0 ) {
divisor ++ ;
return divisor == 0 ;
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
194
if (isArmstrongNumber(i)) {
remainder = num % 10 ;
num = num / 10 ;
Output
Write a user defined function fact() that takes one number and return factorial of the
given number
Input Output
_________________________________________________________________
import java.util.Scanner;
System .out.println(fact(num));
195
int fact = 1 ;
fact = fact * i;
return fact;
Output
Enter a number
120
Write a user defined function isEven() that takes one number and return true if given
Input Output
_________________________________________________________________
import java.util.Scanner;
System .out.println(isEven(num));
if (num % 2 == 0 ) {
return true ;
} else {
return false ;
Output
Enter a number
23
false
196
Write a user defined function getMaxValue() that takes array of integers and return
Input Output
_________________________________________________________________
import java.util.Scanner;
numbers[i] = input.nextInt();
System .out.println(getMaxValue(numbers));
max = num;
return max;
Output
54 76 87 23 43
87
Write a user defined function getMinValue() that takes array of integers and return
Input Output
_________________________________________________________________
197
import java.util.Scanner;
numbers[i] = input.nextInt();
System .out.println(getMinValue(numbers));
min = num;
return min;
Output
54 76 87 23 43
23
Write a user defined function getSum() that takes array of integers and return sum of
Input Output
_________________________________________________________________
import java.util.Scanner;
198
numbers[i] = input.nextInt();
System .out.println(getMinValue(numbers));
int sum = 0 ;
return sum;
Output
54 76 87 23 43
283
Write a program to print greatest number out of four numbers using user defined
Input Output
_________________________________________________________________
import java.util.Scanner;
num1 = input.nextInt();
num2 = input.nextInt();
num3 = input.nextInt();
num4 = input.nextInt();
199
return num1;
} else {
return num2;
Output
67
23
56
43
67
Write a user defined function getRev() that takes one String value and return reverse
of that String
Input Output
_________________________________________________________________
import java.util.Scanner;
System .out.println(getRev(str));
return rev;
200
Output
Chirag
garihC
Input Output
___________________________________________________________________________________________
import java.util.Scanner;
System .out.println(num1 + " & " + num2 + " are twin prime number" );
} else {
System .out.println(num1 + " & " + num2 + " are not twin prime number" );
int divisor = 0 ;
if (num % i == 0 ) {
divisor ++ ;
return divisor == 0 ;
Output
13
11
201
COLLECTION
COLLECTION
Input Output
____________________________________________________________________________________________
import java.util.Scanner;
listOfElement.add(input.nextInt());
if ( ! setOfData.add(element)) {
System .out.println(element);
Output
34 54 34 56 54
34
54
Input Output
_______________________________________________________________________________
import java.util.Scanner;
203
if ( ! setOfChar.add(str.charAt(i))) {
duplicateChar.add(str.charAt(i));
System .out.println(duplicateChar);
Output
Enter a String
[ , ,r s, c, t, i, l, m, o]
Input Output
____________________________________________________________________________________________
Enter a String : This is my collection program { =4, a=1, c=2, e=1, g=1, h=1,
import java.util.Scanner;
if (frequency.containsKey(str.charAt(i))) {
frequency.put(str.charAt(i), frequency.get(str.charAt(i)) + 1 );
} else {
frequency.put(str.charAt(i), 1);
System .out.println(frequency);
204
Output
{ =4, a=1, c=2, e=1, g=1, h=1, i=3, l=2, m=2, n=1, o=3, p=1, r=2, s=2, t=2, y=1}
Input Output
____________________________________________________________________________
import java.util.Scanner;
if ( ! uniquChar.add(str.charAt(i))) {
dupChar.add(str.charAt(i));
uniquChar.removeAll(dupChar);
System .out.println(uniquChar);
Output
Enter a String
[a, e, g, h, n, p, y]
Write a program to find character from the String that has a greatest frequency
Input Output
____________________________________________________________________________
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
205
if (frequency.containsKey(str.charAt(i))) {
frequency.put(str.charAt(i), frequency.get(str.charAt(i)) + 1 );
} else {
frequency.put(str.charAt(i), 1 );
System .out.println(frequency);
char maxChar = 0 ;
maxValue = pair.getValue();
maxChar = pair.getKey();
Output
Enter a String
{ =3, a=5, g=2, h=3, i=2, j=1, m=3, n=1, o=1, p=2, r=2, s=1, t=1, v=1, w=1}
Write a program to get five numbers from user and sort them in ascending order
Input Output
___________________________________________________________________________________________
Enter five numbers : 45 67 23 12 43 Sorted list: [12, 23, 43, 45, 67]
Example
206
numbers.add(input.nextInt());
Collections.sort(numbers);
Output
45 67 23 12 43
Write a program to get five numbers from user and print all numbers in reverse
sequence
Input Output
___________________________________________________________________________________________
Enter five numbers : 45, 67, 23, 12, 43 Reverse numbers : 43, 12, 23, 67, 45
Example
numbers.add(input.nextInt());
Collections.reverse(numbers);
Output
45 67 23 12 43
207
Write a program to get five numbers from user and print each number in reverse order
Input Output
___________________________________________________________________________________________
Enter five numbers : 45, 67, 23, 12, 43 Reverse elements : 54, 76, 32, 76, 34
Example
numbers.add(input.nextInt());
int rev = 0 ;
num = num / 10 ;
return rev;
Output
45 67 23 12 43
Reverse elements:
54 76 32 21 34
Write a program to get five numbers from user twice and check if both the time they
Input Output
________________________________________________________________________
208
numbers1.add(input.nextInt());
numbers2.add(input.nextInt());
if (result) {
} else {
Output
45 67 23 12 43
23 12 67 43 45
Same
Write a program to get five numbers from user twice and print common numbers
Input Output
___________________________________________________________________________________________
209
numbers1.add(input.nextInt());
numbers2.add(input.nextInt());
numbers1.retainAll(numbers2);
System .out.println(numbers1);
Output
45 67 23 12 43
22 12 67 40 45
names.add( "Maryam" );
names.add( "Emily" );
names.add( "Tim" );
names.add( "Anna" );
System .out.println(name);
210
Output
Emily
Maryam
Tim
Anna
211
class Employee {
String employeeName;
int empId;
double salary;
boolean isEligibleForPromotion;
void workOnWeekend() {
isEligibleForPromotion = true ;
void takeLeave() {
isEligibleForPromotion = false ;
void displayEmployeeData() {
System .out.println(employeeName);
System .out.println(empId);
System .out.println(salary);
System .out.println(isEligibleForPromotion);
employee1.employeeName = "Mike" ;
employee1.empId = 9454 ;
employee1.salary = 23500.00 ;
employee1.isEligibleForPromotion = true ;
employee2.employeeName = "George" ;
employee2.empId = 6543 ;
employee2.salary = 5400.00 ;
employee2.isEligibleForPromotion = false ;
employee1.displayEmployeeData();
employee1.workOnWeekend();
employee1.displayEmployeeData();
employee2.displayEmployeeData();
employee2.takeLeave();
employee2.displayEmployeeData();
213
Output
Mike
9454
23500.0
true
Mike is on leave
==================
Mike
9454
23500.0
false
==================
George
6543
5400.0
false
==================
George
6543
5400.0
true
class Bank {
String accName;
int balance;
class ATM {
void showBalance(Bank b) {
System .out.println(b.balance);
214
account1.accName = "Mike" ;
account2.accName = "George" ;
account2.deposit( 10000 );
atm.withdraw(account1, 1000 );
atm.showBalance(account1);
atm.showBalance(account2);
Output
4000
10000
Write a program to demonstrate how to store list of Bank Account objects in the list
class Bank {
String accName;
int balance;
account1.deposit( 5000 );
account2.deposit( 3500 );
account3.deposit( 7200 );
listOfAccount.add(account1);
listOfAccount.add(account2);
listOfAccount.add(account3);
215
maxBalance = account.balance;
Output
216
CONSTRUCTOR
AND
STATIC KEYWORD
CONSTRUCTOR AND STATIC KEYWORD
class Bank {
int accountNumber;
String accName;
int balance;
public Bank() {
balance = 1000 ;
accName = "Mike" ;
accountNumber ++ ;
System .out.println(balance);
System .out.println(accName);
System .out.println(accountNumber);
listOfAccount.add(account1);
listOfAccount.add(account2);
account.showAccountData();
Output
1000
Mike
================
1000
Mike
218
class Bank {
int accountNumber;
String accName;
int balance;
balance = balanceFromUser;
accName = accNameFromUser;
accountNumber ++ ;
System .out.println(balance);
System .out.println(accName);
System .out.println(accountNumber);
listOfAccount.add(account1);
listOfAccount.add(account2);
account.showAccountData();
Output
5000
Mike
================
1000
George
219
class Student {
void showTeacherName() {
student1.instructorName = "Instructor1" ;
student1.mentorName = "Mentor1" ;
student2.instructorName = "Instructor2" ;
student2.mentorName = "Mentor2" ;
student3.instructorName = "Instructor3" ;
student3.mentorName = "Mentor3" ;
student1.showTeacherName();
student2.showTeacherName();
student3.showTeacherName();
Output
Instructor - Instructor3
Mentor - Mentor1
Instructor - Instructor3
Mentor - Mentor2
Instructor - Instructor3
Mentor - Mentor3
220
class Student {
void showMentorName() {
Student.instructorName = "Instructor1" ;
Student.showInstructorName();
student1.mentorName = "Mentor1" ;
student1.showMentorName();
Output
Instructor - Instructor1
Mentor - Mentor1
221
INHERITANCE
AND
POLYMORPHISM
INHERITANCE AND POLYMORPHISM
// Parent Class
class BasicCalculator {
// Child Class
basic.sum( 10 , 20 );
basic.sub( 10 , 20 );
ac.sum( 10 , 20 );
ac.mul( 10 , 20 );
ac.sub( 10 , 20 );
ac.div( 10 , 20 );
Output
sum=30
sub=-10
sum=30
Mul=200
sub=-10
Div=0
223
class Bank {
Bank() {
ChaseBank() {
Output
Write a program to demonstrate use of This & Super keyword with variables
class Parent{
System .out.println(a); // 50
c.printData();
224
Output
50
20
10
Write a program to demonstrate use of This & Super keyword with Methods
class Parent {
System .out.println(a);
System .out.println(a);
super .printData();
c.printData();
Output
20
10
Write a program to demonstrate use of This & Super keyword with Constructor
class Parent {
Parent() {
225
Child() {
super ();
System .out.println(name);
Output
Statement 1
Statement 2
Statement 4
Statement 3
class FlightBooking {
System .out.println( "Booking with seat " + seatNumber + " and name " + name);
System .out.println( "Booking with name " + name + " and price " + price);
226
flightBooking.bookTicket();
flightBooking.bookTicket( 200 );
flightBooking.bookTicket( "Mike" );
flightBooking.bookTicket( 12 , "Mike" );
Output
class Bank {
int balance;
@ Override
@ Override
227
cb.displayInterestRate();
wf.displayInterestRate();
Output
5.0
7.0
class Bank {
int balance;
System .out.println(balance);
class PayPal {
b.showBalance();
228
b.displayInterestRate();
payPal.viewInterestRate(chaseBankAccount);
payPal.viewInterestRate(wellsFargoAccount);
payPal.viewBalance(chaseBankAccount);
payPal.viewBalance(wellsFargoAccount);
Output
5.0
7.0
229
ENCAPSULATION
AND
ABSTRACTION
ENCAPSULATION AND ABSTRACTION
class Bank {
accountNumber ++ ;
return balance;
return accountNumber;
return dateOfBirth;
System .out.println(account1.getBalance());
System .out.println(account1.getDateOfBirth());
System .out.println(account1.getDateOfBirth());
231
Output
5000
28 May 1991
08 May 1990
int balance;
@ Override
void displayRateOfInterest() {
void loanBasedOnCreditCardLimit() {
demoBank.displayRateOfInterest();
demoBank.loanBasedOnCreditCardLimit();
Output
7.0%
232
interface Page {
int PAGE_LOAD_TIME = 60 ;
void waitForPageToLoad();
void openPage();
@ Override
@ Override
@ Override
@ Override
page.waitForPageToLoad();
page.openPage();
page.waitForPageToLoad();
page.openPage();
233
Output
234
EXCEPTION HANDLING
EXCEPTION HANDLING
int num[] = { 32 , 54 , 21 , 62 , 34 };
try {
int a = input.nextInt();
int b = input.nextInt();
} catch (InputMismatchException e) {
} catch (ArithmeticException e) {
} catch (Exception e) {
Output
End of program
236
try {
} catch (Exception e) {
} finally {
Output
34
if (dayNum == 0 ) {
} else if (dayNum == 1 ) {
} else if (dayNum == 2 ) {
} else if (dayNum == 3 ) {
} else if (dayNum == 4 ) {
} else if (dayNum == 5 ) {
} else if (dayNum == 6 ) {
} else {
237
Output
at com.java.class38.LadderIfElseExample.main(LadderIfElseExample.java:29)
method3();
int i = 1 , j = 0 ;
method1();
method2();
Output
at com.java.class38.ThrowAndThrowsKeyword.method1(ThrowAndThrowsKeyword.java:10)
at com.java.class38.ThrowAndThrowsKeyword.method2(ThrowAndThrowsKeyword.java:14)
at com.java.class38.ThrowAndThrowsKeyword.method3(ThrowAndThrowsKeyword.java:18)
at com.java.class38.ThrowAndThrowsKeyword.main(ThrowAndThrowsKeyword.java:22)
238