KEMBAR78
Java Coding Programs - Chirag Khimani | PDF | Class (Computer Programming) | Control Flow
0% found this document useful (1 vote)
170 views243 pages

Java Coding Programs - Chirag Khimani

Java_Coding_Programs_-_Chirag_Khimani
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 (1 vote)
170 views243 pages

Java Coding Programs - Chirag Khimani

Java_Coding_Programs_-_Chirag_Khimani
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

OceanofPDF.

com

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,
OceanofPDF.com
OceanofPDF.com

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


OceanofPDF.com

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


OceanofPDF.com

JAVA BASICS

PROGRAMS
OceanofPDF.com
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)

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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);

O u tp u t

127

128

500

1032423

1.5

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

O u tp u t

10.0

10

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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);

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

O u tp u t

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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);

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 contact@chiragkhimani.com


OceanofPDF.com

JAVA OPERATORS
OceanofPDF.com
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);

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

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
JAVA OPERATORS

Output

Enter first number

10

Enter second number

20

Enter third number

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

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

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
JAVA OPERATORS

// Take principle amount from user

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

principleAmount = input.nextDouble();

// Take rate of interest from user

Output

Enter Principle Amount

1000

Enter rate of interest

6.5

Enter number of years

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

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

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

10

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

Output

Enter value of num1

10

Enter value of num2

20

Values after swapping

11

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

Output

Enter value of num1

10

Enter value of num2

20

Values after swapping

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 contact@chiragkhimani.com


OceanofPDF.com
JAVA OPERATORS

public static void main(String[] args ) {

// Create an object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

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

13

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

Output

Enter first subject marks

60

Enter second subject marks

70

Enter third subject marks

14

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

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

15

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

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

16

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

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 contact@chiragkhimani.com


OceanofPDF.com
JAVA OPERATORS

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

// Variable Declaration

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

18

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

___________________________________________
Data

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

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 contact@chiragkhimani.com


OceanofPDF.com
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);

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

20

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

Output

Enter your weight in Kilogram

72

Enter your height in centimeter

172

Your BMI units are 24.337479718766904

21

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

Output

Enter the length of the cube

12

Enter the width of the cube

12

Enter the height of the cube

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


Data

22

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
JAVA OPERATORS

import java.util.Scanner;

