You are on page 1of 31

Spicer Higher Secondary School

Aundh, Ganeshkind

Pune -411067

“Java Programs”

This project is submitted to the partial fulfillment of the requirement subject


Computer Applications

Submitted By : Priyanshu Pandey

Submitted To :

Std./Sec : X .G

Academic Year: 2021-2022

Date :

________________ ________________

Internal Examiner External Examiner


Index

Sr.No. Topic Page Number

1 If – else

2 Switch

3 Function overloading

4 Constructor

5 String

6 Arrays

7 Special numbers

8 Bibliography
I. If else if (if else ladder)

The selection statements allow to choose the set-of-instructions for execution


depending upon an expression’s truth value. Java provides two types of selection
statements and one of them is the if statement.

i. If
An if statement tests a particular condition; if the condition evaluates
to true, a course-of-action is followed i.e, a statement or set-of-statements
is executed. Otherwise (if the condition evaluates to false), the course-of-
action is ignored.

Format:
if(expression)
statement;

ii. If-else
Another form of it that allows for this kind of either-or condition by providing an else
Clause is known as if-else statement. The if-else statement tests an expression and
depending upon its true value one of the two sets-of-action is executed.

Format:
If(expression)
Statement 1;
Else
Statement 2;
iii. if-else-if:
A common programming construct in java is the if-else-if ladder, which is often also
called the if-else-if staircase because of its appearance.

Format:

if(expression1)
statement 1;
else if(expression2)
statement 2;
else if(expression 3)
statement 3;
:
:
else
statement n;
Program: 1
Design a class name ShowRoom with the following description :
Instance variables/ Data members :
String name – To store the name of the customer
long mobno – To store the mobile number of the customer
double cost – To store the cost of the items purchased
double dis – To store the discount amount
double amount – To store the amount to be paid after discount
Member methods: –
ShowRoom() – default constructor to initialize data members
void input() – To input customer name, mobile number, cost
void calculate() – To calculate discount on the cost of purchased items, based on following
criteria
void display() – To display customer name, mobile number, amount to be paid after discount
Write a main method to create an object of the class and call the above member methods.
Solution.

Cost Discount (in percentage)

Less than or equal to ₹ 10000 5%

More than ₹ 10000 and less than or equal to ₹ 20000 10%

More than ₹ 20000 and less than or equal to ₹ 35000 15%

More than ₹ 35000 20%


Answer:

import java.util.Scanner;

public class ShowRoom


{
private String name;
private long mobno;
private double cost;
private double dis;
private double amount;

public ShowRoom()
{
name = "";
mobno = 0;
cost = 0.0;
dis = 0.0;
amount = 0.0;
}

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter customer name: ");
name = in.nextLine();
System.out.print("Enter customer mobile no: ");
mobno = in.nextLong();
System.out.print("Enter cost: ");
cost = in.nextDouble();
}

public void calculate() {


int disPercent = 0;
if (cost <= 10000)
disPercent = 5;
else if (cost <= 20000)
disPercent = 10;
else if (cost <= 35000)
disPercent = 15;
else
disPercent = 20;

dis = cost * disPercent / 100.0;


amount = cost - dis;
}
public void display() {
System.out.println("Customer Name: " + name);
System.out.println("Mobile Number: " + mobno);
System.out.println("Amout after discount: " + amount);
}

public static void main(String args[]) {


ShowRoom obj = new ShowRoom();
obj.input();
obj.calculate();
obj.display();
}
}

Output:
Enter Mobile number:

9089786866

Enter cost:

1000

Name::priyanshu

Mobile No.::9089786866

Amount::950.0
II. SWITCH
Java provides a multiple – branch selection statement known as switch. This selection statement
successively tests the value of an expression against a list of integer or character constants, for
equality. When a match is found, the statements associated with that constant are executed.

Format:

Switch (expression )
{
case constant1 : statement –sequence1 ;
break ;
case constant : statement – sequence2 ;
break ;
case constant : statement – sequence3 ;
break ;
:
case constant -1 :statement – sequence-1 ;
break ;
[ default : statement – sequence n] ;
}
Program 2:
Display the following pattern using iteration (looping) statement: 1

Answer:
import java.util.Scanner;

public class KnowledgeBoat


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter 1 for letters and Unicode");
System.out.println("Enter 2 to display the pattern");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
switch(ch) {
case 1:
System.out.println("Letters\tUnicode");
for (int i = 65; i <= 90; i++)
System.out.println((char)i + "\t" + i);
break;

case 2:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++)
System.out.print(j + " ");
System.out.println();
}
break;

default:
System.out.println("Wrong choice");
break;
}
}
}
Output:
1. Enter 1 for Unicode:
2. Enter 2 for Pattern:
Enter your choice:
2
1
12
123
1234
12345

