0% found this document useful (0 votes)
6 views243 pages

Sanet - ST Java Coding Programs Nodrm

The document introduces a Java programming book titled 'Java Coding Programs' by Chirag Khimani, emphasizing the importance of learning through practice and experimentation rather than just theory. It contains over 300 color-coded solved programs covering various Java concepts, aimed at improving problem-solving skills. The author expresses gratitude to those who contributed to the book and encourages readers to enhance their programming abilities.

Uploaded by

Rohit Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views243 pages

Sanet - ST Java Coding Programs Nodrm

The document introduces a Java programming book titled 'Java Coding Programs' by Chirag Khimani, emphasizing the importance of learning through practice and experimentation rather than just theory. It contains over 300 color-coded solved programs covering various Java concepts, aimed at improving problem-solving skills. The author expresses gratitude to those who contributed to the book and encourages readers to enhance their programming abilities.

Uploaded by

Rohit Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 243

About the Book

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

we must learn by doing, making mistakes, and learning from them.

Programming is a combination of art and skill that cannot be learned solely by

reading books or watching videos. We must practice writing code to develop a

deeper understanding of the concepts and how to apply them to real-world problems.

When we solve problems on our own, it is common to make mistakes. However,

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-

solving skills, as we are challenged to come up with creative solutions to d i ff e r e n t

problems.

I am delighted to introduce a Java book called “Java Coding Programs” . This

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

at the same time.

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

and contribute to the growth of society.

Wishing you all the best in your career

Happy Reading

Regards,

Chirag Khimani
Java Coding Programs

Author ’s Name: Chirag Khimani

Published by: Self-Published

Printed By: Chirag Khimani

Edition Details: First Edition

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.

Copyright © Chirag Khimani 2022


Table of Contents

1. Java Basics Programs 1-5

2. Java Operators 6-23

3. Conditional Statements 24-52

4. For Loop 53-65

5. While Loop 66-79

6. Do While Loop 80-85

7. Nested Loop 86-141

8. String Program 142-162


9. Using Array 163-191

10. User Defined Methods 192-201

11. Collection 202-211

12. Class And Object 212-216

13. Constructor And Static Keyword 217-221

14. Inheritance And Polymorphism 222-229

15. Encapsulation And Abstraction 230-234

16. Exception Handling 235-238


1

JAVA BASICS

PROGRAMS
JAVA BASIC PROGRAMS

Write a program to print “Hello World” in the output