public class VolumeOfCuboid{

public static void main(String[] args ) {

// Create an object of Scanner class

Output

Enter your basic salary

3500

Total Salary = 9020.0

23

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

CONDITIONAL

STATEMENTS
OceanofPDF.com
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

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

25

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

Output

Enter first number

34

Enter second number

12

34 is greatest

26

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

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
Example

import java.util.Scanner;

public class NumberOfDaysInMonth{

public static void main(String[] args ) {

// Create an object of Scanner class

27

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

int month = input.nextInt();

if (month == 1) {

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

} else if (month == 2) {

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
Example

28

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

import java.util.Scanner;

public class SwitchNumberOfDaysInMonth{

public static void main(String[] args ) {

// Create an object of Scanner class

Output

Enter a month number

31 days

29

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

Write a program to print name of the day from the given number

Input Output

____________________________

0 Sunday
Example

import java.util.Scanner;

public class NumberOfDaysInMonth{

public static void main(String[] args ) {

// Create an object of Scanner class

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 contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

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

Marks Grade

____________________________

90 to 100 A+
Example

import java.util.Scanner;

public class GradeSystem{

public static void main(String[] args ) {

// Create an object of Scanner class

Output

Enter your total marks

55

C+

31

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

_______________________________________
Example

import java.util.Scanner;

public class DiscountedBill{

public static void main(String[] args ) {

// Create an object of Scanner class

Output

Enter the bill amount

9500

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

32

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

Output

Enter first number

33

Enter second number

53

Enter third number

Write a Program to check given character is vowel or not

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

Input Output

__________________________________________
Example

33

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

import java.util.Scanner;

public class CheckVowel{

public static void main(String[] args ) {

char c = ‘ r ’;

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

__________________________________________
Example

import java.util.Scanner;

public class CalculatorUsingSwitch{

public static void main(String[] args ) {

// Create an object of Scanner class

34

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

switch ( choice ) {

case “Add”:

System. out .println(num1 + num2);

break ;

Output

Enter first number

13

Enter second number

15

Enter operation you want to perform

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

message based on entered username and password

dbUsername dbPassword
Data
Example

35

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

public class LoginValidation {

public static void main(String args []) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

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
Example

36

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

import java.util.Scanner;

public class Rating {

public static void main(String[] args ) {

// Create object of Scanner class

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

__________________________________________
Example

37

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

import java.util.Scanner;

public class CountNotes {

public static void main(String[] args ) {

// Create object of Scanner class

38

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

________________________________________________________________________________
Data
Example

import java.util.Scanner;

public class ElectricityBill {

public static void main(String[] args ) {

// Create object of Scanner class

Output

Enter number of units

672

Total Bill Amount=791.2

39

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

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

user

Team Captain

______________________________________________
Data
Example

public class FifaCaptain {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

40

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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
Example

public class FlightCheckin {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

41

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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
Example

public class HotelCheckin {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

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 contact@chiragkhimani.com


OceanofPDF.com
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);

Output

Enter marks of subject 1

80

Enter marks of subject 2

75

Enter marks of subject 3

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

_________________________________
Data

43

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

public class ShippingCost {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

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


Data

public class ObesityLevel {

public static void main(String[] args ) {

// Create object of Scanner class

Scanner input = new Scanner(System.in);

44

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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 ”);

Output

Enter your weight in Kilogram

72

Enter your height in centimeter

170

Your BMI units are 24.913494809688583

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

45

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONDITIONAL STATEMENTS

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

num2 = input.nextInt();

if (num1 < num2) {

System. out .println(num1 + “ 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

Output

Enter your age

17

You are a teenager

46

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

Output

Enter the first number

32

Enter the second number

54

Enter the third number

47

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

_______________________________________________________
Data

import java.util.Scanner;

public class RateOfInterestOnFD {

public static void main(String[] args ) {

// Create object of Scanner class

Output

Enter your age

54

Enter the amount

35000

7.0%

48

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

___________________________________________________________________________________
Data

import java.util.Scanner;

public class BloodDonation {

public static void main(String[] args ) {

// Create object of Scanner class

Output

Enter your age

43

Enter your weight

65

You are eligible

49

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

_______________________________________________________________________________
Data

import java.util.Scanner;

public class CreditLimit {

public static void main(String[] args ) {

// Create object of Scanner class

50

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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%
Data

import java.util.Scanner;

public class IncomeTax {

public static void main(String[] args ) {

// Create object of Scanner class

51

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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 contact@chiragkhimani.com


OceanofPDF.com

FOR LOOP
OceanofPDF.com
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

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 contact@chiragkhimani.com


OceanofPDF.com
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 contact@chiragkhimani.com


OceanofPDF.com
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++) {

O u tp u t

5*1=5

5*2=10

5*3=15

5*4=20

5*5=25

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 contact@chiragkhimani.com


OceanofPDF.com
FOR LOOP

O u tp u t

12

15

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

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;

57

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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++) {

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

O u tp u t

593

58

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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++) {

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

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 contact@chiragkhimani.com


OceanofPDF.com
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;

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

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

60

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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
Example

import java.util.Scanner;

public class FindFactorsOfNumber {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

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 contact@chiragkhimani.com


OceanofPDF.com
FOR LOOP

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

divisors, excluding the number itself

Input Output

____________________________
Example

import java.util.Scanner;

public class PerfectNumber {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

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 contact@chiragkhimani.com


OceanofPDF.com
FOR LOOP

import java.util.Scanner;

public class PrimeNumber {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

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

63

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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--) {

O u tp u t

11

20

28

35

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

64

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
FOR LOOP

O u tp u t

16

65

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

WHILE LOOP
OceanofPDF.com
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;

Output

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

67

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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) {

Output

16

Write a program to print each digit of the number into separate line in reverse order

Input Output

____________________________

5232 2
Example

68

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
WHILE LOOP

import java.util.Scanner;

public class DisplayDigit {

public static void main(String[] args ) {

// Take a number from user

Output

Please enter any number

35434

Write a program to count number of digits in given number

Input Output

____________________________

5232 4
Example

import java.util.Scanner;

public class CountDigit {

public static void main(String[] args ) {

// Take a number from user

69

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
WHILE LOOP

Scanner input = new Scanner(System.in);

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

int num = input.nextInt();

int count =0;

Output

Please enter any number

45448

Write a program to print sum of each digits from the given number

Input Output

____________________________

5232 12
Example

import java.util.Scanner;

public class SumOfDigit {

public static void main(String[] args ) {

// Take a number from user

70

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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
Example

import java.util.Scanner;

public class FindMaxDigitFromNumber {

public static void main(String[] args ) {

// Take a number from user

71

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
WHILE LOOP

Output

Please enter any number

346454

Write a program to print reverse of the given number

Input Output

____________________________

73453 35337
Example

import java.util.Scanner;

public class ReverseGivenNumber {

public static void main(String[] args ) {

// Take a number from user

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 contact@chiragkhimani.com


OceanofPDF.com
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

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
Example

import java.util.Scanner;

public class FibonaciiSeries {

73

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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();

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

_________________________________________
Example

import java.util.Scanner;

public class ArmstrongNumber {

public static void main(String[] args ) {

// Take a number from user

74

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
WHILE LOOP

while (num > 0) {

lastDigit = num % 10;

sum = sum + lastDigit * lastDigit * lastDigit;

num = num / 10;

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

75

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

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

import java.util.Scanner;

public class SumOfDigitTillSingleDigit {

76

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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();

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
Example

import java.util.Scanner;

public class MagicNumber {

public static void main(String[] args ) {

// Take a number from user

77

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
WHILE LOOP

int sum = 0;

while (num > 0) {

while (num > 0) {

sum = sum + num % 10;

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

_________________________________________
Example

import java.util.Scanner;

public class SpyNumbert {

public static void main(String[] args ) {

// Take a number from user

78

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
WHILE LOOP

int lastDigit = num % 10;

sum = sum + lastDigit;

product = product * lastDigit;

num = num / 10;

Output

Please enter a number

217

It is not Spy Number

79

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

DO WHILE LOOP
OceanofPDF.com
DO WHILE LOOP

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

Input Output

_______________________________________________________________

10 20 30
Example

import java.util.Scanner;

public class AdditionUsingDoWhile {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

Output

Please enter two values

10 20

30

81

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
DO WHILE LOOP

Do you want to perform more operation?

Press 1 for yes

Press 2 for No

Please enter two values

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

Input Output

_______________________________________________________________

20 Not prime
Example

import java.util.Scanner;

public class CheckPrimenUsingDoWhile {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

82

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

Output

Please enter any number

20

Not Prime

Do you want to perform more operation?

Write a program to Develop ATM machine algorithm using do while loop that supports

three operation

1. Withdraw

2. Deposit

83

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
DO WHILE LOOP

import java.util.Scanner;

public class ATMMachine {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

84

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
DO WHILE LOOP

Output

Enter initial balance

10000

Select an operation to perform

1. Withdraw

2. Deposit

85

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

NESTED LOOP
OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

12345

12345

12345

87

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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);

88

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int counter = 1, numOfRows = 5;

boolean isDecrementActivated = false;

89

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

System. out . print ln();

1 2 3 4 5

2 4 6 8 10

3 6 9 12 15

4 8 12 16 20

90

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

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

A A A A A

B B B B B

C C C C C

D D D D D

91

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

public static void main( String[] args ) {

int numOfRows = 5;

char ch = ‘ A ’;

J J J J

A A A A

V V V V

A A A A

92

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

93

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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) {

94

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

95

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

System. out . print (“ 0 ”);

} else {

System. out . print (“ 1 ”);

* * * * *

* *

* *

* *

96

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

* * * * *

* * * * *

* *

* *

* * * * *

* * * * *

* *

* *

97

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

System. out . print (J);

System. out . print ln();

98

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

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

System. out . print (“ * ”);

99

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

100

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

21

321

4321

101

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

1 0

1 0 0

102

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

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

12

123

1234

22

333

4444

103

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

**

***

****

104

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

CH

CHI

CHIR

54

543

5432

105

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

45

345

2345

106

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

11

000

1111

10

100

1000

107

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

222

33333

4444444

108

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

System. out . print (i);

System. out . print ln();

***

*****

*******

111

00000

1111111

109

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

121

12321

1234321

110

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

System. out . print (j);

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

101

11011

1110111

111

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

5
5

545
545

54345
54345

5432345

454

34543

2345432

112

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

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

System. out . print (“ “);

CHC

CHIHC

CHIRIHC

113

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

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

101

10001

1000001

114

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

12345

1234

123

115

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

*****

****

***

116

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

12345

2345

345

117

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

54321

4321

321

118

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

System. out . print ln();

12345

1234

123

12

55555

4444

333

22

119

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

*****

****

***

**

120

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

54321

5432

543

54

12345

2345

345

45

121

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

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

System. out . print (“ “);

11111

2222

333

44

122

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

54321
54321

4321
4321

321
321

21

CHIRAG

CHIRA

CHIR

CHI

123

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

System. out . print (“ “);

CHIRAG

HIRAG

IRAG

RAG

124

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

555555555
555555555

4444444
4444444

33333
33333

222

123454321

1234321

12321

121

125

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

System. out . print (j);

000000000

1111111

00000

111

126

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

*********

*********

*******

*******

*****

*****

***

543212345

5432345

54345

545

127

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

System. out . print (j);

123454321

2345432

34543

454

128

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

CHIRAGARIHC

CHIRARIHC

CHIRIHC

100000001

1000001

10001

101

129

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

int numOfRows = 5;

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

222

33333

4444444

130

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

System. out . print (i);

***

*****

*******

131

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

System. out . print (“ * ”);

111

00000

1111111

132

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

System. out . print (“ “);

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

121

12321

1234321

133

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

int numOfRows = 5;

134

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

0
0

101
101

11011
11011

1110111

135

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

} else {

System. out . print (“ 1 ”);

545

54345

5432345

136

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

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

System. out . print (“ “);

137

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

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

System. out . print (j);

CHC

CHIHC

CHIRIHC

138

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

public class Pattern {

public static void main( String[] args ) {

Scanner input = new Scanner(System.in);

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

139

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

Write a program to print following pattern in the output

1
1

101
101

10001
10001

1000001

140

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
NESTED LOOP

System. out . print (“1”);

} else {

System. out . print (“0”);

141

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

STRING PROGRAM
OceanofPDF.com
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);

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


Example

import java.util.Scanner;

public class CountDigitCharAndSpace {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

143

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

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

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

switch (str.charAt(i)) {

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 contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

import java.util.Scanner;

public class CountNumberOfVowels {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

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

145

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

import java.util.Scanner;

public class FrequencyOfChar {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

Output

Enter a String

This is my java program

Enter a character

146

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

Write a program to print reverse of given String

Input Output

___________________________________________
Example

import java.util.Scanner;

public class FindReverseOfGivenString {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

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 contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

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

String name = input.nextLine();

Output

Enter your name

Elon Musk

Initials - E.M.

Write a program to count number of spaces from the String

Input Output

_____________________________________________________
Example

import java.util.Scanner;

public class CountNumberOfSpacest {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

148

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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
Example

import java.util.Scanner;

public class AnagramString {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

Output

Enter first string

Earth

149

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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
Example

import java.util.Scanner;

public class PalindromeString {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

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 contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

import java.util.Scanner;

public class FindDuplicateCharacters {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

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


Example

import java.util.Scanner;

public class FindDuplicateWord {

151

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

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

String str = input.nextLine();

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


Example

import java.util.Scanner;

public class LargetstWord {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

152

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

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

// initialize first word length as max length

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

String maxString = null;

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


Example

import java.util.Scanner;

public class SmallestWord {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

153

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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];

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


1
APPROACH

import java.util.Scanner;
2

public class FirstClass {

public static void main(String[] args ) {


APPROACH

154

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

Scanner input = new Scanner(System.in);

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

String str = input.nextLine();

int count = 0;

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

Output

Enter the string

java revision notes and java programming puzzules

155

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

java 4

revision 8

notes 5

and 3

java 4

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\


Example

import java.util.Scanner;

public class ReplaceSpaceWithSlash {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

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
Example

156

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

import java.util.Scanner;

public class CaeserCipher {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

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


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 contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

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

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

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

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

158

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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


Example

import java.util.Scanner;

public class UniqueWord {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

159

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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);

Output

Enter the string

Yo banana boy

Palindrome

Write a program to compress the given String

160

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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);

Output

Enter the string

aaabcccddddd

a3

b1

c3

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 contact@chiragkhimani.com


OceanofPDF.com
STRING PROGRAM

import java.util.Scanner;

public class ReverseSequenceOfWord {

public static void main(String[] args ) {

Scanner input = new Scanner(System.in);

Output

Enter the string

Learning java is now feels easy

easy feels now is java Learning

162

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

USING ARRAY
OceanofPDF.com
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

import java.util.Scanner;

public class FindIndexOfNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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 contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

import java.util.Scanner;

public class MaxNumberFromArray {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

165

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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);

166

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

_____________________________________________________________________
Example

import java.util.Scanner;

public class CountPositveAndNegativeNumbersFromArray {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

Output

Enter five numbers

56 -24 -75 43 65

167

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

import java.util.Scanner;

public class NumberContains {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

Output

Enter five numbers

56 -24 -75 43 65

Enter number to find

65

65 is in the array

168

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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);

Output

Enter five numbers

54 54 54 56 56

54

56

169

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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);

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

170

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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,

Output

Enter five numbers

45 23 76 23 56

Sorted Array

23

23

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

171

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

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

numbers[i] = input.nextInt();

int count = 1 ;

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
Example

import java.util.Scanner;

public class SegregateOddEven {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

172

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

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

numbers[i] = input.nextInt();

int left = 0 , right = numbers.length - 1 ;

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

_____________________________________________________________________
Example

173

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

import java.util.Scanner;

public class TwoElementSumIsEqualToGivenNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

import java.util.Scanner;

public class RemoveElement {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

174

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

System .out.println( "Enter five numbers" );

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

numbers[i] = input.nextInt();

Output

Enter five numbers

52 54 13 77 80

Enter the number to remove

13

Result Array

175

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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


Example

import java.util.Scanner;

public class InsertElement {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

176

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

Output

Enter five numbers

52 54 13 77 80

Enter the number to insert

12

Enter the position

Write a program to convert each element of an array in reverse order for integer

array

Input Output

_________________________________________________________________________________________
Example

import java.util.Scanner;

public class EachNumbersInReverseOrder {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

177

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

import java.util.Scanner;

public class EachStringInReverseOrder {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

Output

Enter five Strings

Java Python C# C++ Ruby

Result Array

avaJ nohtyP #C ++C ybuR

178

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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


Example

import java.util.Scanner;

public class CommonElements {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

Output

Test Case 1

Enter five elements for array 1

52 54 13 77 32

Enter five elements for array 2

179

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

Test Case 2

Enter five elements for array 1

15 15 15 15 15

Enter five elements for array 2

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

180

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

// Find the number of unique elements in the array

int noOfUniqueElement = 0 ;

for ( int num : numbers) {

if (num != Integer .MAX_VALUE) {

noOfUniqueElement ++ ;

Output

Enter five elements

56 56 76 56 43

Result Array

76

56

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

181

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

int max = Integer .MIN_VALUE;

int secondMax = Integer .MIN_VALUE;

for ( int num : numbers) {

if (max < num) {

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

182

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

} else if (secondMin > num && num != min) {

secondMin = num;

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

Output

Enter five elements

56 56 76 56 43

43

183

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

_________________________________________________________________________________________
Example

import java.util.Scanner;

public class MoveZeros {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

Output

Enter five elements

31 0 34 0 0

Result Array

31 34 0 0 0

184

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

____________________________________________________________________________________
Example

import java.util.Scanner;

public class CountOddEven {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

__________________________________________________________________
Example

185

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

import java.util.Scanner;

public class SumOfElementExceptSmallestAndLargest {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

______________________________________________________________________________________
Example

186

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

import java.util.Scanner;

public class LCS {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

__________________________________________________________________
Example

187

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

import java.util.Scanner;

public class SumOfNumCloseToZero {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

__________________________________________________________________
Example

188

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USING ARRAY

import java.util.Scanner;

public class MaximumProduct {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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;

189

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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 ;

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 contact@chiragkhimani.com


OceanofPDF.com
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];

Output

931

191

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

10

USER DEFINED

METHODS
OceanofPDF.com
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" );

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 contact@chiragkhimani.com


OceanofPDF.com
USER DEFINED METHODS

static boolean isPalindromeNumber( int num) {

int reverse = 0 , lastDigit, originalNum = num;

while (num != 0 ) {

lastDigit = num % 10 ;

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

Output

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

194

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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 + " " );

Output

153 370 371 407

Write a user defined function fact() that takes one number and return factorial of the

given number

Input Output

_________________________________________________________________
Example

import java.util.Scanner;

public class FactMethod {

public static void main( String [] args) {

System .out.println( "Enter a number" );

195

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USER DEFINED METHODS

static int fact( int num) {

int fact = 1 ;

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

fact = fact * i;

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

_________________________________________________________________
Example

import java.util.Scanner;

public class EvenOddMethod {

public static void main( String [] args) {

System .out.println( "Enter a number" );

Output

Enter a number

23

false

196

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USER DEFINED METHODS

Write a user defined function getMaxValue() that takes array of integers and return

greatest value from the array

Input Output

_________________________________________________________________
Example

import java.util.Scanner;

public class MaxValueMethod {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

_________________________________________________________________
Example

197

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USER DEFINED METHODS

import java.util.Scanner;

public class MinValueMethod {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

_________________________________________________________________
Example

import java.util.Scanner;

public class SumMethod {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

198

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USER DEFINED METHODS

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

numbers[i] = input.nextInt();

System .out.println(getMinValue(numbers));

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

_________________________________________________________________
Example

import java.util.Scanner;

public class GreatestNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

199

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
USER DEFINED METHODS

System .out.println(getMaxValue(getMaxValue(num1, num2), getMaxValue(num3, num4)));

static int getMaxValue( int num1, int num2) {

if (num1 > num2) {

Output

Enter first numbers

67

Enter second numbers

23

Enter third numbers

Write a user defined function getRev() that takes one String value and return reverse

of that String

Input Output

_________________________________________________________________
Example

import java.util.Scanner;

public class ReverseString {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

200

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

import java.util.Scanner;

public class TwinPrimeNumber {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

Output

Enter the first number

13

Enter the second number

11

13 & 11 are twin prime number

201

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

11

COLLECTION
OceanofPDF.com
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);

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

203

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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))) {

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

import java.util.Scanner;

public class FrequencyOfEachChar {

public static void main( String [] args) {

System .out.println( "Enter a String" );

204

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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" );

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 contact@chiragkhimani.com


OceanofPDF.com
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();

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 contact@chiragkhimani.com


OceanofPDF.com
COLLECTION

public class SortElement{

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

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

___________________________________________________________________________________________
Example

public class ReverseElementSequence {

public static void main( String [] args) {

Scanner input = new Scanner( System .in);

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

Output

Enter five numbers

45 67 23 12 43

Reverse numbers: [43, 12, 23, 67, 45]

207

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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> ();

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

________________________________________________________________________
Example

208

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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> ();

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

___________________________________________________________________________________________
Example

209

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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> ();

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

210

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
COLLECTION

Output

Emily

Maryam

Tim

Anna

211

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

12

CLASS AND OBJECT


OceanofPDF.com
CLASS AND OBJECT

Write a program to print duplicate element from the list

class Employee {

String employeeName;

int empId;

double salary;

boolean isEligibleForPromotion;

213

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CLASS AND OBJECT

Output

Mike

9454

23500.0

true

Mike is on leave

Write a program to demonstrate how to pass object into the method

class Bank {

String accName;

int balance;

void deposit( int amount) {

214

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CLASS AND OBJECT

// Set Name for account1

account1.accName = "Mike" ;

account1.deposit( 5000 ); // Deposit method not supported by bank

// Set Name for 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) {

215

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CLASS AND OBJECT

int maxBalance = Integer .MIN_VALUE;

for (Bank account : listOfAccount) {

if (maxBalance < account.balance) {

maxBalance = account.balance;

Output

Greatest Balance is 7200

216

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

13

CONSTRUCTOR

AND
OceanofPDF.com
CONSTRUCTOR AND STATIC KEYWORD

Write a program to demonstrate use of No Argument Constructor

class Bank {

int accountNumber;

String accName;

int balance;

Output

1000

Mike

================

1000

218

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
CONSTRUCTOR AND STATIC KEYWORD

Write a program to demonstrate use of parameterized Constructor

class Bank {

int accountNumber;

String accName;

int balance;

Output

5000

Mike

================

1000

219

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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() {

Output

Instructor - Instructor3

Mentor - Mentor1

Instructor - Instructor3

Mentor - Mentor2

Instructor - Instructor3

220

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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() {

Output

Instructor - Instructor1

Mentor - Mentor1

221

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

14

INHERITANCE

AND
OceanofPDF.com
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));

Output

sum=30

sub=-10

sum=30

Mul=200

sub=-10

223

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
INHERITANCE AND POLYMORPHISM

Write a program to demonstrate use of Constructor Chaining

class Bank {

Bank() {

System .out.println( "From Bank Class Constructor" );

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{

224

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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);

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 contact@chiragkhimani.com


OceanofPDF.com
INHERITANCE AND POLYMORPHISM

class Child extends Parent {

Child() {

this ( "Statement 2" );

System .out.println( "Statement 3" );

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

226

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
INHERITANCE AND POLYMORPHISM

public void bookTicket( int price) {

System .out.println( "Booking with price " + price);

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

227

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
INHERITANCE AND POLYMORPHISM

public class MethodOverriding {

public static void main( String [] args) {

ChaseBank cb = new ChaseBank();

cb.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" );

228

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
INHERITANCE AND POLYMORPHISM

public void viewInterestRate(Bank b) {

b.displayInterestRate();

Output

5.0

7.0

229

Knock the door on contact@chiragkhimani.com


OceanofPDF.com

15

ENCAPSULATION

AND
OceanofPDF.com
ENCAPSULATION AND ABSTRACTION

Write a program to demonstrate use of Encapsulation

class Bank {

private static int accountNumber;

private int balance;

private String dateOfBirth;

231

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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();

Output

7.0%

Loan based on credit limit provided by DemoBank

232

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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

233

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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 contact@chiragkhimani.com


OceanofPDF.com

16

EXCEPTION HANDLING
OceanofPDF.com
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);

Output

Enter first number

Enter first number

Cannot divide number with zero

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

236

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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" );

Output

Enter first number

34

Enter second number

This statement get executed only if exception occurs

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

237

Knock the door on contact@chiragkhimani.com


OceanofPDF.com
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();

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 contact@chiragkhimani.com

You might also like