Program 3:
Using switch statement, write a menu driven program for the following:

1. To find and display the sum of the series given below:


S = x1 - x2 + x3 - x4 + x5 .......... - x20
(where x = 2)
2. To display the following series:
1 11 111 1111 11111

For an incorrect option, an appropriate error message should be displayed.

Answer:
import java.util.Scanner;

public class KboatSeriesMenu


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Sum of the series");
System.out.println("2. Display series");
System.out.print("Enter your choice: ");
int choice = in.nextInt();

switch (choice) {
case 1:
int sum = 0;
for (int i = 1; i <= 20; i++) {
int x = 2;
int term = (int)Math.pow(x, i);
if (i % 2 == 0)
sum -= term;
else
sum += term;
}
System.out.println("Sum=" + sum);
break;

case 2:
int term = 1;
for (int i = 1; i <= 5; i++) {
System.out.print(term + " ");
term = term * 10 + 1;
}
break;

default:
System.out.println("Incorrect Choice");
break;
}
}
}

Answer:
a) 1. Sum of the series
2. Display series
Enter your choice: 1
Sum=-699050

b) 1. Sum of the series


2. Display series
Enter your choice: 1
Sum=-699050
Program 4:
Special words are those words which start and end with the same letter.
Example: EXISTENCE, COMIC, WINDOW
Palindrome words are those words which read the same from left to right and vice-versa.
Example: MALYALAM, MADAM, LEVEL, ROTATOR, CIVIC
All palindromes are special words but all special words are not palindromes.

Write a program to accept a word. Check and display whether the word is a palindrome or only
a special word or none of them.

Answer:
import java.util.Scanner;

public class KboatSpecialPalindrome


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = in.next();
str = str.toUpperCase();
int len = str.length();

if (str.charAt(0) == str.charAt(len - 1)) {


boolean isPalin = true;
for (int i = 1; i < len / 2; i++) {
if (str.charAt(i) != str.charAt(len - 1 - i)) {
isPalin = false;
break;
}
}

if (isPalin) {
System.out.println("Palindrome");
}
else {
System.out.println("Special");
}
}
else {
System.out.println("Neither Special nor Palindrome");
}

}
}
a) Enter a word: comic
Special
b) Enter a word: comic
Special
c) Enter a word: rotator
Palindrome
III. FUNCTION OVERLOADING
A function name having several definitions in the same scope that are differentiable by
the number or types of their arguments, is said to be an overloaded function. Process of creating
overloaded functions is called function overloading.

Program 5:
Design a class to overload a function sumSeries() as follows:
(i) void sumSeries(int n, double x): with one integer argument and one double argument to find
and display the sum of the series given below:
s=x/1−x/2+x/3−x/4+x/5... ... to n terms
(ii) void sumSeries(): to find and display the sum of the following series:

s=1+(1×2)+(1×2×3)+...  +(1×2×3×4...  ×20)
Answer:
public class KboatOverload
{
void sumSeries(int n, double x) {
double sum = 0;
for (int i = 1; i <= n; i++) {
double t = x / i;
if (i % 2 == 0)
sum -= t;
else
sum += t;
}
System.out.println("Sum = " + sum);
}

void sumSeries() {
long sum = 0, term = 1;
for (int i = 1; i <= 20; i++) {
term *= i;
sum += term;
}
System.out.println("Sum=" + sum);
}
}
Output:
Sum = 6.266666666666666
IV. CONSTRUCTOR
A member function with the same name as its class is called Constructor and it is used to
initialize the objects of that class type with a legal initial value.
Types of Constructors:
(i) Non – Parameterized Constructors:
A constructor that accepts no parameter is called the non- parameterized constructor. Non –
parameterized constructors are considered default constructors.
Format:
class A
{
int I;
public void getval( ){…}
public void prnval ( ){…}
: //member functions definitions
}
class B
{
Public void Test( )
{
A 01 = new A( );
01.getval( );
01.prnval( );
}
}
(ii) Parameterized Constructors:
Parameterized constructors are the ones that receive parameters and initialize objects with
received values.
Format:
class ABC
{
int i;
float j;
char k;
public ABC (int a ,float b ,char c) //parameterized constructor
{
i= a;
j= b;
k= c;
}
: //other members
}

Program 6:
Non-parameterized constructor
Write a program to accept a number and check and display whether it is a Niven number or
not.

Answer:
import java.util.Scanner;

public class KboatNivenNumber