public class HelloWorld {

public static void main(String[] args ) {

System. out . println ( “ Hello World ” );

O u tp u t

Hello World

Write a program to print “Hello” in the 1st line and “World” in the 2nd line

public class HelloWorld {

public static void main(String[] args ) {

System. out .println(“ Hello ”);

System. out .println(“ World ”);

O u tp u t

Hello

World

Write a program to demonstrate the use of java data types

public class DataTypesExamples {

public static void main(String args []) {

// Numbers (byte - 1, short - 2, int - 4, long - 8, float, double)

// Sentence (String)

// Characters (char)

// True or False (boolean)

byte byteVariable = 127;

short shortVariable = 128;

int intVariable = 500;

long longVariable = 1032423L;

float floatVariable = 1.5f;

double doubleVaraible = 5464564.5;

boolean booleanVariable = true;

// Character value needs to be surround with single quotes

char charVariable = ‘ a ’;

Knock the door on [email protected]


JAVA BASIC PROGRAMS

// String value needs to be surround with double quotes

String stringVariable = “ This is java String statement ”;

System. out .println(byteVariable);

System. out .println(shortVariable);

System. out .println(intVariable);

System. out .println(longVariable);

System. out .println(floatVariable);

System. out .println(doubleVaraible);

System. out .println(charVariable);

System. out .println(stringVariable);

System. out .println(booleanVariable);

O u tp u t

127

128

500

1032423

1.5

5464564.5

This is java String statement

true

Write a program to demonstrate the implicit type casting

public class ImplicitTypeCasting {

public static void main(String[] args ) {

int a = 10;

double d = a; // Implicit type casting

System. out .println(d);

System. out .println(a);

O u tp u t

10.0

10

Knock the door on [email protected]


JAVA BASIC PROGRAMS

Write a program to demostrate the operator precedence using arithmetic operator

public class OperatorPrecedence {

public static void main(String[] args ) {

int a = 15, b = 5, c = 3, result;

result = a / c * b + b * a / c - a * c;

System. out .println(result);

O u tp u t

Write a program to demostrate pre increment operator

public class PreIncrementOperator {

public static void main(String[] args ) {

int a = 5;

int b = ++a;

System. out .println(a);

System. out .println(b);

O u tp u t

Write a program to demostrate post increment operator

public class PostIncrementOperator {

public static void main(String[] args ) {

int a = 5;

int b = a++;

System. out .println(a);

System. out .println(b);

O u tp u t

Knock the door on [email protected]


JAVA BASIC PROGRAMS

Write a program to demostrate the operator precedence using logical operator

public class PostIncrementOperator {

public static void main(String[] args ) {

boolean b1 = true, b2 = false, b3 = true;

boolean result = b1 && b2 || b3 && b2 || b2 || b3 && b1;

System. out .println(result);

O u tp u t

true

Write a program to demostrate the use of scanner class

import java.util.Scanner;

public class PostIncrementOperator {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a number - “);

int num1 = input.nextInt();

System. out .println(“ You have entered “ + num1);

System. out .println(“ Please enter your name - “);

String name = input.next();

System. out .println(“ You have entered “ + name);

O u tp u t

Please enter a number - 43

You have entered 43

Please enter your name - Chirag

You have entered Chirag

Knock the door on [email protected]


2

JAVA OPERATORS
JAVA OPERATORS

Write a program to print addition of two numbers

import java.util.Scanner;

public class AdditionOfNumbers {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter first number ”);

int num1 = input.nextInt();

System. out .println(“ Enter second number ”);

int num2 = input.nextInt();

System. out .println(“ Sum =”+(num1 + num2));

Output

Enter first number

10

Enter second number

20

Sum=30

Write a program to print average of three numbers

import java.util.Scanner;

public class AverageOfNumbers {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter first number ”);

int num1 = input.nextInt();

System. out .println(“ Enter second number ”);

int num2 = input.nextInt();

System. out .println(“ Enter third number ”);

int num3 = input.nextInt();

System. out .println(“ Average= “ + (num1 + num2 + num3) / 3);

Knock the door on [email protected]


JAVA OPERATORS

Output

Enter first number

10

Enter second number

20

Enter third number

30

Average=20

Write a program to print squre of given number

import java.util.Scanner;

public class SqureOfNumber{

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter a number ”);

int num = input.nextInt();

System. out .println(“ Squre of number = “ + (num * num));

Output

Enter a number

10

Squre of number = 100

Write a program to calculate simple interest based on principle, rate of interest and

number of years

import java.util.Scanner;

public class SimpleInterest{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double principleAmount, rateOfInterest;

int noOfYears;

Knock the door on [email protected]


JAVA OPERATORS

// Take principle amount from user

System. out .println(“ Enter Principle Amount ”);

principleAmount = input.nextDouble();

// Take rate of interest from user

System. out .println(“ Enter rate of interest ”);

rateOfInterest = input.nextDouble();

// Take number of years from user

System. out .println(“ Enter number of years ”);

noOfYears = input.nextInt();

double interest = principleAmount * rateOfInterest * noOfYears / 100;

System. out .println(“ Simple Interest :- “ + interest);

Output

Enter Principle Amount

1000

Enter rate of interest

6.5

Enter number of years

20

Simple Interest :- 1300.0

Write a program to take age from user in years and display his age in a month, days

and minutes

import java.util.Scanner;

public class AgeInDifferentFormat{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int age;

// Take age from user

System. out .println(“ Enter your age in years ”);

age = input.nextInt();

System. out .println(“ You are “ + age + “ years old ”);

System. out .println(“ You are “ + age * 12 + “ months old ”);

Knock the door on [email protected]


JAVA OPERATORS

System. out .println(“ You are “ + age * 365 + “ days old ”);

System. out .println(“ You are “ + age * 365 * 60 + “ minutes old ”);

Output

Enter your age in years

23

You are 23 years old

You are 276 months old

You are 8395 days old

You are 503700 minutes old

Write a program to take total bill amount and discount percentage from user and print

value of final bill amount after discount

import java.util.Scanner;

public class BillWithDiscount{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double totalBillAmount, discountPercentage;

// Take totalBillAmount from user

System. out .println(“ Enter total bill amount ”);

totalBillAmount = input.nextDouble();

System. out .println(“ Enter discount percentage ”);

discountPercentage = input.nextDouble();

// Calculate total discount amount from the discount percentage

double discountAmount = totalBillAmount * discountPercentage / 100;

// Calculate final amount after deducting discount amount

double finalBill = totalBillAmount - discountAmount;

System. out .println(“ Your final bill after discount is “ + finalBill);

10

Knock the door on [email protected]


JAVA OPERATORS

Output

Enter total bill amount

1200

Enter discount percentage

10

Your final bill after discount is 1080.0

Write a program to swap values of two variables

import java.util.Scanner;

public class SwapTwoVariables{

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int num1, num2, temp;

// Take data from user

System. out .println(“Enter value of num1”);

num1 = input.nextInt();

System. out .println(“Enter value of num2”);

num2 = input.nextInt();

// Swap values of Variables

temp = num1;

num1 = num2;

num2 = temp;

System. out .println(“ Values after swapping ”);

System. out .println(num1);

System. out .println(num2);

Output

Enter value of num1

10

Enter value of num2

20

Values after swapping

20

10

11

Knock the door on [email protected]


JAVA OPERATORS

Write a program to swap values of two variables without using third variable using

Addition and Subtraction

import java.util.Scanner;

public class SwapTwoVariables{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int num1, num2;

// Take data from user

System. out .println(“ Enter value of num1 ”);

num1 = input.nextInt();

System. out .println(“ Enter value of num2 ”);

num2 = input.nextInt();

// Swap values of Variables

num1 = num1 + num2;

num2 = num1 - num2;

num1 = num1 - num2;

System. out .println(“ Values after swapping ”);

System. out .println(num1);

System. out .println(num2);

Output

Enter value of num1

10

Enter value of num2

20

Values after swapping

20

10

Write a program to swap values of two variables without using third variable using

Multiplication and Division

import java.util.Scanner;

public class SwapTwoVariables{

12

Knock the door on [email protected]


JAVA OPERATORS

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int num1, num2;

// Take data from user

System. out .println(“ Enter value of num1 ”);

num1 = input.nextInt();

System. out .println(“ Enter value of num2 ”);

num2 = input.nextInt();

// Swap values of Variables

num1 = num1 * num2;

num2 = num1 / num2;

num1 = num1 / num2;

System. out .println(“ Values after swapping ”);

System. out .println(num1);

System. out .println(num2);

Write a program to take the temperature in fahrenheit and print it into the celsius

Formula: Temp In C = (F-32) * 5 / 9

import java.util.Scanner;

public class FahrenheitToCelsius{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double temp;

// Take data from user

System. out .println(“ Enter temperature in fahrenheit ”);

temp = input.nextDouble();

System. out .println(“ Temperature in Celsius : “ + (temp - 32) * 5 / 9); um1, num2;

13

Knock the door on [email protected]


JAVA OPERATORS

Output

Enter temperature in fahrenheit

98.6

Temperature in Celsius : 37.0

Write a program to get marks of three subject from user and print result in percentage

import java.util.Scanner;

public class ResultInPercentage{

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int mark1, mark2, mark3;

double percentage;

// Take data from user

System. out .println(“ Enter first subject marks ”);

mark1 = input.nextInt();

System. out .println(“ Enter second subject marks ”);

mark2 = input.nextInt();

System. out .println(“ Enter third subject marks ”);

mark3 = input.nextInt();

int totalMarks = mark1 + mark2 + mark3;

percentage = (totalMarks / 300.0 ) * 100;

System. out .println(“ Percentage : “ + percentage);

Output

Enter first subject marks

60

Enter second subject marks

70

Enter third subject marks

90

Percentage : 73.33333333333333

14

Knock the door on [email protected]


JAVA OPERATORS

Write a program to convert mega bytes into the kilo bytes (1 MB = 1024 KB)

import java.util.Scanner;

public class MegaByteToKiloByte{

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int megabytes;

// Take data from user

System. out .println(“ Enter value in megabytes ”);

megabytes = input.nextInt();

System. out .println(“ Value in kilobytes : “ + megabytes * 1024);

Output

Enter value in megabytes

50

Value in kilobytes : 51200

Write a program to get number of days from user and convert into the seconds

import java.util.Scanner;

public class DaysToSeconds{

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int numOfDays;

// Take data from user

System. out .println(“ Enter number of days ”);

numOfDays = input.nextInt();

System. out .println(“ Value in seconds : “ + numOfDays * 24 * 60 * 60);

15

Knock the door on [email protected]


JAVA OPERATORS

Output

Enter number of days

Value in seconds : 86400

Write a program to find area of the circle ( Area of Circle = PI * Radius * Radius )

import java.util.Scanner;

public class AreaOfCircle{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double r adius;

// Take data from user

System. out .println(“ Enter radius of circle ”);

radius = input.nextDouble();

System. out .println(“ Weight in LBS : “ + radius * radius * 3.14);

Output

Enter radius of circle

Weight in LBS : 50.24

Write a program to get weight in kilogram and convert it into lbs (1 kg = 2.2 lbs)

import java.util.Scanner;

public class KilogramToLBS{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double weightInKg ;

16

Knock the door on [email protected]


JAVA OPERATORS

// Take data from user

System. out .println(“ Enter weight in kilogram ”);

weightInKg = input.nextDouble();

System.out.println(“ Weight in LBS : “ + weightInKg * 2.2);

Output

Enter number of days

Value in seconds : 86400

Write a program to convert distance from kilometer to miles (1 mile = 1.60934 km)

import java.util.Scanner;

public class MegaByteToKiloByte{

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double distanceInKm;

// Take data from user

System. out .println(“ Enter the distance value in kilometer ”);

distanceInKm = input.nextInt();

System. out .println(“ The distance in miles : “ + distanceInKm / 1.60934);

Output

Enter the distance value in kilometer

100

The distance in miles : 62.137273664980675

Write a program to take number from user and display its last digit

import java.util.Scanner;

public class LastDigitOfNumber{

17

Knock the door on [email protected]


JAVA OPERATORS

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int num;

// Take data from user

System. out .println(“ Enter a number ”);

num = input.nextInt();

System. out .println(“ Last Digit From Number Is : “ + num % 10);

Output

Enter a number

1432

Last Digit From Number Is : 2

Write a program to take number of balls from user and convert it into the overs and

balls (1 over = 6 balls)

import java.util.Scanner;

public class BallsIntoOver{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double numOfBalls ;

// Take data from user

System. out .println(“ Enter number of balls ”);

numOfBalls = input.nextInt();

int totalOver = numOfBalls / 6;

int remainingBall = numOfBalls % 6;

System. out .println(“ Total it is “ + totalOver + “ over and “ + remainingBall + “ balls ”);

18

Knock the door on [email protected]


JAVA OPERATORS

Output

Enter number of balls

17

Total it is 2 over and 5 balls

Write a program to calculate salary of the employee based on number of hours they

worked & over time hours they did

Rate as follow

___________________________________________

Normal Hour Rate 20 per hour


Data

Overtime Hour Rate 25 per hour

import java.util.Scanner;

public class SalaryOfEmployees{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int numOfHours;

int overTimeHours;

// Take data from user

System. out .println(“ Enter total num of normal hours ”);

numOfHours = input.nextInt();

System. out .println(“ Enter total num of overtime hours ”);

overTimeHours= input.nextInt();

int totalSalary = numOfHours * 20 + overTimeHours * 25;

System. out .println(“ Your total salary is “ + totalSalary);

Output

Enter total num of normal hours

Enter total num of overtime hours

Your total salary is 45

Write a program to print the discount obtain by the customer based on the total bill

and discount percentage entered by user

19

Knock the door on [email protected]


JAVA OPERATORS

import java.util.Scanner;

public class BillAfterDiscount{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double originalAmount;

double discountPercentage;

// Take data from user

System. out .println(“ Enter the amount in the bill ”);

originalAmount = input.nextInt();

System. out .println(“ Enter the discount percentage ”);

discountPercentage = input.nextInt();

double discountAmount = originalAmount * discountPercentage / 100;

System. out .println(“ Your discount amount is “ + discountAmount );

Output

Enter the amount in the bill 200

Enter the discount percentage 15

Your discount amount is 30.0

Write a program to print total shipping cost to the customer including tax based on

cost entered by user

Fix tax rate - 12% of amount

import java.util.Scanner;

public class ShippingCost{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double shippingCost;

double finalShippingCost;

// Take data from user

System. out .println(“ Enter the amount in the bill ”);

shippingCost = input.nextInt();

20

Knock the door on [email protected]


JAVA OPERATORS

finalShippingCost = shippingCost + (shippingCost * 12 / 100);

System. out .println(“ Your final amount is “ + finalShippingCost );

Output

Enter the shipping cost before tax

200

Your final amount is 224.0

Write a program to get weight and height from user and calculate BMI units

BMI Formula = weight(kg) / height(m)^2

import java.util.Scanner;

public class BMIUnits{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double weight ;

double height;

double bmiUnit;

// Take data from user

System. out .println(“ Enter your weight in Kilogram ”);

weight = input.nextInt();

System. out .println(“ Enter your height in centimeterl ”);

height = input.nextInt();

height = height / 100; // Convert height from centimeter to meter

bmiUnit = weight / (height * height);

System. out .println(“ Your BMI units are “ + bmiUnit );

Output

Enter your weight in Kilogram

72

Enter your height in centimeter

172

Your BMI units are 24.337479718766904

21

Knock the door on [email protected]


JAVA OPERATORS

Write a program to find volume of the Cuboid based on length, width and height

Volume of Cuboid = length * width * height

import java.util.Scanner;

public class VolumeOfCuboid{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double length, width, height, volume;

// Take data from user

System. out .println(“ Enter the length of the cube ”);

length = input.nextInt();

System. out .println(“ Enter the width of the cube ”);

width = input.nextInt();

System. out .println(“ Enter the height of the cube ”);

height = input.nextInt();

volume = length * width * height;

System. out .println(“ Volume of the cube “ + volume );

Output

Enter the length of the cube

12

Enter the width of the cube

12

Enter the height of the cube

12

Volume of the cube 1728.0

Write a program to find gross salary of the employee from the basic salary

HRA 50% of Basic Salary

LEAVE TRAVEL ALLOWANCE FIXED AMOUNT 3000

SPECIAL ALLOWANCE 10% Of Basic Salary

PF EMPLOYER CONTRIBUTION 12 % Of Basic Salary


Data

GROSS SALARY Basic + allowances

22

Knock the door on [email protected]


JAVA OPERATORS

import java.util.Scanner;

public class VolumeOfCuboid{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double salary, hra, lta, sa, pf, grossSalary;

// Take data from user

System. out .println(“ Enter your basic salary ”);

salary = input.nextInt();

hra = salary * 50 / 100;

lta = 3000;

sa = salary * 10 / 100;

pf = salary * 12 / 100;

grossSalary = salary + hra + lta + sa + pf;

System. out .println(“ Total Salary = “ + grossSalary );

Output

Enter your basic salary

3500

Total Salary = 9020.0

23

Knock the door on [email protected]


3

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;

public class CheckNumberDivisibleBy5 {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int num;

// Take number from user

System. out .println(“ Enter any number ”);

num = input.nextInt();

if (num % 5 == 0) {

System. out .println(num +” is divisible by 5 ”);

} else {

System. out .println(num +” is not divisible by 5 ”);

Output

Enter any number

10

10 is divisible by 5

Write a program to check given number is odd or even

import java.util.Scanner;

public class OddEven {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Take number from user

System. out .println(“ Enter any number ”);

int num = input.nextInt();

// If we divide number with 2 and if remainder is zero then it is even number

if (num % 2 == 0) {

System. out .println(“ Even ”);

25

Knock the door on [email protected]


CONDITIONAL STATEMENTS

} else {

System. out .println(“ Odd ”);

Output

Enter any number

55

Odd

Write a program to print greatest number out of two numbers (Assume, numbers are

not equal)

import java.util.Scanner;

public class MaxNumber{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Take numbers from user

System. out .println(“ Enter first number ”);

int num1 = input.nextInt();

System. out .println(“ Enter second number ”);

int num2 = input.nextInt();

if (num1 > num2) {

System. out .println(num1+” is greatest ”);

} else {

System. out .println(num2+” is greatest ”);

Output

Enter first number

34

Enter second number

12

34 is greatest

26

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Write a program to check given number is positive, negative or zero

import java.util.Scanner;

public class PositiveNegative{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Take numbers from user

System. out .println(“ Enter any number ”);

int num = input.nextInt();

if (num > 0) {

System. out .println(“ Number is positive ”);

} else if (num < 0) {

System. out .println(“ Number is negative ”);

} else {

System. out .println(“ Number is zero ”);

Output

Enter any number

10

Number is positive

Write a program to print number of days in a given month using If-Else

Input Output

____________________________

1 31 day

2 28/29 days

3 31 days
Example

4 30 days

12 31 days

import java.util.Scanner;

public class NumberOfDaysInMonth{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Take numbers from user

System. out .println(“ Enter a month number ”);

27

Knock the door on [email protected]


CONDITIONAL STATEMENTS

int month = input.nextInt();

if (month == 1) {

System. out .println(“ 31 days ”);

} else if (month == 2) {

System. out .println(“ 28/29 days ”);

} else if (month == 3) {

System. out .println(“ 31 days ”);

} else if (month == 4) {

System.out.println(“ 30 days ”);

} else if (month == 5) {

System. out .println(“ 31 days ”);

} else if (month == 6) {

System. out .println(“ 30 days ”);

} else if (month == 7) {

System. out .println(“ 31 days ”);

} else if (month == 8) {

System. out .println(“ 31 days ”);

} else if (month == 9) {

System. out .println(“ 30 days ”);

} else if (month == 10) {

System. out .println(“ 31 days ”);

} else if (month == 11) {

System. out .println(“ 30 days ”);

} else if (month == 12) {

System. out .println(“ 31 days ”);

} else {

System. out .println(“ Please enter number from 1 to 12 only ”);

Output

Enter a month number

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

Knock the door on [email protected]


CONDITIONAL STATEMENTS

import java.util.Scanner;

public class SwitchNumberOfDaysInMonth{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Take numbers from user

System. out .println(“ Enter a month number ”);

int month = input.nextInt();

switch (month) {

case 1:

case 3:

case 5:

case 7:

case 10:

case 8:

case 12:

System. out .println(“ 31 days ”);

break ;

case 2:

System. out .print(“ 28/29 days ”);

break ;

case 4:

case 6:

case 9:

case 11:

System. out .print(“ 30 days ”);

break ;

default :

System. out .print(“ Please enter valid input from 1 to 12 only ”);

Output

Enter a month number

31 days

29

Knock the door on [email protected]


CONDITIONAL STATEMENTS

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;

public class NumberOfDaysInMonth{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Take numbers from user

System. out .println(“ Enter a day number ”);

int dayOfWeek = input.nextInt();

if (dayOfWeek == 0) {

System. out .println(“ Sunday ”);

} else if (dayOfWeek == 1) {

System. out .println(“ Monday ”);

} else if (dayOfWeek == 2) {

System. out .println(“ Tuesday ”);

} else if (dayOfWeek == 3) {

System. out .println(“ Wed ”);

} else if (dayOfWeek == 4) {

System. out .println(“ Thursday ”);

} else if (dayOfWeek == 5) {

System. out .println(“ Fri ”);

} else if (dayOfWeek == 6) {

System. out .println(“ Sat ”);

} else {

System. out .println(“ Please enter number from 0 to 6 onyl. ”);

Output

Enter a day number

12

Please enter number from 0 to 6 only...

Please write above program using switch statement by yourself

30

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Write a program to print grade of the student based on the marks

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;

public class GradeSystem{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Take numbers from user

System. out .println(“ Enter your total marks ”);

int marks = input.nextInt();

if (marks > 100 || marks < 0) {

System. out .println(“ Invalid input ”);

} else if (marks >= 90) {

System. out .println(“ A+ ”);

} else if (marks >= 80) {

System. out .println(“ A ”);

} else if (marks >= 70) {

System. out .println(“ B+ ”);

} else if (marks >= 60) {

System. out .println(“ B ”);

} else if (marks >= 50) {

System. out .println(“ C+ ”);

} else if (marks >= 40) {

System. out .println(“ C ”);

} else {

System. out .print(“ Fail ”);

Output

Enter your total marks

55

C+

31

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Can we write above program using switch statement?

Write a program to calculate final bill of customer after giving appropriate discount

based on the amount

Amount Discount

_______________________________________

More than 10000 15%

More than 8000 10%

More than 8000 10%


Example

More than 5000 5%

import java.util.Scanner;

public class DiscountedBill{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Take numbers from user

System. out .println(“ Enter the bill amount ”);

int billAmount = input.nextInt();

if (billAmount > 10000) {

System. out .println(“ You’ve given 15% Discount. your final bill is “ + billAmount * 0.85);

} else if (billAmount > 8000) {

System. out .println(“ You’ve given 10% Discount. your final bill is “ + billAmount * 0.90);

} else if (billAmount > 5000) {

System. out .println(“ You’ve given 5% Discount. your final bill is “ + billAmount * 0.95);

} else if (billAmount > 0) {

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

Enter the bill amount

9500

You’ve givne 10% Discount. your final bill is 8550.0

32

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Write a program to find greatest number out of three numbers

Input Output

__________________________________________

43, 54, 24 54 is greatest


Example

import java.util.Scanner;

public class Max_Number_From_Three_Numbers{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Take numbers from user

System. out .println(“ Enter first number ”);

int num1 = input.nextInt();

System. out .println(“ Enter second number ”);

int num2 = input.nextInt();

System. out .println(“ Enter third number ”);

int num3 = input.nextInt();

if (num1 > num2 && num1 > num3) {

System. out .println(num1 + “ is greatest ”);

} else if (num2 > num3) {

System. out .println(num2 + “ is greatest ”);

} else {

System. out .println(num3 + “ is greatest ”);

Output

Enter first number

33

Enter second number

53

Enter third number

12

53 is greatest

Write a Program to check given character is vowel or not

Vowel characters - a, e, i, o, u

Input Output

__________________________________________

a a is vowel

b b is not vowel
Example

33

Knock the door on [email protected]


CONDITIONAL STATEMENTS

import java.util.Scanner;

public class CheckVowel{

public static void main(String[] args ) {

char c = ‘ r ’;

if (c == ‘ a ’ || c == ‘ e ’ || c == ‘ i ’ || c == ‘ o ’ || c == ‘ u ’) {

System. out .println(“ Vowel ”);

} else {

System. out .println(“ Not Vowel ”);

Output

Not Vowel

Please brainstorm and write above program to include capital letters as well

Write a Program to make a calculator that should perform addition, subtraction

multiplication and division

Input Output

__________________________________________

10,20, Add 30

10,20, Mul 200


Example

import java.util.Scanner;

public class CalculatorUsingSwitch{

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Take numbers from user

System. out .println(“ Enter first number ”);

int num1 = input.nextInt();

System. out .println(“ Enter second number ”);

int num2 = input.nextInt();

// Take operation from the user

System. out .println(“ Enter operation you want to perform ”);

String choice = input.next();

34

Knock the door on [email protected]


CONDITIONAL STATEMENTS

switch ( choice ) {

case “Add”:

System. out .println(num1 + num2);

break ;

case “Sub”:

System. out .println(num1 + num2);

break ;

case “Mul”:

System. out .println(num1 + num2);

break ;

case “Div”:

System. out .println(num1 + num2);

break ;

default :

System. out .print(“ This calculator only supports Add, Div, Mul & Sub ”);

Output

Enter first number

13

Enter second number

15

Enter operation you want to perform

Add

28

Write a program to take username and password from user and print appropriate

message based on entered username and password

dbUsername dbPassword

________________________________________________________

3312 1234
Data

Input Output

_________________________________________________________________________________________

username, password is correct Login Successful

username - incorrect, password - correct Incorrect username

I username - correct, password - incorrect Incorrect password


Example

username - incorrect, password - incorrect Username and password are incorrect

35

Knock the door on [email protected]


CONDITIONAL STATEMENTS

public class LoginValidation {

public static void main(String args []) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Credentials stored in the database

int dbUsername = 1234, dbPassword = 2222;

// Take username and password from user

System. out .println(“ Enter the username ”);

int username = input.nextInt();

System. out .println(“ Enter the password ”);

int password = input.nextInt();

// Compare username and password with database username and password

if (username == dbUsername) {

if (password == dbPassword) {

System. out .println(“ Login successful ”);

} else {

System. out .println(“ Incorrect password ”);

} else {

if (password == dbPassword) {

System. out .println(“ Incorrect username ”);

} else {

System. out .println(“ Username and password are incorrect ”);

Output

Enter the username

1234

Enter the password

3333

Incorrect password

Write a program to print message based on rating of the company

Rating Message

__________________________________________

5 Very Good

4 Good

3 Average
Example

2 Poor

1 Very Poor

36

Knock the door on [email protected]


CONDITIONAL STATEMENTS

import java.util.Scanner;

public class Rating {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Take rating from the user

System. out .println(“ Enter the rating ”);

int rating = input.nextInt();

switch (rating) {

case 5:

System. out .println(“ Very Good ”);

break ;

case 4:

System. out .println(“ Good ”);

break ;

case 3:

System. out .println(“ Average ”);

break ;

case 2:

System. out .println(“ Poor ”);

break ;

case 1:

System. out .println(“ Very Poor ”);

break ;

default :

System. out .println(“ Invalid rating ”);

Output

Enter the rating

Average

Write a Program To Count Total Number Of Minimum Notes In Given Amount

(Notes are of 1, 2, 5, 10, 20, 100 & 500)

Input Output

__________________________________________

Amount = 255 2 Notes of 100

2 Notes of 20
Example

3 Notes of 5

37

Knock the door on [email protected]


CONDITIONAL STATEMENTS

import java.util.Scanner;

public class CountNotes {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter the amount ”);

int amount = input.nextInt();

// Divide amount with 500 so we will get number of notes of 500

int result = amount / 500;

if (result > 0) {

System. out .println(“ you need “ + result + “ notes of 500 ”);

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

result = amount / 100;

if (result > 0) {

System. out .println(“ you need “ + result + “ notes of 100 ”);

amount = amount % 100; // We will remove the amount that is multiple of 100

result = amount / 20;

if (result > 0) {

System. out .println(“ you need “ + result + “ notes of 20 ”);

amount = amount % 20;

result = amount / 10;

if (result > 0) {

System. out .println(“ you need “ + result + “ notes of 10 ”);

amount = amount % 10;

result = amount / 5;

if (result > 0) {

System. out .println(“ you need “ + result + “ notes of 5 ”);

amount = amount % 5;

result = amount / 2;

if (result > 0) {

System. out .println(“ you need “ + result + “ notes of 2 ”);

amount = amount % 2;

if (amount > 0) {

System. out .println(“ you need “ + amount + “ notes of 1 ”);

38

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Output

Please enter the amount

365

you need 3 notes of 100

you need 3 notes of 20

you need 1 notes of 5

Write a program to reads power consumed in units and print amount to be paid by

customer

Consumption Rate of Units Charges

________________________________________________________________________________

If unit is 0-200 USD 0.50 per unit

If unit is 201-400 Fixed Fee of USD 50 + USD 0.65 per unit


Data

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;

public class ElectricityBill {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Take units from the user

System. out .println(“ Enter number of units ”);

int unit = input.nextInt();

double totalPrice = 0;

if (unit <= 200){

totalPrice = totalPrice + unit * 0.5;

} else if (unit <= 400){

totalPrice = totalPrice + unit * 0.65 + 50;

} else {

totalPrice = totalPrice + unit * 0.85 + 220;

System. out .println(“ Total Bill Amount= ”+totalPrice);

Output

Enter number of units

672

Total Bill Amount=791.2

39

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Write a program to print FIFA world cup team captain based on team name entered by

user

Team Captain

______________________________________________

Qatar Hassan Al-Haydos

Netherlands Virgil van Dijk

Argentina Lionel Messi

Portugal Cristiano Ronaldo


Data

Brazil Thiago Silva

Serbia Dusan Tadic

Switzerland Granit Xhaka

Cameroon Vincent Aboubakar

Input Output

__________________________________________

Brazil Thiago Silva


Example

public class FifaCaptain {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a team name ”);

String teamName = input.next();

switch (teamName) {

case “Qatar”:

System. out .println(“ Hassan Al-Haydos ”);

break ;

case “Netherlands”:

System. out .println(“ Virgil van Dijk ”);

break ;

case “Argentina”:

System. out .println(“ Lionel Messi ”);

break ;

case “Portugal”:

System. out .println(“ Cristiano Ronaldo ”);

break ;

case “Brazil”:

System. out .println(“ Thiago Silva ”);

break ;

case “Serbia”:

System. out .println(“ Dusan Tadic ”);

break ;

case “Switzerland”:

System. out .println(“ Granit Xhaka ”);

break ;

40

Knock the door on [email protected]


CONDITIONAL STATEMENTS

case “Cameroon”:

System. out .println(“ Vincent Aboubakar ”);

break ;

default :

System. out .println(“ Invalid team name ”);

Output

Please enter a team name

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

__________________________________________________________________________________

Welcome to Security Check in

Are you coming from connecting flight(Yes / No)? No

Please proceed to security checks

Enjoy your flight


Example

Welcome to Security Check in

Are you coming from connecting flight(Yes / No)? Yes

Enjoy your flight

public class FlightCheckin {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

System. out .println(“ Welcome to Security Check in ”);

System. out .println(“ Are you coming from connecting flight(Yes / No)? ”);

String userInput = input.next();

if (!userInput.equalsIgnoreCase(“Yes”)) {

System. out .println(“ Please proceed to security checks ”);

System. out .println(“ Enjoy your flight “);

41

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Output

Welcome to Security Check in

Are you coming from connecting flight(Yes / No)?

no

Please proceed to security checks

Enjoy your flight

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

_________________________________________________________________________________________

Welcome to ABC Hotel

Are you returning customer(Yes / No)? Yes

Congratulation!! You have got 10% discount on your stay

Enjoy your stay here


Example

Welcome to ABC Hotel

Are you returning customer(Yes / No)? No

Enjoy your stay here

public class HotelCheckin {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

System. out .println(“ Welcome to ABC Hotel ”);

System. out .println(“ Are you returning customer(Yes / No)? ”);

String userInput = input.next();

if (userInput.equalsIgnoreCase(“Yes”)) {

System. out .println(“ Congratulation!! You have got 10% discount on your stay ”);

System. out .println(“ Enjoy your stay here “);

Output

Welcome to ABC Hotel

Are you returning customer(Yes / No)?

Yes

Congratulation!! You have got 10% discount on your stay

Enjoy your stay here

42

Knock the door on [email protected]


CONDITIONAL STATEMENTS

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

“Congratulation! You have got a distinction”

public class ExamResult {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

System. out .println(“ Enter marks of subject 1 ”);

int mark1 = input.nextInt();

System. out .println(“ Enter marks of subject 2 ”);

int mark2 = input.nextInt();

System. out .println(“ Enter marks of subject 3 ”);

int mark3 = input.nextInt();

double percentage = (mark1 + mark2 + mark3) / 300.0 * 100;

System. out .println(“ You have got “ + percentage + “ percentage ”);

if (percentage >= 70) {

System. out .println(“ Congratulation! You have got a distinction ”);

Output

Enter marks of subject 1

80

Enter marks of subject 2

75

Enter marks of subject 3

65

You have got 73.33333333333333 percentage

Congratulation! You have got a distinction

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

Shipping Cost Tax

_________________________________

0 - 999 5%

1000 - 1999 10%


Data

2000 - 4999 15%

greater than 4999 20%

43

Knock the door on [email protected]


CONDITIONAL STATEMENTS

public class ShippingCost {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

System. out .println(“ Enter your shipping cost amount ”);

double shippingCost = input.nextDouble();

if (shippingCost < 1000) {

shippingCost = shippingCost + shippingCost * 0.05;

} else if (shippingCost < 2000) {

shippingCost = shippingCost + shippingCost * 0.1;

} else if (shippingCost < 5000) {

shippingCost = shippingCost + shippingCost * 0.15;

} else {

shippingCost = shippingCost + shippingCost * 0.2;

System. out .println(“ Your total shipping cost including tax is “ + shippingCost);

Output

Enter your shipping cost amount

4300

Your total shipping cost including tax is 4945.0

Write a program to print obesity level of the user based on bmi value calculated from

weight and height entered by user as below

Formula to calculate BMI : weight(kg) / height(m)^2

BMI Value Obesity Level

____________________________________________________

less than 18.5 underweight

18.5 - 24.9 normal

25 - 29.9 overweight
Data

30 - 34.9 obese

greater than 35 extremly obese

public class ObesityLevel {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

double weight, height, bmiUnit;

44

Knock the door on [email protected]


CONDITIONAL STATEMENTS

// Take data from user

System. out .println(“ Enter your weight in Kilogram ”);

weight = input.nextDouble();

System.out.println(“ Enter your height in centimeter ”);

height = input.nextDouble();

height = height / 100; // Convert height from centimeter to meter

bmiUnit = weight / (height * height);

System.out.println(“ Your BMI units are “ + bmiUnit);

if (bmiUnit < 18.5) {

System. out .println(“ Underweight ”);

} else if (bmiUnit >= 18.5 && bmiUnit <= 24.9) {

System. out .println(“ Normal ”);

} else if (bmiUnit >= 25 && bmiUnit <= 29.9) {

System. out .println(“ Overweight ”);

} else if (bmiUnit >= 30 && bmiUnit <= 34.9) {

System. out .println(“ Obese ”);

} else {

System. out .println(“ Extremely Obese ”);

Output

Enter your weight in Kilogram

72

Enter your height in centimeter

170

Your BMI units are 24.913494809688583

Normal

Write a program to find smallest number out of two numbers (Assume both numbers

are not equal)

public class SmallestNumber {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int num1, num2;

// Take data from user

System. out .println(“ Enter the first number ”);

num1 = input.nextInt();

45

Knock the door on [email protected]


CONDITIONAL STATEMENTS

System.out.println(“ Enter your second number ”);

num2 = input.nextInt();

if (num1 < num2) {

System. out .println(num1 + “ is smallest ”);

} else {

System. out .println(num2 + “ is smallest ”);

Output

Enter the first number

45

Enter the second number

56

45 is smallest

Write a program to get age from user and check if user is Teenager or not

import java.util.Scanner;

public class TeenagersProgram {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

System.out.println(“ Enter your age ”);

// Take input from user

System. out .println(“ Enter the first number ”);

int age = input.nextInt();

if (age >= 13 && age <= 19) {

System. out .println(“ You are a teenager ”);

} else {

System. out .println(“ You are not a teenager ”);

Output

Enter your age

17

You are a teenager

46

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Write a program to find smallest number out of three numbers (Assume numbers are

not equal)

import java.util.Scanner;

public class TeenagersProgram {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int num1, num2, num3;

// Take data from user

System. out .println(“ Enter the first number ”);

num1 = input.nextInt();

System. out .println(“ Enter the first number ”);

num2 = input.nextInt();

System. out .println(“ Enter the first number ”);

num3 = input.nextInt();

if (num1 < num2 && num1 < num3) {

System. out .println( numq + “ is smallest ” );

} else if (num2 < num3) {

System. out .println(num2 + “ is smallest ”);

} else {

System. out .println( num3 + “ is smallest ” );

Output

Enter the first number

32

Enter the second number

54

Enter the third number

13

13 is smallest

47

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Write a program to take age and amount from user and print rate of interest of fixed

deposit based on following criteria

Age Amount Rate of interest

_______________________________________________________

>= 60 >= 20000 8.0%

>= 60 < 20000 7.5%


Data

< 60 >= 20000 7.0%

< 60 < 20000 6.0%

import java.util.Scanner;

public class RateOfInterestOnFD {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int age, amount;

// Take data from user

System. out .println(“ Enter your age ”);

age = input.nextInt();

System. out .println(“ Enter the amount ”);

amount = input.nextInt();

if (age >= 60) {

if (amount >= 20000) {

System. out .println(“ 8.0% ”);

} else {

System. out .println(“ 7.5% ”);

} else {

if (amount >= 20000) {

System. out .println(“ 7.0% ”);

} else {

System. out .println(“ 6.0% ”);

Output

Enter your age

54

Enter the amount

35000

7.0%

48

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Write a program to take age and weight from the user and check if they are eligible for

blood donation based on following criteria

Age Weight Message

___________________________________________________________________________________

< 18 >= 50 You are too young to donate blood

< 18 < 50 You are not eligible


Data

>= 18 >= 50 You are eligible

>= 18 < 50 You are underweight to donate blood

import java.util.Scanner;

public class BloodDonation {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int age, weight;

// Take data from user

System. out .println(“ Enter your age ”);

age = input.nextInt();

System. out .println(“ Enter weight ”);

weight = input.nextInt();

if (age < 18) {

if (weight >= 50) {

System. out .println(“ You are too young to donate blood ”);

} else {

System. out .println(“ You are not eligible ”);

} else {

if (weight >= 50) {

System. out .println(“ You are eligible ”);

} else {

System. out .println(“ You are underweight to donate blood ”);

Output

Enter your age

43

Enter your weight

65

You are eligible

49

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Write a program to take salary and existing loan amount from user and decide their

credit card limit based on following criteria

Salary Existing Loan Amount Credit Limit

_______________________________________________________________________________

>= 20000 < 5000 50000

>= 20000 5000 to 15000 25000

>= 20000 >15000 You are not eligible


Data

< 20000 < 5000 25000

< 20000 >= 5000 You are not eligible

import java.util.Scanner;

public class CreditLimit {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int salary, existingLoan;

// Take data from user

System. out .println(“ Enter your salary ”);

salary = input.nextInt();

System. out .println(“ Enter existing loan amount ”);

existingLoan = input.nextInt();

if (salary >= 20000) {

if (existingLoan > 15000) {

System. out .println(“ You are not eligible ”);

} else if (existingLoan > 5000) {

System. out .println(“ 25000 ”);

else {

System. out .println(“ 50000 ”);

} else {

if (existingLoan < 5000) {

System. out .println(“ 25000 ”);

} else {

System. out .println(“ You are not eligible ”);

50

Knock the door on [email protected]


CONDITIONAL STATEMENTS

Output

Enter your salary

35000

Enter your existing loan amount

15000

25000

Write a program to calculate income tax of the employee from the total salary

Salary Incometax Percentage

_________________________________________________________________________________

Up to 3000 0%

3001 to 6000 5% on income which exceeds 3000

6001 to 9000 10% on income which exceeds Rs 6000


Data

9001 to 12000 15% on income which exceeds Rs 9000

12001 to 15000 20% on income which exceeds Rs 12000

greater than 15000 30% on income which exceeds Rs 15000

import java.util.Scanner;

public class IncomeTax {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

int salary;

double incomeTax;

// Take data from user

System. out .println(“ Enter your salary ”);

salary = input.nextInt();

if (salary <= 3000) {

incomeTax = 0;

} else if (salary <= 6000) {

incomeTax = (salary - 3000) * 0.05;

} else if (salary <= 9000) {

incomeTax = (salary - 6000) * 0.1 + 3000 * 0.05;

} else if (salary <= 12000) {

incomeTax = (salary - 9000) * 0.15 + 3000 * 0.1 + 3000 * 0.05;

} else if (salary <= 15000) {

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

Knock the door on [email protected]


CONDITIONAL STATEMENTS

System. out .println(“ Your total income tax is “ + incomeTax);

Output

Enter your salary

18000

Your total income tax is 2400.0

52

Knock the door on [email protected]


4

FOR LOOP
FOR LOOP

Write a program to print 1 to 10 numbers using for loop

public class Print1to10 {

public static void main(String[] args ) {

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

System. out .println(i);

O u tp u t

10

Write a program to print even numbers from 1 to 10 using for loop

public class PrintEvenFrom1to10 {

public static void main(String[] args ) {

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

if (i % 2 == 0) {
1

System. out .println(i);

}
APPROACH

public class PrintEvenFrom1to10 {


2

public static void main(String[] args ) {

for ( int i = 2; i <= 10; i = i + 2) {

System. out .println(i);


APPROACH

54

Knock the door on [email protected]


FOR LOOP

public class PrintEvenFrom1to10 {

public static void main(String[] args ) {

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


3

System. out .println(i * 2);

}
APPROACH

O u tp u t

10

Write a program to print 10 to 1 numbers

public class Print10to1 {

public static void main(String[] args ) {

for ( int i = 10; i >= 1; i--) {

System. out .println(i);

O u tp u t

10

55

Knock the door on [email protected]


FOR LOOP

Write a program to print table of 5

public class TableOf5 {

public static void main(String[] args ) {

int num = 5;

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

System. out .println(num + “ * ” + i + “ = ” + num * i);

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

Write a program to print numbers from 1 to 20 which are divisible by 3

public class PrintNumberFrom1to20DivisbleBy3 {

public static void main(String[] args ) {

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


1

if (i % 3 == 0) {

System. out .println(i);

}
APPROACH

public class PrintNumberFrom1to20DivisbleBy3 {

public static void main(String[] args ) {

for ( int i = 1; i <= 20; i=i+3) {


2

System. out .println(i);

}
APPROACH

56

Knock the door on [email protected]


FOR LOOP

O u tp u t

12

15

18

Java program to Print Pattern 1 10 2 9 3 8 4 7 5 6

public class PrintZigZag {

public static void main(String[] args ) {

// Because we are printing two lines in one iteration so we’ll execute loop 5 time only

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

System. out .println(i);

System. out .println(11 - i);

O u tp u t

10

Java program to Print sum of 1 to 10 numbers

public class SumOf1to10 {

public static void main(String[] args ) {

// Initialize sum variable to 0. This variable will hold the sum of the numbers.

int sum = 0;

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

57

Knock the door on [email protected]


FOR LOOP

sum = sum + i;

System. out .println(sum);

O u tp u t

55

Java program to Print sum of even numbers from 1 to 10

public class SumOfEvenNumbersFrom1to10 {

public static void main(String[] args ) {

int sum = 0;

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

if (i % 2 == 0) {

sum = sum + i;

System. out .println(sum);

O u tp u t

30

Java program to Print sum of 1 to 50 numbers which are divisible by 5 or by 3

public class SumOf1To50DivisibleBy5OR3 {

public static void main(String[] args ) {

int sum = 0;

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

if (i % 3 == 0 || i % 5 == 0) {

sum = sum + i;

System. out .println(sum);

O u tp u t

593

58

Knock the door on [email protected]


FOR LOOP

Java program to Print sum of 1 + 2 - 3 + 4 + 5 - 6 + 7 + 8 - 9 + 10

public class SumOfNumberWithDivisibleBy3Minus {

public static void main(String[] args ) {

int sum = 0;

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

if (i % 3 == 0) {

sum = sum - i;

} else {

sum = sum + i;

System. out .println(sum);

O u tp u t

19

Java program to find sum of 1/2 + 2/3 + 3/4 + 4/5 +......10/11

public class SumOfSeries {

public static void main(String[] args ) {

double sum = 0;

for ( double i = 1; i <= 10; i++) {

sum = sum + i / (i + 1);

System. out .println(sum);

O u tp u t

7.980122655122655

Can you guess the answer, why we need to take i double instead of int?

Java program to find sum of 10 + 1 + 9 + 2 + 8 + 3 + 7 + 4 + 6 + 5

public class SumOfSeries {

public static void main(String[] args ) {

int sum = 0;

59

Knock the door on [email protected]


FOR LOOP

// It is just a sum of 1 to 10 so we can just write program to print 1 + 2 + 3 +...+ 10

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

sum = sum + i;

System. out .println(sum);

O u tp u t

55

Java program to find sum of 1^2 + 2^2 + 3^2 + 4^2 + 5^2 +...+ 10^2

public class SumOfSeries {

public static void main(String[] args ) {

int sum = 0;

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

sum = sum + i*i;

System. out .println(sum);

O u tp u t

385

Java program to find factorial of a given number 5! = 5 * 4 * 3 * 2 * 1

import java.util.Scanner;

public class Factorial {

public static void main(String[] args ) {

// We will store multiplication in mul variable, and we will start with initial value 1

int mul = 1;

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a number ”);

int num = input.nextInt();

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

mul = mul * i;

60

Knock the door on [email protected]


FOR LOOP

System. out .println(mul);

O u tp u t

Please enter a number

120

Java program to find factors of a given number

Input Output

____________________________

6 1,2,3,6

14 1,2,7,14
Example

import java.util.Scanner;

public class FindFactorsOfNumber {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a number ”);

int num = input.nextInt();

System. out .println(“ Factors: ”);

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

if (num % i == 0) {

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

O u tp u t

Please enter a number

12

Factors: 1 2 3 4 6 12

Java program to check given number is perfect or not

61

Knock the door on [email protected]


FOR LOOP

Perfect number is a positive integer that is equal to the sum of its positive

divisors, excluding the number itself

Input Output

____________________________

12 Not perfect (becuase 1 + 2 + 3 + 4 + 6 = 16 which is not equal to 12)

6 Perfect (becuase 1 + 2 + 3 which is equal to 6)


Example

28 Perfect (becuase 1 + 2 + 4 + 7 + 14 which is equal to 28)

import java.util.Scanner;

public class PerfectNumber {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a number ”);

int num = input.nextInt();

int sum = 0;

System. out .println(“ Factors: ”);

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

if (num % i == 0) {

sum = sum + i;

if (sum == num) {

System. out .println(“ It’s a perfect number ”);

} else {

System. out .println(“ It’s not a perfect number ”);

O u tp u t

Please enter a number

28

It’s a perfect number

Java program to check given number is prime or not

Prime number is a number that is divisible only by itself and 1

62

Knock the door on [email protected]


FOR LOOP

import java.util.Scanner;

public class PrimeNumber {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a number ”);

int num = input.nextInt();

int count = 0;

// We will count number of divisor of given number

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

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

System. out .println(“ Prime ”);

} else {

System. out .println(“ Not Prime ”);

O u tp u t

Please enter a number

13

Prime

Write a program to print odd numbers from 1 to 10

public class OddNumbers {

public static void main(String[] args ) {

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

if (i % 2 == 1) {

System. out .println(i);

63

Knock the door on [email protected]


FOR LOOP

O u tp u t

Write a program to print 1 11 20 28 35 41 46 50 53 55 56

public class ZigZagPattern {

public static void main(String[] args ) {

int num = 1;

for ( int i = 10; i >= 0; i--) {

System. out .println(num);

System. out .println(i);

O u tp u t

11

20

28

35

41

46

50

53

55

56

Write a program to print 1 2 4 8 16 32 64, under 100

public class PrintNumbers {

public static void main(String[] args ) {

int num = 1;

for ( int i = 1; i <= 100; i = i * 2) {

System. out .println(i);

64

Knock the door on [email protected]


FOR LOOP

O u tp u t

16

32

64

65

Knock the door on [email protected]


5

WHILE LOOP
WHILE LOOP

Write a program to print 1 to 10 numbers using while loop

public class Print1to10 {

public static void main(String[] args ) {

// We want to print numbers from 1 so we are starting variable i with 1

int i = 1;

// We want to print till 10 so condition will be executed till 10

while (i <= 10) {

System. out .println(i);

i++; // Each time we are incrementing value of i variable to 1

Output

10

Write a program to print even numbers from 1 to 10 using while loop

public class PrintEvenFrom1to10 {

public static void main(String[] args ) {

int i = 1;

while (i <= 10) {

// We will only print numbers if it is divisible by 2 so it is even numbers

if (i%2==0){

System. out .println(i);

i++;

67

Knock the door on [email protected]


WHILE LOOP

Output

10

Write a program to print 1 2 4 8 16 32 64, under 100

public class PrintNumbers {

public static void main(String[] args ) {

int i = 1;

while (i <= 100) {

System. out .println(i);

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

Knock the door on [email protected]


WHILE LOOP

import java.util.Scanner;

public class DisplayDigit {

public static void main(String[] args ) {

// Take a number from user

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter any number ”);

int num = input.nextInt();

int lastDigit;

// execute code till the time number is not becoming zero

while (num != 0) {

// Retrieve last digit from the number

lastDigit = num % 10;

// Print last digit

System. out .println(lastDigit);

// remove last digit from the number

num = num / 10;

Output

Please enter any number

35434

Write a program to count number of digits in given number

Input Output

____________________________

5232 4

34343 5
Example

import java.util.Scanner;

public class CountDigit {

public static void main(String[] args ) {

// Take a number from user

69

Knock the door on [email protected]


WHILE LOOP

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter any number ”);

int num = input.nextInt();

int count =0;

// execute code till the time number is not becoming zero

while (num != 0) {

// Increment the count and each time remove the last digit from the number

count++;

// remove last digit from the number

num = num / 10;

System. out .println(count);

Output

Please enter any number

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;

public class SumOfDigit {

public static void main(String[] args ) {

// Take a number from user

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter any number ”);

int num = input.nextInt();

int lastDigit, sum = 0;

while (num != 0) {

lastDigit = num % 10;

sum = sum + lastDigit;

70

Knock the door on [email protected]


WHILE LOOP

num = num / 10;

System. out .println(sum);

Output

Please enter any number

6456789

45

Write a program to print greatest digit from the given number

Input Output

____________________________

73453 7

843179 9
Example

import java.util.Scanner;

public class FindMaxDigitFromNumber {

public static void main(String[] args ) {

// Take a number from user

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter any number ”);

int num = input.nextInt();

// Assume last digit is a greatest digit

int lastDigit, max = num % 10;

while (num != 0) {

lastDigit = num % 10;

// Compare each digit with our assumed digit, if any digit is greater than our assumed

//digit then assign new value to the max

if (lastDigit > max) {

max = lastDigit;

num = num / 10;

System. out .println(max);

71

Knock the door on [email protected]


WHILE LOOP

Output

Please enter any number

346454

Write a program to print reverse of the given number

Input Output

____________________________

73453 35337

843179 971348
Example

import java.util.Scanner;

public class ReverseGivenNumber {

public static void main(String[] args ) {

// Take a number from user

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter any number ”);

int num = input.nextInt();

int rev = 0;

while (num != 0) {

int lastDigit = num % 10;

// We will multiply current result with 10 and add next number

rev = rev * 10 + lastDigit;

num = num / 10;

System. out .println(rev);

Output

Please enter any number

12345

54321

Write a program to check given number is palindrome or not

A palindromic number is a number (such as 16461) that remains the same

when its digits are reversed

72

Knock the door on [email protected]


WHILE LOOP

Input Output

____________________________

12321 Palindrome

843179 Not Palindrome


Example

import java.util.Scanner;

public class PalindromeNumber {

public static void main(String[] args ) {

// Take a number from user

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter any number ”);

int num = input.nextInt();

int rev = 0;

int originalNum = num;

while (num != 0) {

int lastDigit = num % 10;

rev = rev * 10 + lastDigit;

num = num / 10;

if (rev == originalNum) {

System. out .println(“ Palindrom ”);

} else {

System. out .println(“ Not Palindrom ”);

Output

Please enter any number

643534

Not Palindrom

Write a program to print fibonacii series till given limit

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;

public class FibonaciiSeries {

73

Knock the door on [email protected]


WHILE LOOP

public static void main(String[] args ) {

// Take a number from user

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a limit ”);

int limit = input.nextInt();

int num1 = 0;

int num2 = 1;

int sum = num1 + num2;

System. out .println(num1+” “);

System. out .println(num2+” “);

while (sum <= limit) {

System. out .print(sum+” “);

num1 = num2;

num2 = sum;

sum = num1 + num2;

Output

Please enter a limit

12

0 1 1 2 3 5 8

Write a program to check given number is armstrong or not

Armstrong number is a number that is equal to the sum of cubes of its digits

Input Output

_________________________________________

153 1^3 + 5^3 + 3^3

1 + 125 + 27
Example

=153

import java.util.Scanner;

public class ArmstrongNumber {

public static void main(String[] args ) {

// Take a number from user

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a number ”);

int num = input.nextInt();

int originalNum = num, sum = 0, lastDigit;

74

Knock the door on [email protected]


WHILE LOOP

while (num > 0) {

lastDigit = num % 10;

sum = sum + lastDigit * lastDigit * lastDigit;

num = num / 10;

if (originalNum == sum) {

System. out .println(“ Armstrong ”);

} else {

System. out .println(“ Not Armstrong ”);

Output

Please enter a number

153

Armstrong

Java Program to Convert Binary to Decimal Number

import java.util.Scanner;

public class BinaryToDecimal {

public static void main(String[] args ) {

// Take a number from user

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a number ”);

int num = input.nextInt();

int decimal = 0, i = 0;

while (num > 0) {

int lastDigit = num % 10;

decimal = decimal + lastDigit * (int) Math.pow(2, i);

num = num / 10;

i++;

System. out .println(decimal);

75

Knock the door on [email protected]


WHILE LOOP

Output

Please enter a number

1101

13

Java Program to Convert Binary to Decimal Number

import java.util.Scanner;

public class DecimalToBinary {

public static void main(String[] args ) {

// Take a number from user

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a number ”);

int num = input.nextInt();

String binary = “”;

while (num > 0) {

binary = binary + num % 2;

num = num / 2;

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

System. out .print(binary.charAt(i));

Output

Please enter a number

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;

public class SumOfDigitTillSingleDigit {

76

Knock the door on [email protected]


WHILE LOOP

public static void main(String[] args ) {

// Take a number from user

Scanner sc = new Scanner(System.in);

System. out .println(“ Please enter a number ”);

int num = sc.nextInt();

int sum = 0;

while (num > 0) {

while (num > 0) {

sum = sum + num % 10;

num = num / 10;

num = sum;

sum = 0;

System. out .println(num);

Output

Please enter a number

34567

Java program to check given number is magic number or not

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;

public class MagicNumber {

public static void main(String[] args ) {

// Take a number from user

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a number ”);

int num = input.nextInt();

77

Knock the door on [email protected]


WHILE LOOP

int sum = 0;

while (num > 0) {

while (num > 0) {

sum = sum + num % 10;

num = num / 10;

num = sum;

sum = 0;

if (num == 1) {

System. out .println(“ It is Magic Number ”);

} else {

System. out .println(“ It is not Magic Number ”);

Output

Please enter a number

325

It is Magic Number

Java program to check given number is spy number or not

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;

public class SpyNumbert {

public static void main(String[] args ) {

// Take a number from user

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter a number ”);

int num = input.nextInt();

int sum = 0, product = 1;

while (num > 0) {

78

Knock the door on [email protected]


WHILE LOOP

int lastDigit = num % 10;

sum = sum + lastDigit;

product = product * lastDigit;

num = num / 10;

if (product == sum) {

System. out .println(“ It is Spy Number ”);

} else {

System. out .println(“ It is not Spy Number ”);

Output

Please enter a number

217

It is not Spy Number

79

Knock the door on [email protected]


6

DO WHILE LOOP
DO WHILE LOOP

Write a program to print addition of two numbers until user enters ‘No’

Input Output

_______________________________________________________________

10 20 30

Do you want to perform more operation?

Press 1 for Yes

Press 2 for No

Yes
Example

20 40 60

Do you want to perform more operation?

Press 1 for Yes

Press 2 for No

No

import java.util.Scanner;

public class AdditionUsingDoWhile {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

int userChoice;

do {

System. out .println(“ Please enter two values ”);

int a = input.nextInt(), b = input.nextInt();

System. out .println(a + b);

System. out .println(“ Do you want to perform more operation? ”);

System. out .println(“ Press 1 for yes ”);

System. out .println(“ Press 2 for No ”);

userChoice = input.nextInt();

} while (userChoice == 1);

Output

Please enter two values

10 20

30

81

Knock the door on [email protected]


DO WHILE LOOP

Do you want to perform more operation?

Press 1 for yes

Press 2 for No

Please enter two values

50 100

150

Do you want to perform more operation?

Press 1 for yes

Press 2 for No

Write a program to check given number is prime or not until user enters ‘No’

Input Output

_______________________________________________________________

20 Not prime

Do you want to perform more operation?

Press 1 for Yes

Press 2 for No

Yes
Example

13 prime

Do you want to perform more operation?

Press 1 for Yes

Press 2 for No

No

import java.util.Scanner;

public class CheckPrimenUsingDoWhile {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

int userChoice;

do {

System. out .println(“ Please enter any number ”);

int num = input.nextInt(), count = 0;

// We will count number of divisor of given number

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

if (num % i == 0) {

82

Knock the door on [email protected]


DO WHILE LOOP

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

System. out .println(“ Prime ”);

} else {

System. out .println(“ Not Prime ”);

System. out .println(“ Do you want to perform more operation? ”);

System. out .println(“ Press 1 for yes ”);

System. out .println(“ Press 2 for No ”);

userChoice = input.nextInt();

} while (userChoice == 1);

Output

Please enter any number

20

Not Prime

Do you want to perform more operation?

Press 1 for yes

Press 2 for No

Please enter any number

11

Prime

Do you want to perform more operation?

Press 1 for yes

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

Knock the door on [email protected]


DO WHILE LOOP

import java.util.Scanner;

public class ATMMachine {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter initial balance ”);

int balance = input.nextInt(), repeatOperation;

do {

System. out .println(“ Select an operation to perform ”);

System. out .println(“ 1. Withdraw ”);

System. out .println(“ 2. Deposit ”);

System. out .println(“ 3. Check Balance ”);

int choice = input.nextInt(), amount;

switch (choice) {

case 1:

System. out .println(“ Enter amount to withdraw ”);

amount = input.nextInt();

balance = balance - amount;

System. out .println(“ Updated balance is “ + balance);

break ;

case 2:

System. out .println(“ Enter amount to deposit ”);

amount = input.nextInt();

balance = balance + amount;

System. out .println(“ Updated balance is “ + balance);

break ;

case 3:

System. out .println(“ Available balance “ + balance);

break ;

default :

System. out .println(“ Invalid operation specified ”);

System. out .println(“ Do you want to perform more operation? ”);

System. out .println(“ Press 1 for yes ”);

System. out .println(“ Press 2 for No ”);

repeatOperation = input.nextInt();

} while (repeatOperation == 1);

84

Knock the door on [email protected]


DO WHILE LOOP

Output

Enter initial balance

10000

Select an operation to perform

1. Withdraw

2. Deposit

3. Check Balance

Enter amount to withdraw

500

Updated balance is 9500

Do you want to perform more operation?

Press 1 for yes

Press 2 for No

Select an operation to perform

1. Withdraw

2. Deposit

3. Check Balance

Available balance 9500

Do you want to perform more operation?

Press 1 for yes

Press 2 for No

85

Knock the door on [email protected]


7

NESTED LOOP
NESTED LOOP

Write a program to print following pattern in the output

12345

12345

12345

12345

12345

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

// Outer for loop is responsible for number of rows

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

// Inner for loop is responsible for number of column

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

// Print all numbers in the same line,

// so we are using print() function instead of println()

System. out . print (j);

// Press enter key after inner for loop

System. out . print ln();

Write a program to print following pattern in the output

11111

22222

33333

44444

55555

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

// Outer for loop is responsible for number of rows

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

// Inner for loop is responsible for number of column

87

Knock the door on [email protected]


NESTED LOOP

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

// Print all numbers in the same line,

// so we are using print() function instead of println()

System. out . print (i);

// Press enter key after inner for loop

System. out . print ln();

Write a program to print following pattern in the output

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

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5, counter = 11;

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

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

System. out . print (counter + “ “);

counter++;

System. out . print ln();

Write a program to print following pattern in the output

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

Knock the door on [email protected]


NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int counter = 1, numOfRows = 5;

boolean isDecrementActivated = false;

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

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

System. out . print (counter + “ “);

System. out . print ln();

// If counter value reaches 3 then activate the flag so that we will decrement

from next time


//

if (counter <= numOfRows / 2 && !isDecrementActivated) {

counter++;

} else {

isDecrementActivated = true;

counter--;

Write a program to print following pattern in the output

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

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

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

System. out . print (i);

89

Knock the door on [email protected]


NESTED LOOP

System. out . print ln();

Write a program to print following pattern in the output

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

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int j = numOfRows; j >= 1; j--) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

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

public class Pattern {

public static void main( String[] args ) {

int multiplier = 1, numOfRows = 5;

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

90

Knock the door on [email protected]


NESTED LOOP

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

System. out . print (j * multiplier + “ “);

multiplier++;

System. out . print ln();

Write a program to print following pattern in the output

* * * * *

* * * * *

* * * * *

* * * * *

* * * * *

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

System. out . print (“ * “);

System. out . print ln();

Write a program to print following pattern in the output

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

public class Pattern {

91

Knock the door on [email protected]


NESTED LOOP

public static void main( String[] args ) {

int numOfRows = 5;

char ch = ‘ A ’;

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

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

System. out . print (ch + “ “);

// Explicit type casting from int to character

ch = (char) (ch + 1);

System. out . print ln();

Write a program to print following pattern in the output from given String

Example Input - Java

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;

public class Pattern {

public static void main( String[] args ) {

Scanner input = new Scanner(System.in);

System. out . print ln(“ Enter a String ”);

String str = input.next();

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

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

System. out . print (str.charAt(i) + “ “);

System. out . print ln();

92

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

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

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

if (i == j) {

System. out . print (“ 1 ”);

} else {

System. out . print (“ 0 ”);

System. out . print ln();

Write a program to print following pattern in the output

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

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

93

Knock the door on [email protected]


NESTED LOOP

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

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

if (i == 1 || i == numOfRows || j == 1 || j == numOfRows) {

System. out . print (“ 0 ”);

} else {

System. out . print (“ 1 ”);

System. out . print ln();

Write a program to print following pattern in the output

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

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

if (j >= i) {

System. out . print (“ 1 ”);

} else {

System. out . print (“ 0 ”);

System. out . print ln();

94

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

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

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

if (i % 2 == 0) {

System. out . print (“ 0 ”);

} else {

System. out . print (“ 1 ”);

System. out . print ln();

Write a program to print following pattern in the output

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

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

if (j % 2 == 0) {

95

Knock the door on [email protected]


NESTED LOOP

System. out . print (“ 0 ”);

} else {

System. out . print (“ 1 ”);

System. out . print ln();

Write a program to print following pattern in the output

* * * * *

* * * * *

* *

* *

* *

* *

* *

* *v

* * * * *

* * * * *

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

if (i == 1 || i == numOfRows || j == 1 || j == numOfRows) {

System. out . print (“ * “);

} else {

System. out . print (“ “);

System. out . print ln();

Write a program to print following pattern in the output

96

Knock the door on [email protected]


NESTED LOOP

* * * * *

* * * * *

* *

* *

* * * * *

* * * * *

* *

* *

* * * * *

* * * * *

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

if (i == 1 || i == 5 || j == 1 || j == 5 || i == (numOfRows / 2) + 1) {

System. out . print (“ * “);

} else {

System. out . print (“ “);

System. out . print ln();

Write a program to print following pattern in the output

12

123

1234

12345

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

97

Knock the door on [email protected]


NESTED LOOP

System. out . print (J);

System. out . print ln();

Write a program to print following pattern in the output

22

333

4444

55555

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

System. out . print (i);

System. out . print ln();

Write a program to print following pattern in the output

**

***

****

*****

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

98

Knock the door on [email protected]


NESTED LOOP

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

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

System. out . print (“ * ”);

System. out . print ln();

Write a program to print following pattern in the output

54

543

5432

54321

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = 5; i >= 1; i--) {

for ( int j = 5; j >= i; j--) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

45

345

2345

12345

99

Knock the door on [email protected]


NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = 5; i >= 1; i--) {

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

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

44

333

2222

11111

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = 5; i >= 1; i--) {

for ( int j = 5; j >= i; j--) {

System. out . print (i);

System. out . print ln();

Write a program to print following pattern in the output

100

Knock the door on [email protected]


NESTED LOOP

21

321

4321

54321

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int j = i; j >= 1; j--) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

2 3

4 5 6

7 8 9 10

11 12 13 14 15

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5, counter = 1;

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

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

System. out . print (counter + “ “);

counter++;

System. out . print ln();

101

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

1 0

1 0 0

1 0 0 0

1 0 0 0 0

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

if (j == 1) {

System. out . print (“ 1 “);

} else {

System. out . print (“ 0 “);

System. out . print ln();

Write a program to print following pattern in the output

JA

JAV

JAVA

import java.util.Scanner;

public class Pattern {

public static void main( String[] args ) {

Scanner input = new Scanner(System.in);

System. out . print ln(“ Enter a String ”);

String str = input.next();

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

102

Knock the door on [email protected]


NESTED LOOP

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

System. out . print (str.charAt(j) + “ “);

System. out . print ln();

Write a program to print following pattern in the output

1 1

12 12

123 123

1234 1234

12345 12345

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

22

22

333

333

4444

4444

55555

55555

103

Knock the door on [email protected]


NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

System. out . print (i);

System. out . print ln();

Write a program to print following pattern in the output

* *

** **

*** ***

**** ****

**********

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

System. out . print (“ * ”);

System. out . print ln();

104

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

C
C

CH
CH

CHI
CHI

CHIR
CHIR

CHIRA
CHIRA

CHIRAG
CHIRAG

import java.util.Scanner;

public class Pattern {

public static void main( String[] args ) {

Scanner input = new Scanner(System.in);

System. out . print ln(“ Enter a String ”);

String str = input.next();

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

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

System. out . print (“ “);

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

System. out . print (str.charAt(j));

System. out . print ln();

Write a program to print following pattern in the output

5
5

54
54

543
543

5432
5432

54321
54321

105

Knock the door on [email protected]


NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = 1; s <= i - 1; s++) {

System. out . print (“ “);

for ( int j = numOfRows; j >= i; j--) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

5 5

45 45

345 345

23452345

12345
12345

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = 1; s <= i - 1; s++) {

System. out . print (“ “);

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

System. out . print (j);

System. out . print ln();

106

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

0
0

11
11

000
000

1111
1111

00000
00000

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

if (i % 2 == 0) {

System. out . print (“ 0 ”);

} else {

System. out . print (“ 1 ”);

System. out . print ln();

Write a program to print following pattern in the output

1 1

10 10

100 100

1000 1000

10000
10000

107

Knock the door on [email protected]


NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

if (j == 1) {

System. out . print (“ 1 ”);

} else {

System. out . print (“ 0 ”);

System. out . print ln();

Write a program to print following pattern in the output

1
1

222
222

33333
33333

4444444
4444444

555555555
555555555

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

108

Knock the door on [email protected]


NESTED LOOP

System. out . print (i);

System. out . print ln();

Write a program to print following pattern in the output

*
*

***
***

*****
*****

*******
*******

*********
*********

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

System. out . print (“ * ”);

System. out . print ln();

Write a program to print following pattern in the output

111

111

00000

00000

1111111

1111111

000000000

000000000

109

Knock the door on [email protected]


NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

if (i % 2 == 0) {

System. out . print (“ 1 ”);

} else {

System. out . print (“ 0 ”);

System. out . print ln();

Write a program to print following pattern in the output

1
1

121
121

12321
12321

1234321
1234321

123454321
123454321

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

110

Knock the door on [email protected]


NESTED LOOP

System. out . print (j);

for ( int j = i - 1; j >= 1; j--) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

0
0

101
101

11011
11011

1110111
1110111

111101111
111101111

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

if (j == i) {

System. out . print (“ 0 ”);

} else {

System. out . print (“ 1 ”);

System. out . print ln();

111

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

5
5

545
545

54345
54345

5432345
5432345

543212345
543212345

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = 1; s <= i - 1; s++) {

System. out . print (“ “);

for ( int j = numOfRows; j >= i; j--) {

System. out . print (j);

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

System. out . print (j + 1);

System. out . print ln();

Write a program to print following pattern in the output

5
5

454
454

34543
34543

2345432
2345432

123454321
123454321

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

112

Knock the door on [email protected]


NESTED LOOP

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = 1; s <= i - 1; s++) {

System. out . print (“ “);

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

System. out . print (j);

for ( int j = numOfRows - 1; j >= i; j--) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

C C

CHC CHC

CHIHCCHIHC

CHIRIHC
CHIRIHC

CHIRARIHC
CHIRARIHC

CHIRAGARIHC
CHIRAGARIHC

public class Pattern {

public static void main( String[] args ) {

Scanner input = new Scanner(System.in);

System. out . print ln(“ Enter a String ”);

String str = input.next();

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

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

System. out . print (“ “);

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

113

Knock the door on [email protected]


NESTED LOOP

System. out . print (str.charAt(j));

for ( int j = i - 1; j >= 0; j--) {

System. out . print (str.charAt(j));

System. out . print ln();

Write a program to print following pattern in the output

1
1

101
101

10001
10001

1000001
1000001

100000001
100000001

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

if (i == 1 || j == 1 || j == 2 * i - 1) {

System. out . print (“ 1 ”);

} else {

System. out . print (“ 0 ”);

System. out . print ln();

114

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

12345

1234

123

12

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

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

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

55555

4444

333

22

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

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

System. out . print (i);

System. out . print ln();

115

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

*****

****

***

**

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

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

System. out . print (“ * ”);

System. out . print ln();

Write a program to print following pattern in the output

54321

5432

543

54

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int j = 5; j > numOfRows - i; j--) {

System. out . print (j);

System. out . print ln();

116

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

12345

2345

345

45

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

11111

2222

333

44

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

System. out . print (i);

System. out . print ln();

117

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

54321

4321

321

21

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int j = i; j >= 1; j--) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

CHIRAG

CHIRA

CHIR

CHI

CH

import java.util.Scanner;

public class Pattern {

public static void main( String[] args ) {

Scanner input = new Scanner(System.in);

System. out . print ln(“ Enter a String ”);

String str = input.next();

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

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

118

Knock the door on [email protected]


NESTED LOOP

System. out . print (str.charAt(j));

System. out . print ln();

Write a program to print following pattern in the output

12345
12345

1234
1234

123
123

12
12

1
1

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

System. out . print (“ “);

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

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

55555
55555

4444
4444

333
333

22
22

1
1

119

Knock the door on [email protected]


NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

for ( int j = i; j >= 1; j--) {

System. out . print (i);

System. out . print ln();

Write a program to print following pattern in the output

*****
*****

****
****

***
***

**
**

*
*

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

System. out . print (“ “);

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

System. out . print (“ * ”);

System. out . print ln();

120

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

54321
54321

5432
5432

543
543

54
54

5
5

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

for ( int j = numOfRows; j >= numOfRows - i + 1; j--) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

12345
12345

2345
2345

345
345

45
45

5
5

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

121

Knock the door on [email protected]


NESTED LOOP

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

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

System. out . print (“ “);

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

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

11111
11111

2222
2222

333
333

44
44

5
5

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

System. out . print (“ “);

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

System. out . print (i);

System. out . print ln();

122

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

54321
54321

4321
4321

321
321

21
21

1
1

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

for ( int j = i; j >= 1; j--) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

CHIRAG
CHIRAG

CHIRA
CHIRA

CHIR
CHIR

CHI
CHI

CH
CH

C
C

public class Pattern {

public static void main( String[] args ) {

Scanner input = new Scanner(System.in);

System. out . print ln(“ Enter a String ”);

String str = input.next();

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

123

Knock the door on [email protected]


NESTED LOOP

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

System. out . print (“ “);

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

System. out . print (str.charAt(j));

System. out . print ln();

Write a program to print following pattern in the output

CHIRAG
CHIRAG

HIRAG
HIRAG

IRAG
IRAG

RAG
RAG

AG
AG

G
G

public class Pattern {

public static void main( String[] args ) {

Scanner input = new Scanner(System.in);

System. out . print ln(“ Enter a String ”);

String str = input.next();

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

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

System. out . print (“ “);

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

System. out . print (str.charAt(j));

System. out . print ln();

124

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

555555555
555555555

4444444
4444444

33333
33333

222
222

1
1

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

for ( int j = 2 * i - 1; j >= 1; j--) {

System. out . print (i);

System. out . print ln();

Write a program to print following pattern in the output

123454321
123454321

12343211234321

12321 12321

121 121

1 1

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

125

Knock the door on [email protected]


NESTED LOOP

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

System. out . print (j);

for ( int j = i - 1; j >= 1; j--) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

000000000
000000000

1111111
1111111

00000
00000

111
111

0
0

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

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

if (i % 2 == 0) {

System. out . print (“ 1 ”);

} else {

System. out . print (“ 0 ”);

System. out . print ln();

126

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

*********

*********

*******

*******

*****

*****

***

***

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

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

System. out . print (“ * ”);

System. out . print ln();

Write a program to print following pattern in the output

543212345
543212345

5432345
5432345

5434554345

545 545

5 5

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

127

Knock the door on [email protected]


NESTED LOOP

for ( int j = numOfRows; j >= numOfRows - i + 1; j--) {

System. out . print (j);

for ( int j = numOfRows - i + 2; j <= numOfRows; j++) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

123454321
123454321

2345432
2345432

34543
34543

454
454

5
5

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

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

System. out . print (“ “);

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

System. out . print (j);

for ( int j = numOfRows - 1; j >= i; j--) {

System. out . print (j);

System. out . print ln();

128

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

CHIRAGARIHC

CHIRARIHC

CHIRIHC

CHIHC

CHC

public class Pattern {

public static void main( String[] args ) {

Scanner input = new Scanner(System.in);

System. out . print ln(“ Enter a String ”);

String str = input.next();

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

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

System. out . print (“ “);

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

System. out . print (str.charAt(j));

for ( int j = i - 1; j >= 0; j--) {

System. out . print (str.charAt(j));

System. out . print ln();

Write a program to print following pattern in the output

100000001
100000001

1000001
1000001

10001
10001

101 101

1 1

public class Pattern {

public static void main( String[] args ) {

129

Knock the door on [email protected]


NESTED LOOP

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

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

if (j == 1 || j == 2 * i - 1) {

System. out . print (“ 1 ”);

} else {

System. out . print (“ 0 ”);

System. out . print ln();

Write a program to print following pattern in the output

1 1

222

33333
33333

4444444
4444444

555555555
555555555

4444444
4444444

33333
33333

222
222

1 1

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

130

Knock the door on [email protected]


NESTED LOOP

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

System. out . print (i);

System. out . print ln();

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

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

System. out . print (i);

System. out . print ln();

Write a program to print following pattern in the output

*
*

***
***

*****
*****

*******
*******

*********
*********

*******
*******

*****
*****

***
***

*
*

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

131

Knock the door on [email protected]


NESTED LOOP

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

System. out . print (“ * ”);

System. out . print ln();

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

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

System. out . print (“ * ”);

System. out . print ln();

Write a program to print following pattern in the output

0
0

111
111

00000
00000

1111111
1111111

000000000
000000000

1111111
1111111

00000
00000

111
111

0
0

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

132

Knock the door on [email protected]


NESTED LOOP

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

if (i % 2 == 0) {

System. out . print (“ 1 ”);

} else {

System. out . print (“ 0 ”);

System. out . print ln();

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

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

if (i % 2 == 0) {

System. out . print (“ 1 ”);

} else {

System. out . print (“ 0 ”);

System. out . print ln();

Write a program to print following pattern in the output

1
1

121
121

12321
12321

1234321
1234321

123454321
123454321

1234321
1234321

12321
12321

121
121

1
1

133

Knock the door on [email protected]


NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

System. out . print (j);

for ( int j = i - 1; j >= 1; j--) {

System. out . print (j);

System. out . print ln();

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

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

System. out . print (j);

for ( int j = i - 1; j >= 1; j--) {

System. out . print (j);

System. out . print ln();

134

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

0
0

101
101

11011
11011

1110111
1110111

111101111
111101111

1110111
1110111

11011
11011

101
101

0
0

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

if (i == j) {

System. out . print (“ 0 ”);

} else {

System. out . print (“ 1 ”);

System. out . print ln();

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

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

if (i == j) {

System. out . print (“ 0 ”);

135

Knock the door on [email protected]


NESTED LOOP

} else {

System. out . print (“ 1 ”);

System. out . print ln();

Write a program to print following pattern in the output

55

545
545

54345
54345

5432345
5432345

543212345
543212345

5432345
5432345

5434554345

545 545

5 5

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = 1; s <= i - 1; s++) {

System. out . print (“ “);

for ( int j = numOfRows; j >= i; j--) {

System. out . print (j);

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

System. out . print (j + 1);

System. out . print ln();

136

Knock the door on [email protected]


NESTED LOOP

for ( int i = numOfRows - 1; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

for ( int j = numOfRows; j >= numOfRows - i + 1; j--) {

System. out . print (j);

for ( int j = numOfRows - i + 2; j <= numOfRows; j++) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

454

34543

2345432

123454321

2345432

34543

454

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

System. out . print (j);

137

Knock the door on [email protected]


NESTED LOOP

for ( int j = i - 1; j >= 1; j--) {

System. out . print (j);

System. out . print ln();

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

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

System. out . print (j);

for ( int j = i - 1; j >= 1; j--) {

System. out . print (j);

System. out . print ln();

Write a program to print following pattern in the output

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

Knock the door on [email protected]


NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

Scanner input = new Scanner(System.in);

System. out . print ln(“ Enter a String ”);

String str = input.next();

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

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

System. out . print (“ “);

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

System. out . print (str.charAt(j));

for ( int j = i - 1; j >= 0; j--) {

System. out . print (str.charAt(j));

System. out . print ln();

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

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

System. out . print (“ “);

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

System. out . print (str.charAt(j));

for ( int j = i - 1; j >= 0; j--) {

System. out . print (str.charAt(j));

System. out . print ln();

139

Knock the door on [email protected]


NESTED LOOP

Write a program to print following pattern in the output

1
1

101
101

10001
10001

1000001
1000001

100000001
100000001

1000001
1000001

10001
10001

101
101

1
1

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

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

for ( int s = 1; s <= numOfRows - i; s++) {

System. out . print (“ “);

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

if (i == 1 || j == 1 || j == 2 * i - 1) {

System. out . print (“ 1 ”);

} else {

System. out . print (“ 0 ”);

System. out . print ln();

for ( int i = numOfRows; i >= 1; i--) {

for ( int s = numOfRows; s > i; s--) {

System. out . print (“ “);

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

if (j == 1 || j == 2 * i - 1) {

140

Knock the door on [email protected]


NESTED LOOP

System. out . print (“1”);

} else {

System. out . print (“0”);

System. out . print ln();

141

Knock the door on [email protected]


8

STRING PROGRAM
STRING PROGRAM

Write a program to count number of vowels from the string

Input Output

_____________________________________________________________________

“we will be completing String class today” 10


Example

import java.util.Scanner;

public class CountNumberOfVowels {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter a String ”);

String str = input.nextLine();

str = str.toLowerCase();

int vowelCount = 0;

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

if (str.charAt(i) == ‘ a ’ || str.charAt(i) == ‘ i ’ || str.charAt(i) == ‘ e ’ || str.charAt(i) == ‘ o ’

|| str.charAt(i) == ‘ u ’) {

vowelCount++;

System. out .println(vowelCount);

Output

Enter a String

we will be completing String class today

10

Write a program to count number of vowels, digit, spaces from the string

Input Output

________________________________________________________________________________

“we will be completing String class today” Num of vowels - 10

Num of digit - 0
Example

Num of spaces - 6

import java.util.Scanner;

public class CountDigitCharAndSpace {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter a String ”);

String str = input.nextLine();

143

Knock the door on [email protected]


STRING PROGRAM

int numberOfVowels = 0, digit = 0, spaces = 0;

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

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 ;

System. out .println(“ Num of vowels - “ + numberOfVowels);

System. out .println(“ Num of digit - “ + digit);

System. out .println(“ Num of spaces - “ + spaces);

Output

Enter a String

we will be completing String class today

10

Write a program to count number of words from the string

Input Output

____________________________________________________________________

“we will be completing String class today” 7


Example

144

Knock the door on [email protected]


STRING PROGRAM

import java.util.Scanner;

public class CountNumberOfVowels {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter a String ”);

String str = input.nextLine();

String parts[] = str.split(“ “);

System. out .println(parts.length);

Output

Enter a String

we will be completing String class today

Write a program to count number of words of String without using library function

Input Output

___________________________________________________________________

“This is my first String program” 6


Example

import java.util.Scanner;

public class FindLengthOfString {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter a String ”);

String str = input.nextLine().trim();

int frequecyCounter = 0;

if (!str.isEmpty()) {

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

if (str.charAt(i) == ‘ ‘) {

frequecyCounter++;

System. out .println(frequecyCounter + 1); // No of word = No of space + 1

} else {

System. out .println(frequecyCounter);

145

Knock the door on [email protected]


STRING PROGRAM

Output

Enter a String

This is my java program

Write a program to find frequency of given character from given String

Input Output

________________________________________________________________________________

“we will be completing String class today”


Example

Character : s 3

import java.util.Scanner;

public class FrequencyOfChar {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter a String ”);

String str = input.nextLine().trim();

System. out .println(“ Enter a character ”);

char c = input.next().charAt(0);

int frequecyCounter = 0;

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

if (str.charAt(i) == ‘c) {

frequecyCounter++;

System. out .println(frequecyCounter);

Output

Enter a String

This is my java program

Enter a character

146

Knock the door on [email protected]


STRING PROGRAM

Write a program to print reverse of given String

Input Output

___________________________________________

Elon Musk ksuM nolE


Example

import java.util.Scanner;

public class FindReverseOfGivenString {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter your name ”);

String name = input.nextLine();

System. out .println(“ Reverse - ”);

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

System. out .print(name.charAt(i));


1

System. out .println();


APPROACH

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

System. out .print(name.charAt(name.length() - 1 - i));


2

}
APPROACH

Output

Enter your name

Elon Musk

Reverse - ksuM nolE

Write a program to take full name from the user and print initials from the name

Input Output

______________________________________________

Elon Musk E.M.


Example

import java.util.Scanner;

public class InitialsFromName {

147

Knock the door on [email protected]


STRING PROGRAM

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter your name ”);

String name = input.nextLine();

System. out .println(“ Initials - ”);

String initial = name.charAt(0) + ;”.“

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

if (name.charAt(i) == ‘ ‘) {

initial = initial + name.charAt(i + 1) + “ . ”;

System. out .println(initial);

Output

Enter your name

Elon Musk

Initials - E.M.

Write a program to count number of spaces from the String

Input Output

_____________________________________________________

Hello User, How are you? 4


Example

import java.util.Scanner;

public class CountNumberOfSpacest {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter any statement ”);

String str = input.nextLine();

int count = 0;

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

if (str.charAt(i) == ‘ ‘) {

count++;

148

Knock the door on [email protected]


STRING PROGRAM

System. out .println(“ Spaces - “ + count);

Output

Enter any statement

Hello User, How are you?

Spaces - 4

Write a program to check given two strings are anagram or not

Two strings are said to be anagrams, if they contain the same characters but

in a different order

Input Output

__________________________________________________

Heart & Earth Anagram


Example

import java.util.Scanner;

public class AnagramString {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter first string ”);

String str1 = input.nextLine();

System. out .println(“ Enter second string ”);

String str2 = input.nextLine();

char[] array1 = str1.toLowerCase().toCharArray();

char[] array2 = str2.toLowerCase().toCharArray();

Arrays.sort(array1);

Arrays.sort(array2);

if Arrays.equals(array1, array2)) {

System. out .println(“ Anagram ”);

} else {

System. out .println(“ Not Anagram ”);

Output

Enter first string

Earth

149

Knock the door on [email protected]


STRING PROGRAM

Enter second string

Heart

Anagram

Write a program to check given string is palindrome or not

A String that reads the same backward or forward called palindrome

Input Output

_____________________________________

level palindrome
Example

import java.util.Scanner;

public class PalindromeString {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine();

String rev = “”;

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

rev = rev + str.charAt(i);

if str.equals(rev)) {

System. out .println(“ Palindrome ”);

} else {

System. out .println(“ Not Palindrome ”);

Output

Enter the string

moodoom

Palindrome

Write a program to find duplicate characters in the String

Input Output

______________________________________________________

This is my java program i a m a r


Example

150

Knock the door on [email protected]


STRING PROGRAM

import java.util.Scanner;

public class FindDuplicateCharacters {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine();

char[] array = str.replace(“ “ , “”).toCharArray();

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

int frequency = 0;

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

if (array[i] != ‘ ‘ && array[i] == array[j]) {

frequency++;

//Set array[j] to space to avoid printing visited character

array[j] = ‘ ‘;

if (frequency > 0) {

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

Output

Enter the string

This is my java program

Write a program to find duplicate word in the String

Input Output

______________________________________________________________________________

Learning java programming is not easy but once

you learn java it is easy and interesting java is easy


Example

import java.util.Scanner;

public class FindDuplicateWord {

151

Knock the door on [email protected]


STRING PROGRAM

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine();

String[] words = str.split(“ “);

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

int frequency = 0;

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

if (words[i] != null && words[i].equals(words[j])) {

frequency++;

//Set array[j] to null to avoid printing visited character

array[j] = null;

if (frequency > 0) {

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

Output

Enter the string

Java Program and Java Programming and Java and Java

Java

and

Write a program to find largest word in the String

Input Output

________________________________________________________________________________

Learning java programming is not easy but once

you learn java it is easy and interesting programming


Example

import java.util.Scanner;

public class LargetstWord {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine();

152

Knock the door on [email protected]


STRING PROGRAM

String[] words = str.split(“ “);

// initialize first word length as max length

int maxLength = words[0].length();

String maxString = null;

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

// If we find any word that is greater than our current max word then we will assign new

// word into max word

if (maxLength < words[i].length()) {

maxLength = words[i].length();

maxString = words[i];

System. out .println(maxString);

Output

Enter the string

Learning java programming is not easy but once you learn java it is easy and interesting

programming

Write a program to find smallest word in the String

Input Output

______________________________________________________________________________

Learning java programming is not easy but once

you learn java it is easy and interesting is


Example

import java.util.Scanner;

public class SmallestWord {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine();

String[] words = str.split(“ “);

// initialize first word length as max length

int maxLength = words[0].length();

String minString = null;

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

153

Knock the door on [email protected]


STRING PROGRAM

// If we find any word that is greater than our current max word then we will assign new

// word into max word

if (minLength > words[i].length()) {

minLength = words[i].length();

minString = words[i];

System. out .println(minString);

Output

Enter the string

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;

public class LengthOfString {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine();


1

char[] array = str.toCharArray();

int count = 0;
APPROACH

for ( char c : array) {

count++;

System. out .println(count);

import java.util.Scanner;
2

public class FirstClass {

public static void main(String[] args ) {


APPROACH

154

Knock the door on [email protected]


STRING PROGRAM

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine();

int count = 0;

try {

while (true) {

str.charAt(count);

count++;

} catch (StringIndexOutOfBoundsException e) {

System. out .println(count);

Output

Enter the string

programming

11

Write a program to find length of each word from the String

import java.util.Scanner;

public class LengthOfEachWord {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine();

String[] words = str.split(“ “);

for ( String word : words) {

System. out .println(word + “ “ + word.length());

Output

Enter the string

java revision notes and java programming puzzules

155

Knock the door on [email protected]


STRING PROGRAM

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

______________________________________________________________________________

Learning java programming is not Learning\java\programming\is\not\

easy but once you learn java it is easy\but\once\you\learn\java\it\is


Example

easy and interesting \easy\and\interesting

import java.util.Scanner;

public class ReplaceSpaceWithSlash {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Please enter the string ”);

String str = input.nextLine();

str = str.replace(“ ,“ “\\”);

System. out .println(str);

Output

Please enter the string

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

Knock the door on [email protected]


STRING PROGRAM

import java.util.Scanner;

public class CaeserCipher {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine().toLowerCase();

System. out .println(“ Enter the encryption key ”);

int key = input.nextInt();

final String ALPHABET = “abcdefghijklmnopqrstuvwxyz”;

char[] charArray = str.toCharArray();

String encodedString = “”;

for ( char c : charArray) {

int currentPosition = ALPHABET.indexOf(c);

int encodedPosition = (key + currentPosition) % 26;

encodedString = encodedString + ALPHABET.charAt(encodedPosition);

System. out .println(encodedString);

Output

Enter the string

easyjava

Enter the encryption key

jfxdofaf

Write a program to reverse each word of the given String

Input Output

______________________________________________________________________________

Learning java programming is not gninrael avaj gnimmargorp si ton

easy but once you learn java it is ysae tub ecno uoy nrael avaj ti si

easy and interesting ysae dna gnitseretni


Example

import java.util.Scanner;

public class ReverseEachWord {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

157

Knock the door on [email protected]


STRING PROGRAM

System. out .println(“ Enter the string ”);

String str = input.nextLine().toLowerCase();

String[] words = str.split(“ “);

String rev = “”;

for ( String word : words) {

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

rev = rev + word.charAt(i);

} rev = rev + “ “;

System. out .println(rev);

Output

Enter the string

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

Write a program to print first unique character from the String

Input Output

_____________________________________________

programming puzzules r
Example

import java.util.Scanner;

public class FirstUniqueCharacter {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine().toLowerCase();

boolean isFound = false;

for ( char c : str.toCharArray()) {

//If first index of character is equals to last index of character then that character is unique

//in the String

if (str.indexOf(c) == str.lastIndexOf(c)) {

System. out .println(c);

isFound = true;

break ;

158

Knock the door on [email protected]


STRING PROGRAM

// If value of isFound is still false then it means that we do not have unique character of String

//is empty

if (!isFound) {

System. out .println(-1);

Output

Enter the string

javajava

-1

Write a program to print unique word from the String

Input Output

______________________________________________________________________________

java revision notes java programming

notes and java questions revision programming and questions


Example

import java.util.Scanner;

public class UniqueWord {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine().toLowerCase();

String[] words = str.split(“ “);

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

// Setting count of current word to zero

int count = 1;

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

if (words[i].equalsIgnoreCase(words[j])) {

count++;

// make another word blank otherwise it will get count more than one time

words[j] = “”;

if (count == 1 && words[i] != “”) {

System. out .print(words[i] + “ “);

159

Knock the door on [email protected]


STRING PROGRAM

Output

Enter the string

java revision notes java programming notes and java questions

revision programming and questions

Write a program to check given string is palindrome or not ignoring the space and case

Input Output

___________________________________________________

Never odd or even Palindrome


Example

import java.util.Scanner;

public class PalindromeStringWithoutSpace {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine();

str = str.replace(“ “,””).toLowerCase();

String rev = “”;

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

rev = rev + str.charAt(i);

if (str.equals(rev)) {

System. out .println(“ Palindrome ”);

} else {

System. out .println(“ Not Palindrome ”);

Output

Enter the string

Yo banana boy

Palindrome

Write a program to compress the given String

160

Knock the door on [email protected]


STRING PROGRAM

Input Output

________________________________________

aabbbccddd a2b3c2d4
Example

import java.util.Scanner;

public class CompressString {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine();

int count = 1;

char c = str.charAt(0);

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

if (c == str.charAt(i)) {

count++;

} else {

System. out .println(c + “” + count);

count = 1;

c = str.charAt(i);

System. out .println(c + “” + count);

Output

Enter the string

aaabcccddddd

a3

b1

c3

d5

Write a program to reverse sequence of word from the String

Input Output

______________________________________________________________________________________

Learning java is now feels easy ease feels now is java Learning
Example

161

Knock the door on [email protected]


STRING PROGRAM

import java.util.Scanner;

public class ReverseSequenceOfWord {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

System. out .println(“ Enter the string ”);

String str = input.nextLine();

String words[] = str.split(“ “);

String rev = “”;

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

rev = rev + words[i] + “ “;

System. out .println(rev);

Output

Enter the string

Learning java is now feels easy

easy feels now is java Learning

162

Knock the door on [email protected]


9

USING ARRAY
USING ARRAY

Write a program to find index of a given element from an array

Input Output

_____________________________________________________________________

Enter five numbers : 56 24 75 43 65 1


Example

Enter the number to find : 24

import java.util.Scanner;

public class FindIndexOfNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( “Enter five numbers” );

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

numbers[i] = input.nextInt();

System .out.println( “Enter the number to find” );

int targetNumber = input.nextInt();

boolean isFound = false ;

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

if (targetNumber == numbers[i]) {

System .out.println(i);

isFound = true ;

if ( ! isFound) {

System .out.println( -1 );

Output

Enter five numbers

56 24 75 43 65

Enter the number to find

24

Write a program to find greatest number from an array

Input Output

_____________________________________________________________________

Enter five numbers : 56 24 75 43 65 75


Example

164

Knock the door on [email protected]


USING ARRAY

import java.util.Scanner;

public class MaxNumberFromArray {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( “Enter five numbers” );

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

numbers[i] = input.nextInt();

int max = numbers[0];

for ( int num : numbers) {

if (max < num) {

max = num;

System .out.println(max);

Output

Enter five numbers

56 24 75 43 65

75

Write a program to find sum of array elements

Input Output

_____________________________________________________________________

Enter five numbers : 56 23 74 45 65 263


Example

import java.util.Scanner;

public class SumOfArrayElements {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( “Enter five numbers” );

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

numbers[i] = input.nextInt();

int sum = 0 ;

165

Knock the door on [email protected]


USING ARRAY

for ( int num : numbers) {

sum = sum + num;

System .out.println(sum);

Output

Enter five numbers

56 23 74 45 65

263

Write a program to find sum of even and odd numbers

Input Output

_____________________________________________________________________

Enter five numbers : 56 24 75 43 65 183, 80


Example

import java.util.Scanner;

public class SumOfEvenAndOdd {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( “Enter five numbers” );

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

numbers[i] = input.nextInt();

int sumEvn = 0 ;

int sumOdd = 0 ;

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

if (numbers[i] % 2 == 0 ) {

sumEvn = sumEvn + numbers[i];

} else {

sumOdd = sumOdd + numbers[i];

System .out.println(sumOdd);

System .out.println(sumEvn);

166

Knock the door on [email protected]


USING ARRAY

Output

Enter five numbers

56 24 75 43 65

183

80

Write a program to count number of positive(consider zero also positive) and

negative numbers from an array

Input Output

_____________________________________________________________________

Enter five numbers : 56 -24 -75 43 65 3, 2


Example

import java.util.Scanner;

public class CountPositveAndNegativeNumbersFromArray {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int[ 5 ];

System .out.println( “Enter five numbers” );

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

numbers[i] = input.nextInt();

int positiveCount = 0 , negativeCount = 0 ;

for ( int num : numbers) {

if (num >= 0 ) {

positiveCount ++ ;

} else {

negativeCount ++ ;

System .out.println(positiveCount);

System .out.println(negativeCount);

Output

Enter five numbers

56 -24 -75 43 65

167

Knock the door on [email protected]


USING ARRAY

Write a program to check given number is available in the array or not

Input Output

____________________________________________________________________________

Enter five numbers : 56 -24 -75 43 65 65 is in the array


Example

Enter number to find : 65

import java.util.Scanner;

public class NumberContains {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( “Enter five numbers” );

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

numbers[i] = input.nextInt();

System .out.println( “Enter number to find” );

int targetNum = sc.nextInt();

boolean isNumberFound = false ;

for ( int num : numbers) {

if (targetNum == num) {

isNumberFound = true ;

if (isNumberFound) {

System .out.println(targetNum + “ is in the array” );

} else {

System .out.println(targetNum + “ is not in the array” );

Output

Enter five numbers

56 -24 -75 43 65

Enter number to find

65

65 is in the array

168

Knock the door on [email protected]


USING ARRAY

Write a program to find all duplicates number from the array

Input Output

_____________________________________________________________________

Enter five numbers : 54 54 54 56 56 54, 56


Example

import java.util.Scanner;

public class DuplicateNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( “Enter five numbers” );

int count = 0 ;

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

numbers[i] = input.nextInt();

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

// initialize count to zero for the current number

count = 0 ;

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

if (numbers[i] == numbers[j] && numbers[i] != Integer .MAX_VALUE) {

count ++ ;

// Update duplicate number to integer max value,

// otherwise it will print duplicate numbers in the output

numbers[j] = Integer .MAX_VALUE;

if (count > 0) {

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

Output

Enter five numbers

54 54 54 56 56

54

56

169

Knock the door on [email protected]


USING ARRAY

Write a program to print the elements of an array present in the odd position

Input Output

_____________________________________________________________________

Enter five numbers : 45 23 76 23 56 23, 23


Example

import java.util.Scanner;

public class ElementInOddPosition {

public static void main(String[] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( “Enter five numbers” );

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

numbers[i] = input.nextInt();

int count = 0 ;

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

if (i % 2 == 1 ) {

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

Output

Enter five numbers

45 23 76 23 56

23

23

Write a program to sort array elements in ascending order

Input Output

__________________________________________________________________________________________

Enter five numbers : 45 23 76 23 56 Sorted Array : 23 23 45 56 76


Example

import java.util.Scanner;

public class SortElements {

public static void main(String[] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( “Enter five numbers” );

170

Knock the door on [email protected]


USING ARRAY

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

numbers[i] = input.nextInt();

// Check each number with current number and if we find any number less than current number,

// then swap it with current number

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

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

if (numbers[i] > numbers[j]) {

int temp = numbers[i];

numbers[i] = numbers[j];

numbers[j] = temp;

System .out.println( “Sorted Array “ );

for ( int num : numbers) {

System .out.println(num);

Output

Enter five numbers

45 23 76 23 56

Sorted Array

23

23

45

56

76

Write a program to print all unique elements from the array

Input Output

_____________________________________________________________________

Enter five numbers : 54 54 54 56 56 54, 56


Example

import java.util.Scanner;

public class UniqueElements {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int numbers[] = new int [ 5 ];

System .out.println( “Enter five numbers” );

171

Knock the door on [email protected]


USING ARRAY

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

numbers[i] = input.nextInt();

int count = 1 ;

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

// initialize count to one for the current number

count = 1 ;

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

if (numbers[i] == numbers[j] && numbers[i] != Integer .MAX_VALUE) {

count ++ ;

// Assign integer max value to rest of the same element otherwise

// it will be checked multiple times

numbers[i] = Integer.MAX_VALUE;

if (count == 1) { // if count is still one that mean it is unique element

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

Output

Enter five numbers

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

_________________________________________________________________________________________

Enter five numbers : 52 54 13 77 80 Result Array : 77 13 54 52 80


Example

import java.util.Scanner;

public class SegregateOddEven {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( “Enter five numbers” );

172

Knock the door on [email protected]


USING ARRAY

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

numbers[i] = input.nextInt();

int left = 0 , right = numbers.length - 1 ;

while (left < right) {

// increment left value till we are getting odd numbers

while (numbers[left] % 2 == 1 && left < right) {

left ++ ;

while (numbers[right] % 2 == 0 && left < right) {

right -- ;

// swap two number if left is still less than right

if (left < right) {

int temp = numbers[left];

numbers[left] = numbers[right];

numbers[right] = temp;

System .out.println( “Result Array” );

for ( int num : numbers) {

System .out.print(num + “ “ );

Output

Enter five numbers

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

_____________________________________________________________________

Enter five numbers : 56 24 75 43 65 4


Example

Enter target number : 6 2

173

Knock the door on [email protected]


USING ARRAY

import java.util.Scanner;

public class TwoElementSumIsEqualToGivenNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five numbers" );

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

numbers[i] = input.nextInt();

System .out.println( "Enter target number" );

int targetNum = input.nextInt();

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

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

if (numbers[i] + numbers[j] == targetNum){

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

System .out.println(numbers[j]);

Output

Enter five numbers

3 4 7 2 7

Enter target number

Write a program to remove specific element from the array

Input Output

______________________________________________________________________________________

Enter five numbers : 52 54 13 77 80 Result Array : 52 54 77 80


Example

Enter the number to remove : 13

import java.util.Scanner;

public class RemoveElement {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

int anotherArray[] = new int [numbers.length - 1 ];

174

Knock the door on [email protected]


USING ARRAY

System .out.println( "Enter five numbers" );

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

numbers[i] = input.nextInt();

System .out.println( "Enter the number to remove" );

int targetNum = input.nextInt(), targetPosition = -1 ;

boolean isElementFound = false ;

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

if (numbers[i] == targetNum) {

isElementFound = true ;

targetPosition = i;

break ;

if (isElementFound) {

for ( int i = 0 , j = 0 ; i < numbers.length; i ++ ) {

if (i != targetPosition) {

anotherArray[j] = numbers[i];

j ++ ;

} else {

System .out.println( "Number not found in the array" );

System .out.println( "Result Array" );

for ( int num : anotherArray) {

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

Output

Enter five numbers

52 54 13 77 80

Enter the number to remove

13

Result Array

52 54 77 80

175

Knock the door on [email protected]


USING ARRAY

Write a program to insert specific element in the array at specific position

Input Output

_____________________________________________________________________________________________

Enter five numbers : 52 54 13 77 80 Result Array : 52 54 12 13 77 80

Enter the number to insert: 12


Example

Enter the position: 2

import java.util.Scanner;

public class InsertElement {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

int anotherArray[] = new int [numbers.length + 1 ];

System .out.println( "Enter five numbers" );

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

numbers[i] = sc.nextInt();

System .out.println( "Enter the number to insert" );

int targetNum = input.nextInt();

System .out.println( "Enter the position" );

int targetPosition = input.nextInt();

for (int i = 0 , j = 0 ; i < numbers.length; i ++ ) {

if (i == targetPosition) {

anotherArray[j] = targetNum;

j ++ ;

anotherArray[j] = numbers[i];

j ++ ;

System .out.println( "Result Array" );

for ( int num : anotherArray) {

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

176

Knock the door on [email protected]


USING ARRAY

Output

Enter five numbers

52 54 13 77 80

Enter the number to insert

12

Enter the position

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

_________________________________________________________________________________________

Enter five numbers : 52 54 13 77 32 Result Array : 25 45 31 77 23


Example

import java.util.Scanner;

public class EachNumbersInReverseOrder {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five numbers" );

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

numbers[i] = input.nextInt();

for ( int i = 0 , j = 0 ; i < numbers.length; i ++ ) {

int num = numbers[i];

int rev = 0 ;

while (num > 0 ) {

rev = rev * 10 + num % 10 ;

num = num / 10 ;

numbers[i] = rev;

System .out.println( "Result Array" );

for ( int num : numbers) {

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

177

Knock the door on [email protected]


USING ARRAY

Output

Enter five numbers

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

ybuR tseT noitamotuA

import java.util.Scanner;

public class EachStringInReverseOrder {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

String listOfString[] = new String [ 5 ];

System .out.println( "Enter five Strings" );

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

listOfString[i] = input.next();

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

String rev = "" ;

char charArray[] = listOfString[i].toCharArray();

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

rev = rev + charArray[j];

listOfString[i] = rev;

System .out.println( "Result Array" );

for ( String str : listOfString) {

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

Output

Enter five Strings

Java Python C# C++ Ruby

Result Array

avaJ nohtyP #C ++C ybuR

178

Knock the door on [email protected]


USING ARRAY

Write a program to find common elements between two arrays

Input Output

_____________________________________________________________________________________________

Enter five elements for array 1 : 52 54 13 77 32 Common elements are

Enter five elements for array 2 : 53 52 17 32 15 52


Example

32

import java.util.Scanner;

public class CommonElements {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int array1[] = new int [ 5 ];

int array2[] = new int [ 5 ];

System .out.println( "Enter five elements for array 1" );

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

array1[i] = input.nextInt();

System .out.println( "Enter five elements for array 2" );

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

array2[i] = input.nextInt();

System .out.println( "Common elements are " );

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

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

if (array1[i] == array2[j]) {

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

break ;

Output

Test Case 1

Enter five elements for array 1

52 54 13 77 32

Enter five elements for array 2

53 52 17 32 15

Common elements are

52

32

179

Knock the door on [email protected]


USING ARRAY

Test Case 2

Enter five elements for array 1

15 15 15 15 15

Enter five elements for array 2

15 15 15 14 14

Common elements are

15

15

15

15

15

Please brainstorm how to print unique common elements between two arrays?

Write a program to remove duplicate elements from the array

Input Output

__________________________________________________________________________________

Enter five elements : 56 56 76 56 43 Result Array : 76 56 43


Example

import java.util.Scanner;

public class RemoveDuplicateElement {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five elements" );

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

numbers[i] = input.nextInt();

int count = 1 ;

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

count = 1; // initialize count to one for the current number

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

if (numbers[i] == numbers[j] && numbers[i] != Integer .MAX_VALUE) {

count ++ ;

// Assign integer max value to rest of the same element otherwise

// it will be checked multiple times

numbers[i] = Integer .MAX_VALUE;

180

Knock the door on [email protected]


USING ARRAY

// Find the number of unique elements in the array

int noOfUniqueElement = 0 ;

for ( int num : numbers) {

if (num != Integer .MAX_VALUE) {

noOfUniqueElement ++ ;

// Store unique element in another array

int anotherArray[] = new int [noOfUniqueElement];

for ( int i = 0 , j = 0 ; i < numbers.length; i ++ ) {

if (numbers[i] != Integer .MAX_VALUE) {

anotherArray[j] = numbers[i];

j ++ ;

System .out.println( "Result Array " );

for ( int num : anotherArray) {

System .out.println(num);

Output

Enter five elements

56 56 76 56 43

Result Array

76

56

43

Write a program to find second largest number from the array

Input Output

_________________________________________________________________

Enter five elements : 5 4 3 2 1 4


Example

import java.util.Scanner;

public class SecondLargestNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five elements" );

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

numbers[i] = input.nextInt();

181

Knock the door on [email protected]


USING ARRAY

int max = Integer .MIN_VALUE;

int secondMax = Integer .MIN_VALUE;

for ( int num : numbers) {

if (max < num) {

secondMax = max;

max = num;

} else if (secondMax < num && num != max) {

secondMax = num;

System .out.println(secondMax);

Output

Enter five elements

5 4 3 2 1

Write a pogram to find second smallest number from the array

Input Output

_________________________________________________________________

Enter five elements : 1 2 3 4 5 2


Example

import java.util.Scanner;

public class SecondSmallestNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five elements" );

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

numbers[i] = input.nextInt();

int min = Integer .MAX_VALUE;

int secondMin = Integer .MAX_VALUE;

for ( int num : numbers) {

if (min > num) {

secondMin = min;

min = num;

182

Knock the door on [email protected]


USING ARRAY

} else if (secondMin > num && num != min) {

secondMin = num;

System .out.println(secondMin);

Output

Enter five elements

1 2 3 4 5

Write a program to find smallest number from the array

Input Output

_________________________________________________________________

Enter five elements : 56 56 76 56 43 43


Example

import java.util.Scanner;

public class SmallestNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five elements" );

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

numbers[i] = input.nextInt();

int min = Integer .MAX_VALUE;

for ( int num : numbers) {

if (num < min) {

min = num;

System .out.println(min);

Output

Enter five elements

56 56 76 56 43

43

183

Knock the door on [email protected]


USING ARRAY

Write a program to move all 0's to the end of the array.

Maintain the relative order of non zero elements as well

Input Output

_________________________________________________________________________________________

Enter five elements : 31 0 34 0 0 Result Array : 31 34 0 0 0


Example

import java.util.Scanner;

public class MoveZeros {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five elements" );

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

numbers[i] = input.nextInt();

int index = 0 ;

// Add all non-zero element in the array in sequential order

for ( int num : numbers) {

if (num != 0 ) {

numbers[index] = num;

index ++ ;

// Fill rest of the blocks with zero

while (index < numbers.length) {

numbers[index] = 0 ;

index ++ ;

System .out.println( "Result Array" );

for (int i : numbers) {

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

Output

Enter five elements

31 0 34 0 0

Result Array

31 34 0 0 0

184

Knock the door on [email protected]


USING ARRAY

Write a program to count number of odd and even number in the array

(Consider zero as a positive as well)

Input Output

____________________________________________________________________________________

Enter five elements : 34 45 23 56 23 No of even element is 2


Example

No of odd element is 3

import java.util.Scanner;

public class CountOddEven {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five elements" );

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

numbers[i] = input.nextInt();

int even = 0 , odd = 0 ;

for ( int num : numbers) {

if (num % 2 == 0 ) {

even ++ ;

} else {

odd ++ ;

System .out.println( "No of even element is " + even);

System .out.println( "No of odd element is " + odd);

Output

Enter five elements

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

number from the array

Input Output

__________________________________________________________________

Enter five elements : 34 45 23 56 23 102


Example

185

Knock the door on [email protected]


USING ARRAY

import java.util.Scanner;

public class SumOfElementExceptSmallestAndLargest {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five elements" );

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

numbers[i] = input.nextInt();

int smallest = Integer .MAX_VALUE;

int largest = Integer .MIN_VALUE;

int sum = 0 ;

for ( int num : numbers) {

if (num <= smallest) {

smallest = num;

} else if (num > largest) {

largest = num;

for (int numb : numbers) {

sum += numb;

sum = sum - smallest - largest;

System .out.println(sum);

Output

Enter five elements

34 45 23 56 23

102

Write a Java program to find the length of the longest consecutive elements

sequence from the array

Input Output

______________________________________________________________________________________

Enter ten elements : 3 7 8 9 10 43 45 46 47 9 3 (As longest consecutive


Example

are 45, 46 & 47)

186

Knock the door on [email protected]


USING ARRAY

import java.util.Scanner;

public class LCS {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 10 ];

System .out.println( "Enter ten elements" );

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

numbers[i] = input.nextInt();

int count = 1 ; // Hold final result

int temp = 1 ; // Count consecutive elements each time

for ( int i = 0 ; i < numbers.length - 1 ; i ++ ) {

if (numbers[i] + 1 == numbers[i + 1 ]) {

temp ++ ; // Count consecutive elements

} else {

temp = 1 ;

// Check if we got consecutive elements more than

// our previous count then update value of the count

if (temp > count) {

count = temp;

System .out.println(count);

Output

Enter ten elements

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

closer to the zero

Input Output

__________________________________________________________________

Enter five elements : 12 3 0 -1 1 -1 1


Example

187

Knock the door on [email protected]


USING ARRAY

import java.util.Scanner;

public class SumOfNumCloseToZero {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five elements" );

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

numbers[i] = input.nextInt();

// We need to find minimum value of sum here instead of element

// 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 minSum = numbers[ 0 ] + numbers[ 1 ];

int num1 = 0 ;

int num2 = 0 ;

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

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

int currentSum = numbers[i] + numbers[j];

// If current sum is less than minSum then update the value of minSum

if ( Math .abs(currentSum) < Math .abs(minSum)) {

num1 = numbers[i];

num2 = numbers[j];

minSum = currentSum;

System .out.println(num1 + " " + num2);

Output

Enter five elements

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

__________________________________________________________________

Enter five elements : 12 3 0 -1 1 36


Example

188

Knock the door on [email protected]


USING ARRAY

import java.util.Scanner;

public class MaximumProduct {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five elements" );

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

numbers[i] = input.nextInt();

int maxProduct = 0 ;

for ( int i = 0 ; i < numbers.length - 1 ; i ++ ) {

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

int currentProduct = numbers[i] * numbers[j];

if (currentProduct > maxProduct) {

maxProduct = currentProduct;

System .out.println(maxProduct);

Output

Enter five elements

12 3 0 -1 1

36

Write a program to print sum of each column of 2D array

public class SumOfEachColumn {

public static void main( String [] args) {

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

int noOfRow = numbers.length;

int noOfColumn = numbers[ 0 ].length;

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

int columnSum = 0 ;

189

Knock the door on [email protected]


USING ARRAY

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

columnSum = columnSum + numbers[j][i];

System .out.println(columnSum);

Output

Frequency=3

Write a program to find sum of each row from two dimention array

public class TwoDimensionalArraySumOfEachRow {

public static void main( String [] args) {

int numbers[][] = {{ 4 , 5 , 9 , 4 }, { 1 , 2 , 6 , 4 }, { 1 , 4 , 9 , 4 }};

int sum = 0 ;

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

sum = 0 ;

for ( int j = 0 ; j < numbers[i].length; j ++ ) {

sum = sum + numbers[i][j];

System .out.println(sum);

Output

22

13

18

Write a program to find greatest number from two dimention array

public class FindMaxNumberFrom2DArray {

public static void main( String [] args) {

int [][] data = {{ 12 , 54 , 51 , 43 }, { 533 , 93 , 23 , 53 }, { 931 , 9 , 3 , 6 }};

int max = data[ 0 ][ 1 ];

190

Knock the door on [email protected]


USING ARRAY

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

for ( int j = 0 ; j < data[i].length; j ++ ) {

if (data[i][j] > max) {

max = data[i][j];

System .out.println(max);

Output

931

191

Knock the door on [email protected]


10

USER DEFINED

METHODS
USER DEFINED METHODS

Write a program to check given number is palindrome or not

Input Output

_____________________________________________________________________

Enter a number : 1441 Palindrom


Example

import java.util.Scanner;

public class PalindromeNumber {

public static void main( String [] args) {

System .out.println( "Enter a number" );

Scanner input = new Scanner( System .in);

int num = input.nextInt();

int reverse = getReverseNumber(num);

if (num == reverse) {

System .out.println( "Palindrome" );

} else {

System .out.println( "Not palindrome" );

static int getReverseNumber( int num) {

int reverse = 0 , lastDigit;

while (num != 0 ) {

lastDigit = num % 10 ;

reverse = reverse * 10 + lastDigit;

num = num / 10 ;

return reverse;

Output

Enter a number

1441

Palindrom

Write a program to print all palindrome numbers from 11 to 200

public class PalindromeFrom11to20 {

public static void main( String [] args) {

for ( int i = 11 ; i <= 200 ; i ++ ) {

if (isPalindromeNumber(i)) {

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

193

Knock the door on [email protected]


USER DEFINED METHODS

static boolean isPalindromeNumber( int num) {

int reverse = 0 , lastDigit, originalNum = num;

while (num != 0 ) {

lastDigit = num % 10 ;

reverse = reverse * 10 + lastDigit;

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

Write a program to print list of prime numbers from 2 to 50

public class PrimeFrom2to50 {

public static void main( String [] args) {

for ( int i = 2 ; i <= 50 ; i ++ ) {

if (isPrime(i)) {

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

static boolean isPrime( int num) {

int divisor = 0 ;

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

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

Knock the door on [email protected]


USER DEFINED METHODS

Write a program to print all armstrong number from 1 to 1000

public class ArmstrongFrom1to1000 {

public static void main( String [] args) {

for ( int i = 2 ; i <= 1000 ; i ++ ) {

if (isArmstrongNumber(i)) {

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

static boolean isArmstrongNumber( int num) {

int sum = 0 , remainder, originalNum = num;

while (num > 0 ) {

remainder = num % 10 ;

sum = sum + remainder * remainder * remainder;

num = num / 10 ;

return originalNum == sum;

Output

153 370 371 407

Write a user defined function fact() that takes one number and return factorial of the

given number

Input Output

_________________________________________________________________

Enter a number : 5 120


Example

import java.util.Scanner;

public class FactMethod {

public static void main( String [] args) {

System .out.println( "Enter a number" );

Scanner input = new Scanner( System .in);

int num = input.nextInt();

System .out.println(fact(num));

195

Knock the door on [email protected]


USER DEFINED METHODS

static int fact( int num) {

int fact = 1 ;

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

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

number is even & return false if number is odd

Input Output

_________________________________________________________________

Enter a number : 23 false


Example

import java.util.Scanner;

public class EvenOddMethod {

public static void main( String [] args) {

System .out.println( "Enter a number" );

Scanner input = new Scanner( System .in);

int num = input.nextInt();

System .out.println(isEven(num));

static boolean isEven( int num) {

if (num % 2 == 0 ) {

return true ;

} else {

return false ;

Output

Enter a number

23

false

196

Knock the door on [email protected]


USER DEFINED METHODS

Write a user defined function getMaxValue() that takes array of integers and return

greatest value from the array

Input Output

_________________________________________________________________

Enter five numbers : 54 76 87 23 43 87


Example

import java.util.Scanner;

public class MaxValueMethod {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five numbers" );

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

numbers[i] = input.nextInt();

System .out.println(getMaxValue(numbers));

static int getMaxValue( int [] numbers) {

int max = numbers[ 0 ];

for ( int num : numbers) {

if (max < num) {

max = num;

return max;

Output

Enter five numbers

54 76 87 23 43

87

Write a user defined function getMinValue() that takes array of integers and return

smallest value from the array

Input Output

_________________________________________________________________

Enter five numbers : 54 76 87 23 43 23


Example

197

Knock the door on [email protected]


USER DEFINED METHODS

import java.util.Scanner;

public class MinValueMethod {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five numbers" );

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

numbers[i] = input.nextInt();

System .out.println(getMinValue(numbers));

static int getMinValue( int [] numbers) {

int min = numbers[ 0 ];

for ( int num : numbers) {

if (min > num) {

min = num;

return min;

Output

Enter five numbers

54 76 87 23 43

23

Write a user defined function getSum() that takes array of integers and return sum of

the array elements

Input Output

_________________________________________________________________

Enter five numbers : 54 76 87 23 43 283


Example

import java.util.Scanner;

public class SumMethod {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int numbers[] = new int [ 5 ];

System .out.println( "Enter five numbers" );

198

Knock the door on [email protected]


USER DEFINED METHODS

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

numbers[i] = input.nextInt();

System .out.println(getMinValue(numbers));

static int getMinValue( int [] numbers) {

int sum = 0 ;

for ( int num : numbers) {

sum = sum + num;

return sum;

Output

Enter five numbers

54 76 87 23 43

283

Write a program to print greatest number out of four numbers using user defined

function (without array)

Input Output

_________________________________________________________________

Enter first numbers: 67 67

Enter second numbers: 23

Enter third numbers: 56


Example

Enter fourth numbers: 43

import java.util.Scanner;

public class GreatestNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

int num1, num2, num3, num4;

System .out.println( "Enter first numbers" );

num1 = input.nextInt();

System .out.println( "Enter second numbers" );

num2 = input.nextInt();

System .out.println( "Enter third numbers" );

num3 = input.nextInt();

System .out.println( "Enter fourth numbers" );

num4 = input.nextInt();

199

Knock the door on [email protected]


USER DEFINED METHODS

System .out.println(getMaxValue(getMaxValue(num1, num2), getMaxValue(num3, num4)));

static int getMaxValue( int num1, int num2) {

if (num1 > num2) {

return num1;

} else {

return num2;

Output

Enter first numbers

67

Enter second numbers

23

Enter third numbers

56

Enter fourth numbers

43

67

Write a user defined function getRev() that takes one String value and return reverse

of that String

Input Output

_________________________________________________________________

Enter the string : Chirag garihC


Example

import java.util.Scanner;

public class ReverseString {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

System .out.println( "Enter the string" );

String str = input.next();

System .out.println(getRev(str));

static String getRev( String str) {

String rev = "" ;

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

rev = rev + str.charAt(i);

return rev;

200

Knock the door on [email protected]


USER DEFINED METHODS

Output

Enter the string

Chirag

garihC

Java program to check given numbers are twin prime or not

Input Output

___________________________________________________________________________________________

Enter the first number : 13 13 11 are twin prime number


Example

Enter the second number : 11

import java.util.Scanner;

public class TwinPrimeNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

System .out.println( "Enter the first number" );

int num1 = input.nextInt();

System .out.println( "Enter the second number" );

int num2 = inputc.nextInt();

if (isPrime(num1) && isPrime(num2) && Math .abs(num2 - num1) == 2 ) {

System .out.println(num1 + " & " + num2 + " are twin prime number" );

} else {

System .out.println(num1 + " & " + num2 + " are not twin prime number" );

static boolean isPrime( int num) {

int divisor = 0 ;

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

if (num % i == 0 ) {

divisor ++ ;

return divisor == 0 ;

Output

Enter the first number

13

Enter the second number

11

13 & 11 are twin prime number

201

Knock the door on [email protected]


11

COLLECTION
COLLECTION

Write a program to print duplicate element from the list

Input Output

____________________________________________________________________________________________

Enter five numbers : 34 54 34 56 54 Duplicate numbers are : 34, 54


Example

import java.util.Scanner;

public class DuplicateFromList {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

System .out.println( "Enter five numbers" );

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

listOfElement.add(input.nextInt());

System .out.println( "Duplicate numbers are " );

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

for ( Integer element : listOfElement) {

if ( ! setOfData.add(element)) {

System .out.println(element);

Output

Enter five numbers

34 54 34 56 54

Duplicate numbers are

34

54

Write a program to print duplicate characters from the given String

Input Output

_______________________________________________________________________________

Enter a String : This is my collection program [ , r, s, c, t, i, l, m, o]


Example

import java.util.Scanner;

public class DuplicateCharFromString {

public static void main( String [] args) {

System .out.println( "Enter a String" );

Scanner input = new Scanner( System .in);

String str = input.nextLine().toLowerCase();

203

Knock the door on [email protected]


COLLECTION

Set <Character> setOfChar = new HashSet <Character> ();

Set <Character> duplicateChar = new HashSet <Character> ();

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

if ( ! setOfChar.add(str.charAt(i))) {

duplicateChar.add(str.charAt(i));

System .out.println(duplicateChar);

Output

Enter a String

This is my collection program

[ , ,r s, c, t, i, l, m, o]

Write a program to print frequency of each character from the String

Input Output

____________________________________________________________________________________________

Enter a String : This is my collection program { =4, a=1, c=2, e=1, g=1, h=1,

i=3, l=2, m=2, n=1, o=3, p=1,


Example

r=2, s=2, t=2, y=1}

import java.util.Scanner;

public class FrequencyOfEachChar {

public static void main( String [] args) {

System .out.println( "Enter a String" );

Scanner input = new Scanner( System .in);

String str = input.nextLine().toLowerCase();

Map <Character , Integer> frequency = new HashMap <> ();

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

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

Knock the door on [email protected]


COLLECTION

Output

This is my collection program

{ =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}

Write a program to print unique characters from the String

Input Output

____________________________________________________________________________

Enter a String : This is my collection program [a, e, g, h, n, p, y]


Example

import java.util.Scanner;

public class FindUniqueChar {

public static void main( String [] args) {

System .out.println( "Enter a String" );

Scanner input = new Scanner( System .in);

String str = input.nextLine().toLowerCase();

Set <Character> uniquChar = new HashSet <> ();

Set <Character> dupChar = new HashSet <> ();

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

if ( ! uniquChar.add(str.charAt(i))) {

dupChar.add(str.charAt(i));

uniquChar.removeAll(dupChar);

System .out.println(uniquChar);

Output

Enter a String

This is my collection program

[a, e, g, h, n, p, y]

Write a program to find character from the String that has a greatest frequency

Input Output

____________________________________________________________________________

Enter a String : java programming with hashmap [a, e, g, h, n, p, y]


Example

import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;

import java.util.Set;

205

Knock the door on [email protected]


COLLECTION

public class ExceptionWithFinally {

public static void main( String [] args) {

System .out.println( "Enter a String" );

Scanner input = new Scanner( System .in);

String str = input.nextLine().toLowerCase();

Map <Character , Integer> frequency = new HashMap <> ();

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

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

Set < Map.Entry <Character , Integer>> listOfPair = frequency.entrySet();

int maxValue = Integer .MIN_VALUE;

char maxChar = 0 ;

for (Map.Entry <Character , Integer> pair : listOfPair) {

if (maxValue < pair.getValue()) {

maxValue = pair.getValue();

maxChar = pair.getKey();

System .out.println(maxChar + " has greatest frequency" );

Output

Enter a String

java programming with hashmap

{ =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}

a has greatest frequency

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

Knock the door on [email protected]


COLLECTION

public class SortElement{

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

System .out.println( "Enter five numbers" );

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

numbers.add(input.nextInt());

Collections.sort(numbers);

System .out.println( "Sorted list: " + numbers);

Output

Enter five numbers

45 67 23 12 43

Sorted list: [12, 23, 43, 45, 67]

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

public class ReverseElementSequence {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

System .out.println( "Enter five numbers" );

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

numbers.add(input.nextInt());

Collections.reverse(numbers);

System .out.println( "Reverse numbers: " + numbers);

Output

Enter five numbers

45 67 23 12 43

Reverse numbers: [43, 12, 23, 67, 45]

207

Knock the door on [email protected]


COLLECTION

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

public class ReverseElement {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

System .out.println( "Enter five numbers" );

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

numbers.add(input.nextInt());

System .out.println( "Reverse elements: " );

for ( int num : numbers) {

System .out.print(getReverse(num) + " " );

public static int getReverse( int num) {

int rev = 0 ;

while (num > 0 ) {

rev = rev * 10 + num % 10 ;

num = num / 10 ;

return rev;

Output

Enter five numbers

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

have entered the exact same numbers ignoring the order

Input Output

________________________________________________________________________

Enter first five element : 45 67 23 12 43 same


Example

Enter second five element : 23 12 67 43 4567, 45

208

Knock the door on [email protected]


COLLECTION

public class SameElements {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

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

System .out.println( "Enter first five numbers" );

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

numbers1.add(input.nextInt());

System .out.println( "Enter second five numbers" );

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

numbers2.add(input.nextInt());

boolean result = numbers1.containsAll(numbers2) && numbers2.containsAll(numbers1);

if (result) {

System .out.println( "Same" );

} else {

System .out.println( "Not same" );

Output

Enter first five numbers

45 67 23 12 43

Enter second five numbers

23 12 67 43 45

Same

Write a program to get five numbers from user twice and print common numbers

from the two list of numbers

Input Output

___________________________________________________________________________________________

Enter first five element: 45 67 23 12 43 Common Numbers: 12, 67, 45


Example

Enter second five element : 22 12 67 40 45

209

Knock the door on [email protected]


COLLECTION

public class FirstClass {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

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

System .out.println( "Enter first five numbers" );

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

numbers1.add(input.nextInt());

System .out.println( "Enter second five numbers" );

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

numbers2.add(input.nextInt());

numbers1.retainAll(numbers2);

System .out.println(numbers1);

Output

Enter first five numbers

45 67 23 12 43

Enter second five numbers

22 12 67 40 45

[45, 67, 12]

Write a program to demonstrate how to convert Set into Array

public class FirstClass {

public static void main( String [] args) {

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

names.add( "Maryam" );

names.add( "Emily" );

names.add( "Tim" );

names.add( "Anna" );

// Converting the HashSet to an array

String [] namesArray = names.toArray( new String [ 0 ]);

// Printing the array

for ( String name : namesArray) {

System .out.println(name);

210

Knock the door on [email protected]


COLLECTION

Output

Emily

Maryam

Tim

Anna

211

Knock the door on [email protected]


12

CLASS AND OBJECT


CLASS AND OBJECT

Write a program to print duplicate element from the list

class Employee {

String employeeName;

int empId;

double salary;

boolean isEligibleForPromotion;

void workOnWeekend() {

System .out.println(employeeName + " Working on Saturday" );

isEligibleForPromotion = true ;

void takeLeave() {

System .out.println(employeeName + " is on leave" );

isEligibleForPromotion = false ;

void displayEmployeeData() {

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

System .out.println(employeeName);

System .out.println(empId);

System .out.println(salary);

System .out.println(isEligibleForPromotion);

public class EmployeeMainClass {

public static void main( String [] args) {

Employee employee1 = new Employee();

Employee employee2 = new Employee();

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

Knock the door on [email protected]


CLASS AND OBJECT

Output

Mike

9454

23500.0

true

Mike is on leave

==================

Mike

9454

23500.0

false

==================

George

6543

5400.0

false

George Working on Saturday

==================

George

6543

5400.0

true

Write a program to demonstrate how to pass object into the method

class Bank {

String accName;

int balance;

void deposit( int amount) {

balance = balance + amount;

class ATM {

void withdraw(Bank b, int amount) {

b.balance = b.balance - amount;

void showBalance(Bank b) {

System .out.println(b.balance);

public class BankMainClass {

public static void main( String [] args) {

Bank account1 = new Bank();

Bank account2 = new Bank();

214

Knock the door on [email protected]


CLASS AND OBJECT

// Set Name for account1

account1.accName = "Mike" ;

account1.deposit( 5000 ); // Deposit method not supported by bank

// Set Name for account2

account2.accName = "George" ;

account2.deposit( 10000 );

// Withdraw 1000 from account1 so 5000-1000=4000 will be left

ATM atm = new ATM();

atm.withdraw(account1, 1000 );

atm.showBalance(account1);

// Check balance in account2

atm.showBalance(account2);

Output

4000

10000

Write a program to demonstrate how to store list of Bank Account objects in the list

and find account that is greatest balance

class Bank {

String accName;

int balance;

void deposit( int amount) {

balance = balance + amount;

public class EmployeeMainClass {

public static void main( String [] args) {

Bank account1 = new Bank();

Bank account2 = new Bank();

Bank account3 = new Bank();

account1.deposit( 5000 );

account2.deposit( 3500 );

account3.deposit( 7200 );

List < Bank > listOfAccount = new ArrayList <> ();

listOfAccount.add(account1);

listOfAccount.add(account2);

listOfAccount.add(account3);

215

Knock the door on [email protected]


CLASS AND OBJECT

int maxBalance = Integer .MIN_VALUE;

for (Bank account : listOfAccount) {

if (maxBalance < account.balance) {

maxBalance = account.balance;

System .out.println( "Greatest Balance is " + maxBalance);

Output

Greatest Balance is 7200

216

Knock the door on [email protected]


13

CONSTRUCTOR

AND

STATIC KEYWORD
CONSTRUCTOR AND STATIC KEYWORD

Write a program to demonstrate use of No Argument Constructor

class Bank {

int accountNumber;

String accName;

int balance;

public Bank() {

balance = 1000 ;

accName = "Mike" ;

accountNumber ++ ;

public void showAccountData() {

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

System .out.println(balance);

System .out.println(accName);

System .out.println(accountNumber);

public class BankMainClass {

public static void main( String [] args) {

Bank account1 = new Bank();

Bank account2 = new Bank();

List < Bank > listOfAccount = new ArrayList <> ();

listOfAccount.add(account1);

listOfAccount.add(account2);

for (Bank account : listOfAccount) {

account.showAccountData();

Output

1000

Mike

================

1000

Mike

218

Knock the door on [email protected]


CONSTRUCTOR AND STATIC KEYWORD

Write a program to demonstrate use of parameterized Constructor

class Bank {

int accountNumber;

String accName;

int balance;

public Bank( int balanceFromUser, String accNameFromUser) {

balance = balanceFromUser;

accName = accNameFromUser;

accountNumber ++ ;

public void showAccountData() {

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

System .out.println(balance);

System .out.println(accName);

System .out.println(accountNumber);

public class BankMainClass {

public static void main( String [] args) {

Bank account1 = new Bank( 5000 , "Mike" );

Bank account2 = new Bank( 1000 , "George" );

List < Bank listOfAccount = new ArrayList <> ();

listOfAccount.add(account1);

listOfAccount.add(account2);

for (Bank account : listOfAccount) {

account.showAccountData();

Output

5000

Mike

================

1000

George

219

Knock the door on [email protected]


CONSTRUCTOR AND STATIC KEYWORD

Write a program to demonstrate use of Static Variable

class Student {

static String instructorName; // Instructor will be same for each student

String mentorName; // Mentor will be different for each student

void showTeacherName() {

System .out.println( "Instructor - " + instructorName);

System .out.println( "Mentor - " + mentorName);

public class StudentTester {

public static void main( String [] args) {

Student student1 = new Student();

Student student2 = new Student();

Student student3 = new Student();

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

Knock the door on [email protected]


CONSTRUCTOR AND STATIC KEYWORD

Write a program to demonstrate use of Static Methods

class Student {

static String instructorName; // Instructor will be same for each student

String mentorName; // Mentor will be different for each student

static void showInstructorName() {

System .out.println( "Instructor - " + instructorName);

void showMentorName() {

System .out.println( "Mentor - " + mentorName);

public class StudentTester {

public static void main( String [] args) {

Student.instructorName = "Instructor1" ;

Student.showInstructorName();

Student student1 = new Student();

student1.mentorName = "Mentor1" ;

student1.showMentorName();

Output

Instructor - Instructor1

Mentor - Mentor1

221

Knock the door on [email protected]


14

INHERITANCE

AND

POLYMORPHISM
INHERITANCE AND POLYMORPHISM

Write a program to demonstrate use of Inheritance

// Parent Class

class BasicCalculator {

public void sum( int a, int b) {

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

public void sub( int a, int b) {

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

// Child Class

class AdvanceCalculator extends BasicCalculator{

public void div( int a, int b) {

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

public void mul( int a, int b) {

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

public class InheritanceExample {

public static void main( String [] args) {

BasicCalculator basic = new BasicCalculator();

basic.sum( 10 , 20 );

basic.sub( 10 , 20 );

AdvanceCalculator ac = new AdvanceCalculator();

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

Knock the door on [email protected]


INHERITANCE AND POLYMORPHISM

Write a program to demonstrate use of Constructor Chaining

class Bank {

Bank() {

System .out.println( "From Bank Class Constructor" );

class ChaseBank extends Bank {

ChaseBank() {

System .out.println( "From Chase Bank Class Constructor" );

public class ConstructorChaining {

public static void main( String [] args) {

ChaseBank chaseBank = new ChaseBank();

Output

From Bank Class Constructor

From Chase Bank Class Constructor

Write a program to demonstrate use of This & Super keyword with variables

class Parent{

int a = 10 ; // instance variable

class Child extends Parent{

int a = 20 ; // instance variable

public void printData(){

int a = 50 ; // local variable

System .out.println(a); // 50

System .out.println( this .a); // 20

System .out.println( super .a); // 10

public class ExampleOfThisAndSuper {

public static void main( String [] args) {

Child c = new Child();

c.printData();

224

Knock the door on [email protected]


INHERITANCE AND POLYMORPHISM

Output

50

20

10

Write a program to demonstrate use of This & Super keyword with Methods

class Parent {

int a = 10 ; // instance variable

public void printData() {

System .out.println(a);

class Child extends Parent {

int a = 20 ; // instance variable

public void printData() {

System .out.println(a);

super .printData();

public class ExampleOfThisAndSuper {

public static void main( String [] args) {

Child c = new Child();

c.printData();

Output

20

10

Write a program to demonstrate use of This & Super keyword with Constructor

class Parent {

Parent() {

System .out.println( "Statement 1" );

225

Knock the door on [email protected]


INHERITANCE AND POLYMORPHISM

class Child extends Parent {

Child() {

this ( "Statement 2" );

System .out.println( "Statement 3" );

Child( String name) {

super ();

System .out.println(name);

System .out.println( "Statement 4" );

public class ExampleOfThisAndSuper {

public static void main( String [] args) {

Child c = new Child();

Output

Statement 1

Statement 2

Statement 4

Statement 3

Write a program to demonstrate use of Method Overloading

class FlightBooking {

public void bookTicket() {

System .out.println( "Booking the ticket" );

public void bookTicket( String name) {

System .out.println( "Booking with name " + name);

public void bookTicket( int seatNumber, String name) {

System .out.println( "Booking with seat " + seatNumber + " and name " + name);

public void bookTicket( String name, int price) {

System .out.println( "Booking with name " + name + " and price " + price);

226

Knock the door on [email protected]


INHERITANCE AND POLYMORPHISM

public void bookTicket( int price) {

System .out.println( "Booking with price " + price);

public class MethodOverloadingExample {

public static void main( String [] args) {

FlightBooking flightBooking = new FlightBooking();

flightBooking.bookTicket();

flightBooking.bookTicket( 200 );

flightBooking.bookTicket( "Mike" );

flightBooking.bookTicket( "Mike" , 200 );

flightBooking.bookTicket( 12 , "Mike" );

Output

Booking the ticket

Booking with price 200

Booking with name Mike

Booking with name Mike and price 200

Booking with seat 12 and name Mike

Write a program to demonstrate use of Method Overriding

class Bank {

int balance;

public void displayInterestRate() {

System .out.println( "6.0" );

class ChaseBank extends Bank {

@ Override

public void displayInterestRate() {

System .out.println( "5.0" );

class WellsFargo extends Bank {

@ Override

public void displayInterestRate() {

System .out.println( "7.0" );

227

Knock the door on [email protected]


INHERITANCE AND POLYMORPHISM

public class MethodOverriding {

public static void main( String [] args) {

ChaseBank cb = new ChaseBank();

cb.displayInterestRate();

WellsFargo wf = new WellsFargo();

wf.displayInterestRate();

Output

5.0

7.0

Write a program to demonstrate use of Dynamic Polymorphism

class Bank {

int balance;

public void displayInterestRate() {

System .out.println( "6.0" );

public void showBalance() {

System .out.println(balance);

class ChaseBank extends Bank {

public void displayInterestRate() {

System .out.println( "5.0" );

class WellsFargo extends Bank {

public void displayInterestRate() {

System .out.println( "7.0" );

class PayPal {

public void viewBalance(Bank b) {

b.showBalance();

228

Knock the door on [email protected]


INHERITANCE AND POLYMORPHISM

public void viewInterestRate(Bank b) {

b.displayInterestRate();

public class DynamicPolymorphism {

public static void main( String [] args) {

ChaseBank chaseBankAccount = new ChaseBank();

WellsFargo wellsFargoAccount = new WellsFargo();

PayPal payPal = new PayPal();

payPal.viewInterestRate(chaseBankAccount);

payPal.viewInterestRate(wellsFargoAccount);

payPal.viewBalance(chaseBankAccount);

payPal.viewBalance(wellsFargoAccount);

Output

5.0

7.0

229

Knock the door on [email protected]


15

ENCAPSULATION

AND

ABSTRACTION
ENCAPSULATION AND ABSTRACTION

Write a program to demonstrate use of Encapsulation

class Bank {

private static int accountNumber;

private int balance;

private String dateOfBirth;

Bank( int balance, String dateOfBirth) {

this .balance = balance;

this .dateOfBirth = dateOfBirth;

accountNumber ++ ;

public int getBalance() {

return balance;

public void setBalance( int balance) {

this .balance = balance;

public int getAccountNumber() {

return accountNumber;

public void setAccountNumber( int accountNumber) {

this .accountNumber = accountNumber;

public String getDateOfBirth() {

return dateOfBirth;

public void setDateOfBirth( String dateOfBirth) {

this .dateOfBirth = dateOfBirth;

public class Encapsulation {

public static void main( String [] args) {

Bank account1 = new Bank( 5000 , "28 May 1991" );

System .out.println(account1.getBalance());

System .out.println(account1.getDateOfBirth());

account1.setDateOfBirth( "08 May 1990" );

System .out.println(account1.getDateOfBirth());

231

Knock the door on [email protected]


ENCAPSULATION AND ABSTRACTION

Output

5000

28 May 1991

08 May 1990

Write a program to demonstrate use of Abstract class

abstract class Bank {

int balance;

abstract void displayRateOfInterest();

void deposit( int amount) {

balance = balance + amount;

class DemoBank extends Bank {

@ Override

void displayRateOfInterest() {

System .out.println( "7.0%" );

void loanBasedOnCreditCardLimit() {

System .out.println( "Loan based on credit limit provided by DemoBank" );

public class DynamicPolymorphism {

public static void main( String [] args) {

DemoBank demoBank = new DemoBank();

demoBank.displayRateOfInterest();

demoBank.loanBasedOnCreditCardLimit();

Output

7.0%

Loan based on credit limit provided by DemoBank

232

Knock the door on [email protected]


ENCAPSULATION AND ABSTRACTION

Write a program to demonstrate use of Interface

interface Page {

// All variable in interface by default public, static, final

int PAGE_LOAD_TIME = 60 ;

// All methods in interface are by default public and abstract

void waitForPageToLoad();

void openPage();

class LoginPage implements Page {

@ Override

public void waitForPageToLoad() {

System .out.println( "Wait for login page to load" );

@ Override

public void openPage() {

System .out.println( "Opening login page" );

class HomePage implements Page {

@ Override

public void waitForPageToLoad() {

System .out.println( "Wait for home page to load" );

@ Override

public void openPage() {

System .out.println( "Opening home page" );

public class MainClass {

public static void main( String [] args) {

Page page = new LoginPage();

page.waitForPageToLoad();

page.openPage();

page = new HomePage();

page.waitForPageToLoad();

page.openPage();

233

Knock the door on [email protected]


ENCAPSULATION AND ABSTRACTION

Output

Wait for login page to load

Opening login page

Wait for home page to load

Opening home page

234

Knock the door on [email protected]


16

EXCEPTION HANDLING
EXCEPTION HANDLING

Write a program to demonstrate use of try catch block

public class ExceptionExample {

public static void main( String [] args) {

int num[] = { 32 , 54 , 21 , 62 , 34 };

Scanner input = new Scanner( System .in);

try {

System .out.println( "Enter first number" );

int a = input.nextInt();

System .out.println( "Enter first number" );

int b = input.nextInt();

System .out.println(a / b);

System .out.println(num[ 5 ]);

} catch (InputMismatchException e) {

System .out.println( "Input should be numbers only" );

} catch (ArithmeticException e) {

System .out.println( "Cannot divide number with zero" );

} catch (Exception e) {

System .out.println( "Something went wrong!" );

System .out.println( "End of program" );

Output

Enter first number

Enter first number

Cannot divide number with zero

End of program

Write a program to demonstrate use of finally keyword

public class ExceptionWithFinally {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

System .out.println( "Enter first number" );

int num1 = input.nextInt();

System .out.println( "Enter second number" );

int num2 = input.nextInt();

236

Knock the door on [email protected]


EXCEPTION HANDLING

try {

System .out.println(num1 / num2);

System .out.println( "This statement get executed if everything goes well" );

} catch (Exception e) {

System .out.println( "This statement get executed only if exception occurs" );

} finally {

System .out.println( "This statement will be executed for sure" );

Output

Enter first number

34

Enter second number

This statement get executed only if exception occurs

This statement will be executed for sure

Write a program to demonstrate use of throw keyword

public class LadderIfElseExample {

public static void main( String [] args) {

System .out.println( "Enter any number from 0 to 6: " );

Scanner input = new Scanner( System .in);

int dayNum = input.nextInt();

if (dayNum == 0 ) {

System .out.println( "Sun" );

} else if (dayNum == 1 ) {

System .out.println( "Mon" );

} else if (dayNum == 2 ) {

System .out.println( "Tues" );

} else if (dayNum == 3 ) {

System .out.println( "Wed" );

} else if (dayNum == 4 ) {

System .out.println( "Thur" );

} else if (dayNum == 5 ) {

System .out.println( "Fri" );

} else if (dayNum == 6 ) {

System .out.println( "Sat" );

} else {

throw new RuntimeException( "Please enter from 0 to 6 only" );

237

Knock the door on [email protected]


EXCEPTION HANDLING

Output

Exception in thread "main" java.lang.RuntimeException: Please enter from 0 to 6 only

at com.java.class38.LadderIfElseExample.main(LadderIfElseExample.java:29)

Write a program to demonstrate use of throws keyword

public class ThrowsKeyword {

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

method3();

public static void method1() throws IOException {

int i = 1 , j = 0 ;

System .out.println(i / j);

public static void method2() throws IOException {

method1();

public static void method3() throws IOException {

method2();

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero

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

Knock the door on [email protected]

You might also like