{
public void checkNiven() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int num = in.nextInt();
int orgNum = num;

int digitSum = 0;
while (num != 0) {
int digit = num % 10;
num /= 10;
digitSum += digit;
}
if (digitSum != 0 && orgNum % digitSum == 0)
System.out.println(orgNum + " is a Niven number");
else
System.out.println(orgNum + " is not a Niven number");
}
}

Output:
a) Enter number: 5
5 is a Niven number
b) Enter number: 7777
7777 is not a Niven number
V. STRING FUNCTIONS
Java offers three classes to work with character data:
(i) Character class whose instances or objects can hold single character data.This class offers
many methods to manipulate or inspect single – character data.
(ii) String class whose instances or objects can hold unchanging string(immutable string) i.e.,
once initialized its contents cannot be modified.
(iii) StringBuffer class whose instances or objects can hold strings that can be changed or
modified. Methods used to obtain information about an object are known as accessor
methods.The class string provides many accessor methods that may be used to perform
operations on strings.
Some most used accessor methods of String class:
Method prototype Description
Char charAt(int index) Returns the characters at the specified index.

int capacity( ) Returns maximum no. of characters that can be


entered in the current string object( this ) i.e., its
capacity.
int compareTo(String1, anotherString) Compares two strings lexicographically1.
String concat(String str) Concatenates the specified string to the end of
this string (current String object) string.
str1 + str2 Concatenation operator (i.e., +), achieves same
as concat method.
boolean endswith (String str) Test if the this string ( current String object )
ends with the specified suffix ( str ).

boolean equals ( String str ) Compares the this string (current string object)
to the specified suffix ( str ).

boolean equalsIgnoreCase ( String str ) Compares the this string (current String object)
to ignoring case considerations.

int indexOf ( char ch ) Returns the index2 withing the this string
(current String object ) of the occurrence of the
specified character.

in lastIndexOf ( char ch ) Returns the index within the this string of the
last occurrence of the specified character.

int length ( ) Returns the length of the this string.

String replace ( char oldChar, char newChar) Returns a new string resulting from replacing all
occurrence of oldChar in the this string with
newChar..

Boolean startsWith ( String str ) Tests if the this string starts with the specified
suffix (str).

String substring ( int beginIndex ,intendIndex ) Returns a new string that is a substring of the
this string.

String toLowerCase () Converts all of the characters in the this String


to lower case.

String toString ( ) Returns the string itself.

String toUpperCase ( ) Converts all of the characters in the this String


to upper case.

String trim ( ) Removes white space from both ends of the this
String.

String valueOf ( all types ) Returns string representation of the passed


argument e.g., 12 represemted as “12”

Program 7:
Write a program to input a sentence and convert it into uppercase and count and display the
total number of words starting with a letter 'A'.

Answer:
import java.util.Scanner;

public class WordsWithLetterA


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a string: ");
String str = in.nextLine();
str = " " + str; //Add space in the begining of str
int c = 0;
int len = str.length();
str = str.toUpperCase();
for (int i = 0; i < len - 1; i++) {
if (str.charAt(i) == ' ' && str.charAt(i + 1) == 'A')
c++;
}
System.out.println("Total number of words starting with
letter 'A' = " + c);
}
}

Output:
Enter a string:
MY NAME IS PRIYANSHU
Total number of words starting with letter 'A' = 0
Enter a string:
ADVANCEMENT AND APPLICATION OF INFORMATION TECHNOLOGY ARE EVER
CHANGING
Total number of words starting with letter 'A' = 4

Program 8:
Write a program in Java to accept a string in lower case and change the first letter of every
word to upper case. Display the new string.

Answer:
import java.util.Scanner;

public class KboatString


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
String word = "";

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


if (i == 0 || str.charAt(i - 1) == ' ') {
word += Character.toUpperCase(str.charAt(i));
}
else {
word += str.charAt(i);
}
}

System.out.println(word);
}
}
Output:
Enter a sentence:
my name is priyanshu
My Name Is Priyanshu

VI. ARRAYS
An Array is a collection of variables of the same type that are referenced by a common
name.

Arrays are of different types:


(i) one – dimensional arrays : comprised of finite homogeneous elements.

Format:
type array-name[ ]= new type[ size]; or type[ ] arrayname = new type [size]
(ii) multi-dimensional arrays : comprised of elements , each of which is itself an array.

Format:
type array-name[ ] [ ] = new type [row] [columns];
or as
type [ ] [ ] array-name =new type [rows] [ columns];

Program 9:
Write a program to input twenty names in an array. Arrange these names in descending order
of letters, using the bubble sort technique.

Answer:
import java.util.Scanner;
public class KboatArrangeNames
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String names[] = new String[20];
System.out.println("Enter 20 names:");
for (int i = 0; i < names.length; i++) {
names[i] = in.nextLine();
}

//Bubble Sort
for (int i = 0; i < names.length - 1; i++) {
for (int j = 0; j < names.length - 1 - i; j++) {
if (names[j].compareToIgnoreCase(names[j + 1]) < 0) {
String temp = names[j + 1];
names[j + 1] = names[j];
names[j] = temp;
}
}
}

System.out.println("\nSorted Names");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
}
}

Output:
Enter 20 names:
Priyanshu
Manvanth
Gelin
Sujal
Aiti
Manaswi
Shirish
Neil
Keerthana
Gautham
Diyanshu
Ruturah
Shev
Aayushi
Aayush
Shivraj
Sarthak
Adrika
Leena
Virendra

Sorted Names
Virendra
Sujal
Shivraj
Shirish
Shev
Sarthak
Ruturah
Priyanshu
Neil
Manvanth
Manaswi
Leena
Keerthana
Gelin
Gautham
Diyanshu
Aiti
Adrika
Aayushi
Aayush

Searching:
Sometimes you need to search for an element in an array. To accomplish this task , you can use
different searching techniques. It consists of two very common search techniques viz ., linear
search and binary search.

(i) Binary Search:


Binary Search is a search technique that works for sorted arrays. Here search item is compared
with the middle element of the array. If the search- item matches with the element , search
finishes. If the search – item is less than the middle perform (in ascending order) perform binary
search in the first half of the array , otherwise perform binary search in the latter half of the
array.

Program 10:
Write a program to accept the year of graduation from school as an integer value from the user.
Using the binary search technique on the sorted array of integers given below, output the
message "Record exists" if the value input is located in the array. If not, output the message
"Record does not exist".
Sample Input:

n[0] n[1] n[2] n[3] n[4] n[5] n[6] n[7] n[8] n[9]

1982 1987 1993 1996 1999 2003 2006 2007 2009 2010

Answer:
import java.util.Scanner;

public class KboatGraduationYear


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n[] = {1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007,
2009, 2010};

System.out.print("Enter graduation year to search: ");


int year = in.nextInt();

int l = 0, h = n.length - 1, idx = -1;


while (l <= h) {
int m = (l + h) / 2;
if (n[m] == year) {
idx = m;
break;
}
else if (n[m] < year) {
l = m + 1;
}
else {
h = m - 1;
}
}

if (idx == -1)
System.out.println("Record does not exist");
else
System.out.println("Record exists");
}
}

Output:
Enter graduation year to search: 1999
Record exists
Enter graduation year to search: 2020
Record does not exist
Sorting:
Sorting of an array means arranging the array elements in a specified order i.e., either ascending
or descending order. There are several sorting techniques available e.g., shell sort,
shuttle sort, bubble sort, selection sort, quick sort, heap sort, etc. But the most popular techniques
are selection sort and bubble sort.

(i) Bubble Sort


The idea of bubble sort is to move the largest element to the highest index position in the array.
To attain this, two adjacent elements are compared repeatedly and exchanged if they are not in
the correct order.

Program 11:
Write a program to input 10 integer elements in an array and sort them in descending order
using bubble sort technique.

Answer:
import java.util.Scanner;

public class KboatBubbleSortDsc


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = 10;
int arr[] = new int[n];

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


for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}

//Bubble Sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
}
}
}

System.out.println("Sorted Array:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}

Output:
Enter the elements of the array:
78
67
45
34
90
89
23
12
78
03
Sorted Array:
90 89 78 78 67 45 34 23 12 3
VII. SPECIAL NUMBER PROGRAM
Program 12:
A special two-digit number is such that when the sum of its digits is added to the product of its
digits, the result is equal to the original two-digit number.
Write a program to accept a two-digit number. Add the sum of its digits to the product of its
digits. If the value is equal to the number input, then display the message "Special two—digit
number" otherwise, display the message "Not a special two-digit number".

Answer:
import java.util.Scanner;

public class KboatSpecialNumber


{
public void checkNumber() {

Scanner in = new Scanner(System.in);

System.out.print("Enter a 2 digit number: ");


int orgNum = in.nextInt();

int num = orgNum;


int count = 0, digitSum = 0, digitProduct = 1;

while (num != 0) {
int digit = num % 10;
num /= 10;
digitSum += digit;
digitProduct *= digit;
count++;
}

if (count != 2)
System.out.println("Invalid input, please enter a 2-digit
number");
else if ((digitSum + digitProduct) == orgNum)
System.out.println("Special 2-digit number");
else
System.out.println("Not a special 2-digit number");

}
}
Output:
Enter a 2 digit number: 34
Not a special 2-digit number
Enter a 2 digit number: 59
Special 2-digit number
BIBLIOGRAPHY
 ICSE solved papers last10 years

You might also like